Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
Axiom pinpointing and provenance semirings, over the derivation DAG the reasoner already builds (#153)
Fabio Rovai06ce8fa2816d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c720d104..99612cf3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -408,6 +408,14 @@ jobs:run: OO_REQUIRE_FIXTURES=1 cargo test --test shacl_core_verified_test -- --nocapture- name: Check the description-logic model certificatesrun: OO_REQUIRE_FIXTURES=1 cargo test --test dl_model_certificate_test -- --nocapture+ - name: Pinpoint justifications, and check each one through the proved checker+ # Strict rather than excepted. The only thing this file skips on is+ # benchmark/reference/pizza-reference.owl, which ships with the+ # repository, so on a full checkout there is nothing for it to miss and+ # a skip here would mean the checkout is wrong.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test justify_test -- --nocapture+ - name: Annotate the closure with provenance semirings+ run: OO_REQUIRE_FIXTURES=1 cargo test --test provenance_test -- --nocapture- name: Check the refutation certificatesrun: 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 ontologydiff --git a/.mcp/server.json b/.mcp/server.jsonindex c96a0cb0..f9448fe3 100644--- a/.mcp/server.json+++ b/.mcp/server.json@@ -2,7 +2,7 @@"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.fabio-rovai/open-ontologies","title": "Open Ontologies",- "description": "AI-native ontology engineering MCP server: validate, query, diff, lint, version, and govern RDF/OWL ontologies with 109 tools and 6 workflow prompts via an Oxigraph triple store. All 109 tools ship in a default build; 8 need an optional Cargo feature (embeddings, plugins, postgres or duckdb).",+ "description": "AI-native ontology engineering MCP server: validate, query, diff, lint, version, and govern RDF/OWL ontologies with 116 tools and 6 workflow prompts via an Oxigraph triple store. All 116 tools ship in a default build; 8 need an optional Cargo feature (embeddings, plugins, postgres or duckdb).","version": "0.1.9","packages": [{diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8170cd04..772a0f55 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -231,6 +231,43 @@ All notable changes to Open Ontologies are documented here.than letting it be assumed away.### Added+- **A conclusion can name the axioms responsible for it, and a derived triple carries an+ algebraic expression over the asserted ones.** Two tools, `onto_justify` and+ `onto_provenance`, over one substrate that already existed and that nothing read back.+ `derivations.tsv` is a derivation DAG, but it records ONE step per inferred triple, the first+ the fixpoint reached, which is right for a checker that re-derives and wrong for an explainer:+ a triple derived two independent ways has two justifications and the file shows one. So+ `Reasoner::derivation_graph` captures every applicable ground rule instance instead, opt-in,+ at the cost of one branch per candidate triple on a run that did not ask for it.+ `onto_justify` returns the MINIMAL sets of asserted triples responsible for a triple or for a+ clash, and it keeps three claims apart under three words. SUFFICIENCY is re-run and, with+ `certificate_dir`, machine-checkable: each justification gets a certified run over exactly its+ own triples, so `lake exe oo-cert` verifies under `OOCert.certificate_sound` that the+ conclusion follows from that subset. MINIMALITY is re-run without each element and is covered+ by NO theorem. COMPLETENESS of the list is Reiter's hitting-set tree, bounded by+ `max_justifications` and `max_oracle_calls`, with `truncated` naming the bound that fired, and+ complete only for a monotone oracle: the engine's restriction and list vocabulary is read into+ maps keyed by the node, so a node with two values for a functional position contributes one and+ a justification can be MISSED there. None can be falsely reported, because each is re-run.+ `candidate` CHECKS a set instead of searching for one, and a superset of a justification comes+ back `not_a_justification_not_minimal` with the useless triples named. For a clash the verdict+ explained is `clash_found_by_this_engine` and never the checker's+ `unsatisfiable_under_disjointness`. `onto_provenance` evaluates six semirings over the same+ DAG: `boolean`, `why`, `lineage`, `counting`, `tropical` (min-plus) and `trust` (max-min, and+ the choice is named rather than left to be guessed). Recursion is reported rather than hidden:+ `counting` diverges on a cycle, so round k counts proof trees of height at most k,+ `depth_bound` rides beside the number, `value_is_exact` is false unless the iteration+ stabilised on its own, and `cycle_in_support` names a triple on the cycle. Convergence is never+ one word covering unrelated reasons, since `why`, `tropical` and `trust` converge by absorption+ while `boolean` and `lineage` converge because their value lattices are finite. A negative+ weight is refused for min-plus and a weight above 1.0 for max-min, each because it breaks the+ semiring rather than because it is unusual; the second was found by a test that expected 5.0+ and got 1.0. `why` truncation keeps the SMALLEST monomials, which is what keeps the survivors+ an antichain, and a truncated run withdraws the claim that they are minimal supports. 35 tests+ in `tests/justify_test.rs` and `tests/provenance_test.rs`, every fixture small enough that the+ answer is known on paper. See+ [decision 0009](docs/decisions/0009-a-conclusion-names-the-axioms-responsible-for-it.md) and+ docs/explanation.md.- **Common Logic has three dialects and this engine emitted one, so `fol --format cgif` writes asecond.** ISO/IEC 24707 defines CLIF, CGIF and XCL, and ISO/IEC 21838-1 clause 4.3 names allthree as qualifying; emitting CLIF and calling the result Common Logic support was a partialdiff --git a/CLAUDE.md b/CLAUDE.mdindex 7fff75a1..dfada7c9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -80,6 +80,8 @@ Claude dynamically decides the next tool call based on what the previous tool re| `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_rules_import` | To read rules you wrote in a STANDARD rule syntax into the Horn rule table `onto_reason` evaluates with `rules_file`. `from: "swrl"` reads SWRL rules encoded in RDF (`swrl:Imp` with `swrl:body`/`swrl:head` as `rdf:List` atom lists) out of the loaded graph or out of `file`; `from: "rif"` reads RIF Core in its XML syntax (the presentation syntax is refused, not half-read). Only a FRAGMENT of each language is a Horn table over triple patterns: SWRL built-in atoms, same-individual and different-individual atoms, data ranges and anonymous class expressions are refused, as are RIF equality, External, Expr, `rif:local` constants, list terms, Or/Neg/Naf, an existential conclusion and an Atom of arity 0 or 3+. Every refusal is NAMED AND COUNTED and by default fails the whole import with no table written, because a rule set that quietly lost half its rules still reaches a fixpoint and still produces a certificate that checks green. `allow_partial: true` imports the rest and flags `certifies_a_weaker_rule_set`. A table from this tool can only ever earn `entailed_under_supplied_rules` |+| `onto_justify` | AFTER a conclusion surprises you, and BEFORE deleting an axiom to fix a contradiction. Axiom pinpointing: the MINIMAL sets of asserted triples responsible for a triple (`triple`) or for a clash (`inconsistency: true`). A support set that is not minimal blames axioms that had nothing to do with the conclusion, so minimality is the product. Three claims, three words: SUFFICIENCY is re-run and, with `certificate_dir`, machine-checkable by `oo-cert` under `OOCert.certificate_sound`; MINIMALITY is re-run without each element and is covered by NO theorem; COMPLETENESS of the list is Reiter's hitting-set tree, bounded by `max_justifications` (16) and `max_oracle_calls` (400), with `truncated` naming the bound that fired, and complete only for a monotone oracle. Pass `candidate` to CHECK a set instead of searching for one: it comes back `minimal_justification`, `not_a_justification_not_minimal` with the useless triples named, or `not_a_justification_target_not_reached`. For a clash the word is `clash_found_by_this_engine` and never the checker's. `owl-dl` is refused: no rule trace, no derivation to walk. See docs/explanation.md |+| `onto_provenance` | To see WHY a triple holds as algebra rather than as a list. Provenance semirings over the whole derivation DAG, not over `derivations.tsv`, which records only the first derivation of each triple: `boolean`, `why` (whose minimal monomials are the justifications), `lineage` (the union of contributors, which is NOT a justification), `counting`, `tropical` (min-plus, the cheapest proof tree) and `trust` (max-min, the confidence of the weakest premise). RECURSION IS NAMED RATHER THAN HIDDEN: `counting` diverges on a cycle, so round k counts proof trees of height at most k, `depth_bound` (32) rides beside the number, `value_is_exact` is false unless the iteration stabilised, and `cycle_in_support` names a triple on the cycle. `why` is capped by `max_monomials` (64), the cap keeps the SMALLEST monomials so the survivors stay an antichain, and a truncated run withdraws the minimality claim. Negative weights are refused for min-plus and weights above 1.0 for max-min, because each breaks the semiring. Nothing here is machine-checked; `onto_justify` is the one that re-runs the engine. See docs/explanation.md || `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. || `onto_plan` | Before applying changes — shows added/removed classes, blast radius, risk score. All of that is about SHAPE; pass `check_conservativity: true` for the only part that is about MEANING, namely whether the change alters any consequence over the names the store already uses. A new `rdfs:domain` reclassifies every existing individual of that property while adding no class and removing nothing, so every other number in the plan stays green. Opt-in because it reasons both graphs to a fixpoint; when it is off the plan says so rather than staying silent |diff --git a/README.md b/README.mdindex 0c307297..f8cb8c4a 100644--- a/README.md+++ b/README.md@@ -368,6 +368,15 @@ this section said every conforming countermodel had to be hand-built; that was wcorrection is in [docs/lean-certificates.md](docs/lean-certificates.md) and in the changelog ratherthan edited out of sight.+**A justification is minimal because re-running said so, not because anything proved it.**+`onto_justify` answers which asserted triples a conclusion or a contradiction rests on, and of the+three claims in that answer only one can be machine-checked. That a set SUFFICES is checkable, and+is, when a certificate is written for it. That every element is NECESSARY comes from running the+engine again without each one, and no theorem covers it. That the list is COMPLETE comes from+Reiter's hitting-set tree, which is complete for a monotone oracle, and the engine has one corner+that is not monotone, named in [docs/explanation.md](docs/explanation.md). Nothing in+`onto_provenance` is machine-checked at all.+The discipline matters more than the machinery, and it runs through all of it.A rule **you** supplied is an assumption the certificate carries, never a fact it establishes, so@@ -428,8 +437,8 @@ Restart, and the `onto_*` tools are available. Cursor, Windsurf, Zed and VS Code## What is in the box-**117 tools** to build, validate, query, diff, lint, version, reason over, align, plan, certify-and govern RDF and OWL, over an in-memory Oxigraph store. A default build advertises 109 tools.+**119 tools** to build, validate, query, diff, lint, version, reason over, align, plan, certify+and govern RDF and OWL, over an in-memory Oxigraph store. A default build advertises 111 tools.Eight need an optional Cargo feature and return an error without it: four need `embeddings`, twoneed `plugins`, two need `postgres` or `duckdb`. The published binaries and the GHCR image arebuilt with the default feature set, so they do not carry those eight.@@ -457,6 +466,7 @@ a Protégé-style inspector. No JVM. No Protégé.| Quickstart | [docs/quickstart.md](docs/quickstart.md) || Architecture | [docs/architecture.md](docs/architecture.md) || Derivation certificates and the Lean checkers | [docs/lean-certificates.md](docs/lean-certificates.md) |+| Which axioms a conclusion rests on, and provenance semirings | [docs/explanation.md](docs/explanation.md) || What the Lean proofs assume about the Rust | [docs/trusted-computing-base.md](docs/trusted-computing-base.md) || Which gates a green CI tick actually ran | [docs/ci-gates.md](docs/ci-gates.md) || First-order export, TPTP and Common Logic | [docs/first-order-export.md](docs/first-order-export.md) |diff --git a/docs/architecture.md b/docs/architecture.mdindex 287cefce..3d0ee11f 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -24,7 +24,7 @@ flowchart TDREST["REST API\n/api/query · /api/update\n/api/save · /api/load · /api/lineage"]end- subgraph ToolGroups["117 Tools"]+ subgraph ToolGroups["119 Tools"]direction LRCore["Core\nvalidate · load · save · clear\nstats · query · diff · lint\nconvert · status"]DataPipe["Data Pipeline\nmap · ingest · shacl\nreason · extend · import-schema"]diff --git a/docs/ci-gates.md b/docs/ci-gates.mdindex fca9cbc2..1342886f 100644--- a/docs/ci-gates.md+++ b/docs/ci-gates.md@@ -54,6 +54,8 @@ job invokes the file at all.| test file | needs | provided by | in CI ||---|---|---|---|| `lean_certificate_test.rs` | lake | `lean` job | **strict** |+| `justify_test.rs` | `benchmark/reference/pizza-reference.owl`, which ships with the repository | `lean` job | **strict** |+| `provenance_test.rs` | the same shipped ontology | `lean` job | **strict** || `shacl_core_verified_test.rs` | lake + vendored W3C SHACL suite | `lean` job | **strict** || `dl_model_certificate_test.rs` | lake + `oo-dlmodel` | `lean` job | **strict** || `lean_refutation_test.rs` | lake + `oo-refute` | `lean` job | **strict** |diff --git a/docs/decisions/0009-a-conclusion-names-the-axioms-responsible-for-it.md b/docs/decisions/0009-a-conclusion-names-the-axioms-responsible-for-it.mdnew file mode 100644index 00000000..3b255d6b--- /dev/null+++ b/docs/decisions/0009-a-conclusion-names-the-axioms-responsible-for-it.md@@ -0,0 +1,103 @@+# 0009 · A conclusion names the axioms responsible for it, and minimality is re-run++- **Status**: implemented · `src/justify.rs`, `src/provenance.rs`,+ `Reasoner::derivation_graph` · `onto_justify`, `onto_provenance` ·+ `tests/justify_test.rs` (17), `tests/provenance_test.rs` (18) · opt-in, and a run that does+ not ask for the DAG pays one branch per candidate triple+- **Written**: 2026-09-15+- **Related**: decision 0002 (an inference carries a certificate), decision 0007 (a slice+ preserves a conclusion or it does not); `docs/explanation.md`++## The problem++The engine could say what it derived, and since decision 0002 it could hand over a certificate a+proved-sound Lean checker verifies. Neither answers the question that actually gets asked when a+conclusion is wrong or an ontology contradicts itself, which is **which of my axioms did this**.++`derivations.tsv` is a derivation DAG and nothing read it back for explanation. That was the gap.++## Decisions++1. **Explanation does not read the certificate file.** `derivations.tsv` records ONE step per+ inferred triple, the first the fixpoint reached, which is correct for a checker that+ re-derives and wrong for an explainer. A triple derived two independent ways has two+ justifications and the file shows one. An explanation built from it would be a confident,+ specific, false statement about where a conclusion came from, which is worse than a vague one.+ `Reasoner::derivation_graph` captures EVERY applicable ground rule instance instead.+ `tests/justify_test.rs::the_derivation_dag_carries_both_instances_where_a_certificate_carries_one`+ measures the difference on one graph: two instances, one line.++2. **Minimality is the product, not a refinement of it.** A support set that is not minimal+ blames axioms that had nothing to do with the conclusion. Someone who deletes one of them and+ watches the conclusion survive learns to distrust the tool rather than the ontology, so a+ non-minimal answer is not a slightly worse answer.++3. **Minimality is established by re-running the fixpoint, and by nothing else.** For every+ element of every reported justification the engine is run again without it and the conclusion+ must be gone. No Lean theorem says a set is minimal, the payload does not imply one, and the+ word in it is `verified_by_re_running_the_fixpoint_without_each_element`.++4. **Sufficiency is the half a theorem can cover, so it is offered separately.** With+ `certificate_dir` each justification gets a certified run over exactly its own triples, and+ `lake exe oo-cert` verifies under `OOCert.certificate_sound` that the conclusion follows from+ that subset. The payload says what that establishes and what it does not, in those words.++5. **Completeness of the LIST is an algorithm's claim and is bounded out loud.** Reiter's+ hitting-set tree enumerates justifications over the same oracle. `max_justifications` and+ `max_oracle_calls` bound it, `truncated` fires and `truncation.bound` names which one. A+ truncated answer is incomplete and is never wrong: every justification in it was re-run.++6. **The one non-monotone corner of the engine is named rather than assumed away.** Reiter's+ construction is complete for a monotone oracle. No rule reads the absence of a triple, but the+ restriction and list vocabulary is read into maps keyed by the node, so a node carrying two+ values for a functional position contributes one, chosen by hash order. Removing a triple can+ change which value is read. Where that bites, a justification can be MISSED. None can be+ falsely reported, because each is re-run.++7. **Inconsistency gets the same machinery and keeps `onto_reason`'s word.** The target becomes+ "this engine finds a clash", the verdict explained is `clash_found_by_this_engine`, and the+ Lean checker's `unsatisfiable_under_disjointness` is never spoken here. Ten of the seventeen+ rules that conclude `false` are looked for, so no clash found is still not a consistency+ result.++8. **Provenance is a semiring evaluation over the same DAG, and recursion is reported rather than+ hidden.** Six semirings ship. Datalog is recursive, so the counting semiring diverges on a+ cycle. Rather than print a finite number and let a reader assume it is the count, round `k`+ computes the annotation over proof trees of height at most `k`, `depth_bound` rides beside the+ value, `value_is_exact` is false unless the iteration stabilised on its own, and+ `cycle_in_support` names a triple on the cycle. `tests/provenance_test.rs` pins two bounds+ giving two different numbers, which is what a bound has to do to be a bound.++9. **Convergence is never one word covering unrelated reasons.** `why`, `tropical` and `trust` converge+ because they are absorptive. `boolean` and `lineage` converge because their value lattices are+ finite and the iteration is monotone; they are NOT absorptive, and the payload says which+ reason applies to which semiring.++10. **A weight that breaks a semiring is refused.** Min-plus is absorptive only for non-negative+ weights. Max-min is a semiring on `[0, 1]` whose multiplicative identity is 1, so a weight+ above it makes a conjunction of premises come out smaller than the algebra says. Both are+ refused with the reason, rather than computed and quietly wrong. The second was found by a+ test that expected 5.0 and got 1.0.++11. **The truncation of why-provenance keeps the SMALLEST monomials.** A proper subset is strictly+ smaller, so a discarded monomial can never be a proper subset of a kept one and the survivors+ stay an antichain. Truncation still costs completeness, and it can cost minimality indirectly+ through an intermediate fact, so a truncated run sets `monomials_are_minimal_supports: false`+ and withdraws the claim.++## What this does not claim++Neither tool makes an ontology correct, and neither is a statement about OWL 2 RL. The rule table+is this engine's 29 of the profile's 78 rules, so a justification is a claim about what THIS engine+derives from the graph as loaded. A set that stops yielding the conclusion under this table may+still yield it under the full profile, and a conclusion this engine never reaches is not a+non-entailment result.++Nothing in `onto_provenance` is machine-checked. In `onto_justify` exactly one thing is, and only+when a certificate was written and the checker was actually run.++## Cost++One fixpoint per hitting-set-tree node, plus one per minimality check. On a large ontology that is+the entire cost of `onto_justify`, and it is why the bounds default low. The first justification is+free: it is a walk of the DAG with no re-run at all.diff --git a/docs/explanation.md b/docs/explanation.mdnew file mode 100644index 00000000..c3f5e209--- /dev/null+++ b/docs/explanation.md@@ -0,0 +1,187 @@+# Explaining a conclusion: pinpointing and provenance++The reasoner has always been able to say WHAT it derived. Since+[decision 0002](decisions/0002-an-inference-carries-a-certificate.md) it can hand over a+certificate that a proved-sound Lean checker verifies, which says that each step is entailed.+Neither answers the question an engineer actually asks when a conclusion is wrong, which is+**which of my axioms did this**.++Two tools answer it, over one substrate.++- `onto_justify`, axiom pinpointing. The minimal sets of asserted triples responsible for a+ conclusion, or for a contradiction.+- `onto_provenance`, provenance semirings. The algebraic expression over the asserted triples+ that a derived triple carries.++## The substrate is the DAG, and it is not the certificate file++`derivations.tsv` records ONE step per inferred triple: the first the fixpoint reached. That is+exactly right for a certificate, because a checker re-derives and one derivation is all it needs.+It is exactly wrong for explanation. A triple derived two independent ways has two justifications+and the file shows one of them, so an explanation read off the file would be a confident, specific,+false statement about where a conclusion came from.++So `Reasoner::derivation_graph` runs the fixpoint and captures EVERY applicable ground rule+instance instead. The capture is opt-in and costs one branch per candidate triple on a run that did+not ask for it. The last round of the loop applies every rule over the complete closure and adds+nothing, so every instance applicable at the fixpoint fires at least once and is recorded;+deduplication is by (rule, conclusion, premises).++`tests/justify_test.rs::the_derivation_dag_carries_both_instances_where_a_certificate_carries_one`+is that difference, measured: two instances in the DAG, one line in the file, same graph.++## `onto_justify`++A justification (a MinA) for `T` is a subset `S` of the asserted graph with `T` in `closure(S)` and+`T` not in `closure(S')` for any proper subset. **The second half is the product.** A support set+that is not minimal blames axioms that had nothing to do with the conclusion, and someone who+deletes one of them and watches the conclusion survive learns to distrust the tool rather than the+ontology.++### Three claims, three words++| claim | how it is established | what stands behind it |+|---|---|---|+| sufficiency | the engine is run over exactly `S` and the conclusion appears | with `certificate_dir`, `OOCert.certificate_sound` via `lake exe oo-cert` |+| minimality | the engine is run again over `S \ {e}` for every `e`, and the conclusion must be gone | execution only. NO theorem |+| completeness of the list | Reiter's hitting-set tree over the same oracle | an algorithm, complete for a monotone oracle, bounded and flagged |++The certificate is worth spelling out. With `certificate_dir`, each justification gets its own+directory holding an `asserted.tsv` of exactly that justification's triples and a `derivations.tsv`+that concludes the target. `oo-cert` accepting it establishes that the conclusion really does+follow from that subset, under a machine-checked theorem. It establishes nothing about minimality+and nothing about the list being complete, and the payload says so in those words.++### Cost, and the bounds++The FIRST justification is nearly free: walk one derivation tree from the conclusion down to+asserted leaves, no re-run at all. It is not necessarily minimal, so it is shrunk by the oracle in+`|S|` re-runs, and it seeds the tree.++Everything after that is one full fixpoint per node. `max_justifications` (default 16) and+`max_oracle_calls` (default 400) bound it, `truncated` says when a bound fired and `truncation.bound`+says which. A truncated answer is not a wrong answer: every justification in it is still sufficient+and still minimal, both re-run. It is an incomplete one, and it says so.++### The monotonicity caveat, precisely++Reiter's construction is complete for a monotone oracle. The rule table is monotone, in that no rule reads+the ABSENCE of a triple, but two places in `src/reason.rs` are not. `owl:onProperty`,+`owl:someValuesFrom`, `owl:allValuesFrom`, `owl:hasValue`, `rdf:first` and `rdf:rest` are read into+maps keyed by the node, so a node carrying TWO values for one of them contributes one, chosen by+hash order. Removing a triple can therefore change which value is read rather than only removing+consequences.++Where that bites, the tree can MISS a justification. It cannot report a false one, because every+reported set is verified by re-running the engine over it and over each of its subsets.++### Inconsistency is the half that is worth more++An inconsistent ontology entails everything, so the useful question is never which conclusion to+doubt. It is which axioms to remove. `inconsistency: true` runs the same machinery with the target+being "this engine finds a clash".++The verdict word is `clash_found_by_this_engine`, exactly as `onto_reason` reports it, and never the+Lean checker's `unsatisfiable_under_disjointness`. Ten of the seventeen OWL 2 RL rules that conclude+`false` are looked for, so no clash found is not a consistency result and a justification here+explains a clash rather than unsatisfiability.++### Checking someone else's answer++Pass `candidate` and nothing is searched for. The set is checked, and the answer is one of++- `minimal_justification`: sufficient, and every element necessary. Both halves re-run.+- `not_a_justification_not_minimal`: with the removable triples named.+- `not_a_justification_target_not_reached`: a different failure, under a different word.++## `onto_provenance`++Green, Karvounarakis and Tannen's construction, applied to this engine's rule table rather than to+relational algebra: evaluate the fixpoint a second time with truth values replaced by elements of a+commutative semiring, and every derived triple carries an expression over the asserted ones.++| semiring | `⊕` | `⊗` | reads as |+|---|---|---|---|+| `boolean` | ∨ | ∧ | derivability |+| `why` | union then absorption | pairwise union | the leaf sets of the proof trees; the minimal ones are the justifications |+| `lineage` (`Which(X)`) | ∪ | ∪ | which triples contribute at all. NOT a justification |+| `counting` | + | × | the number of proof trees |+| `tropical` | min | + | the cheapest proof tree, summing leaf weights with multiplicity |+| `trust` | max | min | the confidence of the best derivation, which is that of its weakest premise |++`trust` is **max-min**, not min-plus, and the choice is named here because the two disagree about+which derivation is better and a reader is owed which one they are looking at. `tropical` is the+min-plus one and is offered beside it.++### Recursion, which is where provenance goes wrong quietly++Datalog is recursive. A triple whose support contains a cycle has arbitrarily many proof trees, so+its counting annotation DIVERGES and its how-provenance is an infinite series rather than a+polynomial. Producing a finite number anyway and not saying so is the failure this tool is built to+avoid.++- **The absorptive ones converge.** `why`, `tropical` and `trust` satisfy `a ⊕ (a ⊗ b) = a`, so a+ derivation that goes round a cycle is absorbed by the one that does not. The payload says+ `absorptive: true` and `stabilised: true`, and the round count is well under the bound.+- **`boolean` and `lineage` converge for a DIFFERENT reason**, which is that their value lattices+ are finite and the iteration is monotone in them. They are not absorptive, the payload says so,+ and neither reason is ever collapsed into the word "converges".+- **`counting` does not converge.** Round `k` counts proof trees of height at most `k`, so+ `depth_bound` (default 32) rides beside the number, `value_is_exact` is false unless the+ iteration stabilised on its own, `value_means` says the number is a LOWER BOUND, and+ `cycle_in_support` names a triple on the cycle. A 128-bit counter that overflows is reported as+ `saturated` rather than as a count.++`tests/provenance_test.rs::the_counting_semiring_reports_its_bound_instead_of_a_finite_lie` pins+two different bounds giving two different numbers on the same graph, which is what a bound has to+do to be a bound.++### The monomial cap, and why the survivors are still an antichain++Why-provenance is worst-case exponential, so `max_monomials` (default 64) caps it. The monomials+KEPT are the smallest. That is not a heuristic: a proper subset is strictly smaller, so a discarded+monomial can never be a proper subset of a kept one, and the survivors remain an antichain.++What truncation does cost is completeness, and it can cost minimality indirectly, because the+smaller monomial that would have absorbed a kept one may have been dropped at an INTERMEDIATE fact.+So a truncated run sets `monomials_are_minimal_supports: false` and withdraws the claim rather than+keeping it. Every monomial listed is still the leaf set of a real derivation.++### Weights are refused rather than bent++`tropical` is absorptive only for non-negative weights, since `min(a, a+b) = a` needs `b ≥ 0`; a+negative weight is refused. `trust` is a semiring on `[0, 1]` whose multiplicative identity is 1, so+a weight above 1 makes a conjunction of premises come out SMALLER than the algebra says; that is+refused too, and the message says to use `tropical` instead if the numbers are costs rather than+confidences.++## How the two relate++Feature 1 is feature 2 under the right semiring: the minimal elements of the why-provenance value+coincide with the MinAs, for an untruncated run that stabilised over a monotone rule table. The two+share the DAG index and the target parsing, and+`tests/provenance_test.rs::the_why_monomials_are_the_justifications_the_re_runs_verify`+asserts they return the same sets on the same graph.++They do not share the guarantee, and that is deliberate. `onto_provenance` does algebra over a DAG+and can truncate. `onto_justify` re-runs the engine, without each element of each answer, and+reports what those runs showed. When they disagree the re-runs win, which is why they exist.++## What neither tool claims++Neither makes an ontology correct, and neither is a statement about OWL 2 RL. The rule table is+this engine's 29 of the profile's 78 rules, so a justification is a claim about what THIS engine+derives from the graph as loaded. A set that stops yielding the conclusion under this table may+still yield it under the full profile, and a conclusion this engine never reaches is not a+non-entailment result.++Nothing in `onto_provenance` is machine-checked. In `onto_justify`, one thing is: that a+justification suffices, and only when a certificate was written and `oo-cert` was actually run.++A SUPPLIED Horn rule table is out of scope. `onto_reason` with `rules_file` runs a different+fixpoint (`Reasoner::run_horn`), the DAG capture is not threaded through it, and neither tool takes+a `rules_file`. Explaining a conclusion drawn under rules nobody has checked would also need a+fourth word, because the conclusion itself only ever earns `entailed_under_supplied_rules`.++`owl-dl` is refused by both, rather than answered with an empty DAG that would read as "nothing was+derived". The tableaux path records no rule applications.diff --git a/docs/lean-certificates.md b/docs/lean-certificates.mdindex 1216d830..051ec314 100644--- a/docs/lean-certificates.md+++ b/docs/lean-certificates.md@@ -70,6 +70,21 @@ inside one.then the derivation steps that reached the clash in the same spelling as `derivations.tsv`, thenone `refute TAB rule` line with the clash rule's premises. See the refutation section below.+## What the file is NOT enough for++`derivations.tsv` is a derivation DAG and it is tempting to read explanations out of it. Do not.+It records ONE step per inferred triple, the first the fixpoint reached, which is exactly what a+checker that re-derives needs and exactly wrong for the question "which of my axioms did this". A+triple derived two independent ways has two justifications and the file shows one, so an+explanation built from it would be specific, confident and false.++`onto_justify` and `onto_provenance` therefore ask the reasoner for every applicable ground rule+instance instead, and never open the file. See [docs/explanation.md](explanation.md) and+[decision 0009](decisions/0009-a-conclusion-names-the-axioms-responsible-for-it.md). What the+certificate IS enough for, those tools use: with `certificate_dir`, each justification gets its own+certified run over its own triples, so `oo-cert` can verify that the conclusion really does follow+from that subset. Minimality is not in the theorem and is re-run instead.+## What is proved`OOCert.certificate_sound` in `lean/OOCert/Soundness.lean`:diff --git a/funding.json b/funding.jsonindex 524f493f..faccd099 100644--- a/funding.json+++ b/funding.json@@ -14,7 +14,7 @@{"guid": "open-ontologies","name": "Open Ontologies",- "description": "Open Ontologies is a Rust MCP (Model Context Protocol) server and desktop Studio for AI-native ontology engineering. It exposes 109 tools that let an LLM client build, validate, query, diff, lint, version, reason over, align, plan, certify and govern RDF/OWL ontologies against an in-memory Oxigraph triple store. All 109 ship in a default build, and 8 of them require an optional Cargo feature (embeddings, plugins, postgres or duckdb). It ships as a single binary with no JVM and no Protege dependency, and covers OWL 2 profile checking, SHACL validation, SPARQL, OWL-RL reasoning, ontology diffing, a marketplace of 33 standard ontologies, IES (Information Exchange Standard) support for UK defence and government data, semantic embeddings in builds compiled with the embeddings feature, PDDL planning, and a full lineage audit trail. The design is deliberately MCP-native: the server provides validation, scaffolding and proof, while the connected model supplies the intelligence. There are no embedded LLM clients, no API keys and no provider lock-in, so the same engine runs offline and in air-gapped environments. Open Ontologies is the verification engine behind a public programme of register-integrity audits, where every published finding is re-checked by an independent path before release. Funding supports maintenance, cross-platform release engineering, the reasoning and planner layers, and continued free distribution.",+ "description": "Open Ontologies is a Rust MCP (Model Context Protocol) server and desktop Studio for AI-native ontology engineering. It exposes 116 tools that let an LLM client build, validate, query, diff, lint, version, reason over, align, plan, certify and govern RDF/OWL ontologies against an in-memory Oxigraph triple store. All 116 ship in a default build, and 8 of them require an optional Cargo feature (embeddings, plugins, postgres or duckdb). It ships as a single binary with no JVM and no Protege dependency, and covers OWL 2 profile checking, SHACL validation, SPARQL, OWL-RL reasoning, ontology diffing, a marketplace of 33 standard ontologies, IES (Information Exchange Standard) support for UK defence and government data, semantic embeddings in builds compiled with the embeddings feature, PDDL planning, and a full lineage audit trail. The design is deliberately MCP-native: the server provides validation, scaffolding and proof, while the connected model supplies the intelligence. There are no embedded LLM clients, no API keys and no provider lock-in, so the same engine runs offline and in air-gapped environments. Open Ontologies is the verification engine behind a public programme of register-integrity audits, where every published finding is re-checked by an independent path before release. Funding supports maintenance, cross-platform release engineering, the reasoning and planner layers, and continued free distribution.","webpageUrl": {"url": "https://github.com/fabio-rovai/open-ontologies"},diff --git a/python/README.md b/python/README.mdindex 2c48b9b2..178890c9 100644--- a/python/README.md+++ b/python/README.md@@ -226,7 +226,7 @@ report["conforms"] # None, because nothing was examined## Relationship to the Rust engine-This is the **Python layer** of the project. For the full engine (three-layer Dynamics/Causal/Planner architecture, HNSW semantic search, SHIQ tableaux reasoning, PDDL planning, governance, 109 tools), use the [Rust build](https://github.com/fabio-rovai/open-ontologies). HNSW semantic search there is a compile-time feature, so build with `--features embeddings`; the published binaries do not carry it. Same Oxigraph core; pick the weight class you need.+This is the **Python layer** of the project. For the full engine (three-layer Dynamics/Causal/Planner architecture, HNSW semantic search, SHIQ tableaux reasoning, PDDL planning, governance, 116 tools), use the [Rust build](https://github.com/fabio-rovai/open-ontologies). HNSW semantic search there is a compile-time feature, so build with `--features embeddings`; the published binaries do not carry it. Same Oxigraph core; pick the weight class you need.## Licensediff --git a/python/src/open_ontologies_lite/horn/reason.py b/python/src/open_ontologies_lite/horn/reason.pyindex 62cdcb47..15e44d95 100644--- a/python/src/open_ontologies_lite/horn/reason.py+++ b/python/src/open_ontologies_lite/horn/reason.py@@ -246,7 +246,7 @@ def _facts(store, graphs) -> tuple[list[Fact], list[str]]:The default is the DEFAULT GRAPH ALONE, which is where `OntologyEngine.load()`puts everything, so this package's own users lose nothing by it. The Rustengine flattens every named graph here EXCEPT the inferred one- (`src/reason.rs:2753`, `graph.triples_outside(&[INFERRED_GRAPH])`). Before+ (`src/reason.rs:2968`, `graph.triples_outside(&[INFERRED_GRAPH])`). Before15 September 2026 it excepted nothing, which was the defect above: a storeholding a prior materialisation turned derived triples into assertions."""diff --git a/python/tests/test_horn_differential.py b/python/tests/test_horn_differential.pyindex 425b56ef..23158cf4 100644--- a/python/tests/test_horn_differential.py+++ b/python/tests/test_horn_differential.py@@ -26,7 +26,7 @@ WHAT IS COMPARED, AND WHAT IS NOT.The assertion is SET EQUALITY OF DERIVED TRIPLES against the Rust `run_horn`, overthe same `builtin_rules.tsv`. Byte identity of the two `horn.tsv` files is NOT agoal and must not be asserted: the Rust emitter sorts interned `u32` triples-(`src/reason.rs:2823`, `all.sort_unstable()` over `Vec<(u32,u32,u32)>`), so its+(`src/reason.rs:3038`, `all.sort_unstable()` over `Vec<(u32,u32,u32)>`), so itsline order is first-appearance order in the store, not lexicographic order.Reproducing it from Python would mean reimplementing the interner and betting onidentical store-iteration order across two bindings, to buy nothing the setdiff --git a/python/tests/test_horn_fixpoint_and_scope.py b/python/tests/test_horn_fixpoint_and_scope.pyindex a23f1f19..ffbf8948 100644--- a/python/tests/test_horn_fixpoint_and_scope.py+++ b/python/tests/test_horn_fixpoint_and_scope.py@@ -24,7 +24,7 @@ previous materialisation in the inferred graph turned derived triples intoASSERTIONS. The checker could not detect it: the soundness theorem is conditionalon the assertions, and it is TOLD what they are, so the result was a greenabsolute verdict about a graph nobody asserted. It now reads-`src/reason.rs:2753`, `graph.triples_outside(&[INFERRED_GRAPH])`, and the+`src/reason.rs:2968`, `graph.triples_outside(&[INFERRED_GRAPH])`, and theinferred graph is out of scope.The two engines still differ in HOW, and the difference is deliberate. Rustdiff --git a/skills/ontology-engineer.md b/skills/ontology-engineer.mdindex ddb0e19b..adc31748 100644--- a/skills/ontology-engineer.md+++ b/skills/ontology-engineer.md@@ -5,7 +5,7 @@ description: Use when building, modifying, or validating ontologies. Orchestrate# Ontology Engineer-AI-native ontology engineering using the Open Ontologies `onto_*` MCP tools (109 tools, 8 of which require an optional Cargo feature).+AI-native ontology engineering using the Open Ontologies `onto_*` MCP tools (116 tools, 8 of which require an optional Cargo feature).## When to Usediff --git a/skills/ontology-engineering/SKILL.md b/skills/ontology-engineering/SKILL.mdindex 14799238..893e6e22 100644--- a/skills/ontology-engineering/SKILL.md+++ b/skills/ontology-engineering/SKILL.md@@ -5,7 +5,7 @@ description: Build, validate, and govern RDF/OWL ontologies using the Open Ontol# Ontology Engineering Workflow-You have access to the Open Ontologies MCP server, which provides 109 tools for AI-native ontology engineering backed by an in-memory Oxigraph triple store. All 109 are available in a default build, but 8 require an optional Cargo feature and return an error without it: four need `embeddings`, two need `plugins`, and two need `postgres` or `duckdb`.+You have access to the Open Ontologies MCP server, which provides 116 tools for AI-native ontology engineering backed by an in-memory Oxigraph triple store. All 116 are available in a default build, but 8 require an optional Cargo feature and return an error without it: four need `embeddings`, two need `plugins`, and two need `postgres` or `duckdb`.## Core Workflowdiff --git a/src/inputs.rs b/src/inputs.rsindex 09e85650..30ede1e8 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -306,6 +306,73 @@ pub struct OntoReasonInput {pub rules_file: Option<String>,}+#[derive(Deserialize, JsonSchema)]+pub struct OntoJustifyInput {+ /// The conclusion to explain, as ONE N-Triples triple: `<s> <p> <o>`, with+ /// full IRIs in angle brackets and literals in quotes. Prefixed names are+ /// not read. A blank node may be written `_:label` and comes back the same+ /// way. Give this or `inconsistency`, never both.+ pub triple: Option<String>,+ /// Explain the CLASH instead of a triple: which asserted triples are+ /// responsible for the contradiction this engine found. The more valuable+ /// question, because an inconsistent ontology entails everything and the+ /// only useful answer is which axioms to remove.+ pub inconsistency: Option<bool>,+ /// A support set someone else produced, to be CHECKED rather than+ /// searched for. Each entry is one N-Triples triple. The answer is one of+ /// `minimal_justification`, `not_a_justification_not_minimal` (with the+ /// removable triples named) or `not_a_justification_target_not_reached`.+ pub candidate: Option<Vec<String>>,+ /// `rdfs`, `owl-rl` (the default here, because a clash needs the OWL+ /// rules) or `owl-rl-ext`. `owl-dl` is refused: the tableaux path records+ /// no rule applications, so there is no derivation to walk. It must match+ /// the profile whose conclusion you are asking about.+ pub profile: Option<String>,+ /// Stop after this many justifications. Default 16. A run that stops here+ /// sets `truncated` and names the bound.+ pub max_justifications: Option<usize>,+ /// Stop after this many fixpoint re-runs. Default 400. Every node of the+ /// hitting-set tree and every minimality check is one re-run, so this is+ /// the real cost control.+ pub max_oracle_calls: Option<usize>,+ /// Write one derivation certificate per justification, over exactly that+ /// justification's triples, so `lake exe oo-cert` can verify SUFFICIENCY+ /// under `OOCert.certificate_sound`. Minimality is not covered by any+ /// theorem and is verified by re-running the engine instead.+ pub certificate_dir: Option<String>,+}++#[derive(Deserialize, JsonSchema)]+pub struct ProvenanceWeight {+ /// One N-Triples triple that must be ASSERTED in the store.+ pub triple: String,+ /// Its weight. Non-negative for `tropical`; in [0, 1] when `trust` is+ /// asked for, because max-min's multiplicative identity is 1.+ pub weight: f64,+}++#[derive(Deserialize, JsonSchema)]+pub struct OntoProvenanceInput {+ /// The triple to annotate, as ONE N-Triples triple. Omit to get the shape+ /// of the derivation DAG with nothing annotated.+ pub triple: Option<String>,+ /// `rdfs`, `owl-rl` (default) or `owl-rl-ext`. `owl-dl` is refused.+ pub profile: Option<String>,+ /// Which semirings to evaluate. Any of `boolean`, `why`, `lineage`,+ /// `counting`, `tropical` (min-plus), `trust` (max-min). All of them by+ /// default.+ pub semirings: Option<Vec<String>>,+ /// Maximum rounds of the annotated fixpoint, which is a bound on+ /// derivation DEPTH: round k covers proof trees of height at most k.+ /// Default 32. Only `counting` can fail to converge before it.+ pub depth_bound: Option<usize>,+ /// Maximum monomials kept per fact in the `why` semiring. Default 64. When+ /// the cap bites, the SMALLEST monomials are kept and `truncated` is set.+ pub max_monomials: Option<usize>,+ /// Per-triple weights for `tropical` and `trust`. Absent means 1.0.+ pub weights: Option<Vec<ProvenanceWeight>>,+}+#[derive(Deserialize, JsonSchema)]pub struct OntoFolExportInput {/// Directory to write the export to. `ontology.p` (TPTP), `ontology.clif`diff --git a/src/justify.rs b/src/justify.rsnew file mode 100644index 00000000..d2605c35--- /dev/null+++ b/src/justify.rs@@ -0,0 +1,727 @@+//! Axiom pinpointing: which ASSERTED triples are responsible for a conclusion.+//!+//! A justification (a MinA, a minimal axiom set) for a conclusion `T` is a+//! subset `S` of the asserted graph with `T` in `closure(S)` and `T` not in+//! `closure(S')` for any proper subset `S'`. The second half is the whole+//! point. A support set that is not minimal is a lie about responsibility: it+//! blames triples that had nothing to do with the conclusion, and an engineer+//! deleting one of them and watching the conclusion survive learns to distrust+//! the tool rather than the ontology.+//!+//! # Where the answer comes from, and what checked it+//!+//! Three different things are going on and they carry three different words.+//!+//! * **Sufficiency is re-run, and can be machine-checked.** Every justification+//! reported here was produced by running the engine over exactly that subset+//! and seeing the conclusion appear. With `certificate_dir` the run is+//! repeated with `--certificate`, so `lake exe oo-cert` can verify under+//! `OOCert.certificate_sound` that the subset really does entail the+//! conclusion. That is the one claim here a theorem stands behind.+//! * **Minimality is re-run, and is NOT machine-checked.** For every element+//! `e` of every reported justification, the engine is run again over+//! `S \ {e}` and the conclusion must be gone. It is a property of this+//! engine's rule table verified by execution, and no Lean theorem says a set+//! is minimal.+//! * **Completeness of the LIST is an algorithm's claim, bounded and flagged.**+//! All justifications are enumerated by Reiter's hitting-set tree over the+//! same oracle. The search is bounded by `max_justifications` and+//! `max_oracle_calls`, and `truncated` says when a bound fired and which one.+//! Reiter's construction is complete for a MONOTONE oracle; see the+//! monotonicity note below for the one corner of this engine that is not.+//!+//! # The first justification is nearly free, the rest are not+//!+//! [`crate::reason::Reasoner::derivation_graph`] hands back every applicable+//! ground rule instance. Walking one derivation tree from the conclusion down+//! to asserted leaves gives a support set with no re-run at all. It is not+//! necessarily minimal, so it is shrunk by the oracle, and it seeds the+//! hitting-set tree. Everything after that costs one fixpoint per node.+//!+//! # Monotonicity, precisely+//!+//! The rule table is monotone: no rule reads the ABSENCE of a triple. Two+//! places in [`crate::reason`] are not, and they are named here rather than+//! assumed away. `owl:onProperty`, `owl:someValuesFrom`, `owl:allValuesFrom`+//! and `owl:hasValue` are read into maps keyed by the restriction node, and+//! `rdf:first` / `rdf:rest` likewise, so a node carrying TWO values for one of+//! them contributes only one, chosen by hash order. Removing a triple can+//! therefore change which value is read rather than only removing+//! consequences. Where that bites, the hitting-set tree may miss a+//! justification; it cannot report a false one, because every reported set is+//! verified by re-running the engine over it and over each of its subsets.+//!+//! # Inconsistency+//!+//! The same machinery, with the target being "this engine finds a clash" rather+//! than a triple. That is the operationally valuable half: an inconsistent+//! ontology entails everything, and the question is never which conclusion to+//! doubt but which axioms to remove. The verdict word is+//! `clash_found_by_this_engine` exactly as [`crate::reason`] reports it: ten of+//! the seventeen OWL 2 RL rules that conclude `false` are looked for, so a+//! justification here explains a clash this engine found and NOT+//! unsatisfiability.++use crate::graph::GraphStore;+use crate::provenance::{parse_triple, triple_out};+use crate::reason::{DerivationGraph, InferenceTarget, Reasoner, Spelled};+use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};+use std::path::{Path, PathBuf};+use std::sync::Arc;++/// Justifications returned before the search gives up.+pub const DEFAULT_MAX_JUSTIFICATIONS: usize = 16;++/// Fixpoint re-runs allowed before the search gives up.+///+/// Every node of the hitting-set tree and every minimality check is one full+/// re-run of the reasoner over a subset of the graph. On a large ontology that+/// is the entire cost of this tool, and a run that hits this bound reports the+/// fact rather than a shorter list wearing the word "all".+///+/// It is checked BETWEEN nodes, so the reported `oracle_calls` can overshoot it+/// by one minimisation pass, and the final verification pass runs on top of it+/// whatever it says. The reported number is always the count of runs actually+/// made, never the bound.+pub const DEFAULT_MAX_ORACLE_CALLS: usize = 400;++/// What is being explained.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Target {+ /// One conclusion, in the store's own N-Triples spelling.+ Triple(Spelled),+ /// Any clash this engine detects. Not unsatisfiability; see the module+ /// docs.+ Inconsistency,+}++impl Target {+ fn label(&self) -> &'static str {+ match self {+ Target::Triple(_) => "triple",+ Target::Inconsistency => "inconsistency",+ }+ }++ /// Does this run reach the target?+ fn holds(&self, dg: &DerivationGraph) -> bool {+ match self {+ Target::Triple(t) => dg.holds(t),+ Target::Inconsistency => !dg.clashes.is_empty(),+ }+ }+}++pub struct JustifyOptions {+ pub profile: String,+ pub max_justifications: usize,+ pub max_oracle_calls: usize,+ /// Where to write one derivation certificate per justification, so that+ /// `oo-cert` can verify the SUFFICIENCY half against a machine-checked+ /// soundness theorem.+ pub certificate_dir: Option<PathBuf>,+}++impl Default for JustifyOptions {+ fn default() -> Self {+ Self {+ profile: "owl-rl".to_string(),+ max_justifications: DEFAULT_MAX_JUSTIFICATIONS,+ max_oracle_calls: DEFAULT_MAX_ORACLE_CALLS,+ certificate_dir: None,+ }+ }+}++/// The sentence that travels with every answer here.+pub const ENGINE_CAVEAT: &str =+ "a justification is a statement about THIS ENGINE's rule table, 29 of OWL 2 RL's 78 rules, \+ and about the graph as loaded. A set that no longer yields the conclusion under this table \+ may still yield it under the full profile, and a conclusion this engine never reaches is not \+ a non-entailment result.";++// ───────────────────────────────────────────────────────────────────────────+// The oracle: one fixpoint per question+// ───────────────────────────────────────────────────────────────────────────++struct Oracle<'a> {+ asserted: Vec<Spelled>,+ target: &'a Target,+ profile: &'a str,+ calls: usize,+ /// Set once if a re-run ever stopped at the iteration cap. Every answer+ /// after that is about a partial closure and the report has to say so.+ hit_iteration_cap: bool,+}++impl<'a> Oracle<'a> {+ fn new(asserted: Vec<Spelled>, target: &'a Target, profile: &'a str) -> Self {+ Self {+ asserted,+ target,+ profile,+ calls: 0,+ hit_iteration_cap: false,+ }+ }++ fn store_of(keep: &BTreeSet<Spelled>) -> anyhow::Result<Arc<GraphStore>> {+ let mut nt = String::with_capacity(keep.len() * 96);+ for (s, p, o) in keep {+ nt.push_str(s);+ nt.push(' ');+ nt.push_str(p);+ nt.push(' ');+ nt.push_str(o);+ nt.push_str(" .\n");+ }+ let g = GraphStore::new();+ g.load_ntriples(&nt)?;+ Ok(Arc::new(g))+ }++ /// Run the engine over `keep` and return the DAG when the target is+ /// reached, `None` when it is not.+ fn ask(&mut self, keep: &BTreeSet<Spelled>) -> anyhow::Result<Option<DerivationGraph>> {+ self.calls += 1;+ let store = Self::store_of(keep)?;+ let dg = Reasoner::derivation_graph(&store, self.profile)?;+ if !dg.fixpoint_reached {+ self.hit_iteration_cap = true;+ }+ Ok(self.target.holds(&dg).then_some(dg))+ }++ fn without(&self, removed: &BTreeSet<Spelled>) -> BTreeSet<Spelled> {+ self.asserted+ .iter()+ .filter(|t| !removed.contains(*t))+ .cloned()+ .collect()+ }+}++// ───────────────────────────────────────────────────────────────────────────+// One justification, read off the DAG+// ───────────────────────────────────────────────────────────────────────────++/// The asserted leaves of ONE derivation tree for the target.+///+/// Free: no re-run, just a walk. The result is a support set and is not+/// necessarily minimal, which is why nothing calls this without+/// [`minimise`] afterwards.+///+/// The instance chosen for each fact is the FIRST one the fixpoint found, and+/// that choice is what makes the walk terminate. A rule reads its premises out+/// of the closure as it stood at the start of a round, so the first instance+/// concluding a fact has every premise concluded in a strictly earlier round.+/// The visited set is belt and braces.+fn leaves(dg: &DerivationGraph, target: &Target) -> Option<BTreeSet<Spelled>> {+ let mut first: HashMap<&Spelled, &Vec<Spelled>> = HashMap::new();+ for inst in &dg.instances {+ first.entry(&inst.conclusion).or_insert(&inst.premises);+ }+ let asserted: HashSet<&Spelled> = dg.asserted.iter().collect();++ let mut work: Vec<Spelled> = match target {+ Target::Triple(t) => vec![t.clone()],+ Target::Inconsistency => {+ // Prefer a clash the Lean refutation checker can judge, so that a+ // certificate written for this justification carries a+ // `refutation.tsv` worth checking rather than only the derivation+ // steps.+ let clash = dg+ .clashes+ .iter()+ .find(|c| c.certifiable)+ .or_else(|| dg.clashes.first())?;+ clash.premises.clone()+ }+ };+ let mut seen: HashSet<Spelled> = HashSet::new();+ let mut out: BTreeSet<Spelled> = BTreeSet::new();+ while let Some(t) = work.pop() {+ if asserted.contains(&t) {+ out.insert(t);+ continue;+ }+ if !seen.insert(t.clone()) {+ continue;+ }+ let premises = first.get(&t)?;+ work.extend(premises.iter().cloned());+ }+ Some(out)+}++/// Shrink a support set to a minimal one, one element at a time.+///+/// `|candidate|` oracle calls. Linear minimisation is exact for a monotone+/// oracle: once an element has been shown removable it stays removable, because+/// removing more can only take conclusions away.+fn minimise(+ oracle: &mut Oracle<'_>,+ candidate: &BTreeSet<Spelled>,+) -> anyhow::Result<BTreeSet<Spelled>> {+ let mut cur = candidate.clone();+ for e in candidate.iter() {+ let mut trial = cur.clone();+ trial.remove(e);+ if trial.len() == cur.len() {+ continue;+ }+ if oracle.ask(&trial)?.is_some() {+ cur = trial;+ }+ }+ Ok(cur)+}++// ───────────────────────────────────────────────────────────────────────────+// All justifications: Reiter's hitting-set tree+// ───────────────────────────────────────────────────────────────────────────++struct Search {+ minas: Vec<BTreeSet<Spelled>>,+ truncated_by: Option<&'static str>,+ nodes_expanded: usize,+ reused: usize,+}++/// Enumerate justifications by hitting-set tree.+///+/// A node is a set `H` of removed triples. If the target survives `G \ H` there+/// is a justification disjoint from `H`, and every OTHER justification must+/// contain one of its elements, so the node branches on them. If the target+/// does not survive, `H` is a hitting set of all justifications and nothing+/// below it can be new.+fn hitting_set_tree(oracle: &mut Oracle<'_>, seed: BTreeSet<Spelled>, opts: &JustifyOptions) -> anyhow::Result<Search> {+ let mut s = Search {+ minas: vec![seed.clone()],+ truncated_by: None,+ nodes_expanded: 0,+ reused: 0,+ };+ let mut visited: HashSet<BTreeSet<Spelled>> = HashSet::new();+ let mut queue: VecDeque<BTreeSet<Spelled>> = VecDeque::new();+ for e in &seed {+ queue.push_back(BTreeSet::from([e.clone()]));+ }++ while let Some(h) = queue.pop_front() {+ if s.minas.len() >= opts.max_justifications {+ s.truncated_by = Some("max_justifications");+ break;+ }+ if oracle.calls >= opts.max_oracle_calls {+ s.truncated_by = Some("max_oracle_calls");+ break;+ }+ if !visited.insert(h.clone()) {+ continue;+ }+ s.nodes_expanded += 1;++ // Reuse: a known justification disjoint from `H` is still present in+ // `G \ H`, so the answer is known without a fixpoint. This is the+ // optimisation that makes the tree affordable at all.+ if let Some(m) = s.minas.iter().find(|m| m.is_disjoint(&h)).cloned() {+ s.reused += 1;+ for e in &m {+ let mut next = h.clone();+ next.insert(e.clone());+ queue.push_back(next);+ }+ continue;+ }++ let keep = oracle.without(&h);+ let Some(dg) = oracle.ask(&keep)? else {+ // `H` hits every justification. Closed.+ continue;+ };+ let Some(raw) = leaves(&dg, oracle.target) else {+ // The target holds but no derivation tree could be walked for it.+ // On a correct run this is unreachable; swallowing it would turn a+ // producer bug into a silently short list.+ anyhow::bail!(+ "the target holds over a subset but no derivation tree could be walked for it, \+ so the derivation DAG and the closure disagree. This is a bug in the producer; \+ please report it"+ );+ };+ let m = minimise(oracle, &raw)?;+ if !s.minas.contains(&m) {+ s.minas.push(m.clone());+ }+ for e in &m {+ let mut next = h.clone();+ next.insert(e.clone());+ queue.push_back(next);+ }+ }+ s.minas.sort_by(|a, b| a.len().cmp(&b.len()).then_with(|| a.iter().cmp(b.iter())));+ Ok(s)+}++// ───────────────────────────────────────────────────────────────────────────+// Checking a candidate someone else produced+// ───────────────────────────────────────────────────────────────────────────++/// What a candidate support set turned out to be.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum CandidateVerdict {+ /// The engine does not reach the target from this set at all.+ NotASupport,+ /// The target survives removing each of these, so the set blames triples+ /// that are not responsible.+ NotMinimal(Vec<Spelled>),+ /// Sufficient, and every element is necessary. Both halves re-run.+ MinimalJustification,+}++impl CandidateVerdict {+ pub fn name(&self) -> &'static str {+ match self {+ CandidateVerdict::NotASupport => "not_a_justification_target_not_reached",+ CandidateVerdict::NotMinimal(_) => "not_a_justification_not_minimal",+ CandidateVerdict::MinimalJustification => "minimal_justification",+ }+ }+}++// ───────────────────────────────────────────────────────────────────────────+// The entry point+// ───────────────────────────────────────────────────────────────────────────++/// Explain a conclusion, or a clash, in terms of the asserted triples.+pub fn justify(+ graph: &Arc<GraphStore>,+ target_text: Option<&str>,+ inconsistency: bool,+ candidate: Option<&[String]>,+ opts: &JustifyOptions,+) -> anyhow::Result<serde_json::Value> {+ if target_text.is_some() == inconsistency {+ anyhow::bail!(+ "ask about exactly one of `triple` and `inconsistency`. Explaining everything at once \+ is a different question with a different cost"+ );+ }+ if opts.profile == "owl-dl" {+ anyhow::bail!(+ "owl-dl records no rule applications, so there is no derivation to walk and no \+ justification to extract. Run rdfs, owl-rl or owl-rl-ext"+ );+ }++ // Blank nodes do not survive being written out and read back: every oracle+ // call rebuilds a store from a subset of triples, and the parser may+ // relabel. Skolemising once, up front, is what makes a subset comparable to+ // the whole. `crate::projection_entailment` owns that function and the+ // reasons are in its docstring.+ let (sk, _map) = crate::projection_entailment::skolemise(graph)?;++ let target = match target_text {+ Some(t) => Target::Triple(parse_triple(t)?),+ None => Target::Inconsistency,+ };++ let full = Reasoner::derivation_graph(&sk, &opts.profile)?;+ let asserted: Vec<Spelled> = full.asserted.clone();++ let target_json = match &target {+ Target::Triple(t) => triple_out(t),+ Target::Inconsistency => serde_json::json!("inconsistency"),+ };+ let mut out = serde_json::json!({+ "target": target_json,+ "target_kind": target.label(),+ "profile_used": full.profile_used,+ "asserted": asserted.len(),+ "closure": full.closure.len(),+ "rule_instances": full.instances.len(),+ "fixpoint_reached": full.fixpoint_reached,+ "means": ENGINE_CAVEAT,+ });+ if let Target::Inconsistency = target {+ out["verdict_explained"] = serde_json::json!("clash_found_by_this_engine");+ out["verdict_means"] = serde_json::json!(+ "the justifications below explain a contradiction THIS ENGINE found, under ten of the \+ seventeen OWL 2 RL rules that conclude false. They are not an explanation of \+ unsatisfiability, and `oo-refute`'s `unsatisfiable_under_disjointness` is a different \+ word for a different, checked, result"+ );+ out["clashes_found"] = serde_json::json!(full.clashes.len());+ }+ if !full.fixpoint_reached {+ out["fixpoint_warning"] = serde_json::json!(+ "the reasoner stopped at its iteration cap rather than a fixpoint, so the closure is \+ a LOWER BOUND. A justification search over a partial closure can miss justifications \+ and can call a set minimal that is not, because the removal test is run against the \+ same partial closure"+ );+ }++ if !target.holds(&full) {+ out["reached"] = serde_json::json!(false);+ out["justifications"] = serde_json::json!([]);+ let note = match target {+ Target::Triple(_) => {+ "this engine does not derive that triple from the loaded graph under this \+ profile, so there is nothing to explain. That is not a non-entailment result"+ }+ Target::Inconsistency => {+ "this engine found no clash in the closure it computed. That is NOT a consistency \+ result: seven of the seventeen rules that conclude false are not looked for at \+ all, and a TBox unsatisfiable with no individual asserted is invisible to this \+ route"+ }+ };+ out["note"] = serde_json::json!(note);+ return Ok(out);+ }+ out["reached"] = serde_json::json!(true);++ let mut oracle = Oracle::new(asserted.clone(), &target, &opts.profile);++ // ── The candidate path: check, do not search ────────────────────────+ if let Some(cand) = candidate {+ let mut parsed: BTreeSet<Spelled> = BTreeSet::new();+ let asserted_set: HashSet<&Spelled> = asserted.iter().collect();+ let mut not_asserted: Vec<Spelled> = Vec::new();+ for c in cand {+ let t = parse_triple(c)?;+ if !asserted_set.contains(&t) {+ not_asserted.push(t.clone());+ }+ parsed.insert(t);+ }+ let verdict = if oracle.ask(&parsed)?.is_none() {+ CandidateVerdict::NotASupport+ } else {+ let mut removable: Vec<Spelled> = Vec::new();+ for e in parsed.iter() {+ let mut trial = parsed.clone();+ trial.remove(e);+ if oracle.ask(&trial)?.is_some() {+ removable.push(e.clone());+ }+ }+ if removable.is_empty() {+ CandidateVerdict::MinimalJustification+ } else {+ CandidateVerdict::NotMinimal(removable)+ }+ };+ let removable: Vec<serde_json::Value> = match &verdict {+ CandidateVerdict::NotMinimal(rs) => rs.iter().map(triple_out).collect(),+ _ => Vec::new(),+ };+ let means = match &verdict {+ CandidateVerdict::NotASupport => {+ "running the engine over exactly this set does not reach the target, so it is \+ not a support at all"+ }+ CandidateVerdict::NotMinimal(_) => {+ "the target survives removing each triple under `removable`, so this set blames \+ triples that are not responsible for it. Every element of a justification must \+ be necessary"+ }+ CandidateVerdict::MinimalJustification => {+ "the engine reaches the target from this set, and loses it when any one element \+ is removed. Both halves were re-run, neither is machine-checked"+ }+ };+ out["candidate"] = serde_json::json!({+ "size": parsed.len(),+ "triples": parsed.iter().map(triple_out).collect::<Vec<_>>(),+ "verdict": verdict.name(),+ "not_in_the_asserted_graph": not_asserted.iter().map(triple_out).collect::<Vec<_>>(),+ "removable": removable,+ "means": means,+ "checks_run": parsed.len() + 1,+ });+ out["oracle_calls"] = serde_json::json!(oracle.calls);+ out["searched"] = serde_json::json!(false);+ if oracle.hit_iteration_cap {+ out["iteration_cap_hit_during_search"] = serde_json::json!(true);+ }+ return Ok(out);+ }++ // ── The search path ─────────────────────────────────────────────────+ let Some(raw) = leaves(&full, &target) else {+ anyhow::bail!(+ "the target holds but no derivation tree could be walked for it, so the derivation \+ DAG and the closure disagree. This is a bug in the producer; please report it"+ );+ };+ let from_dag = raw.len();+ let seed = minimise(&mut oracle, &raw)?;+ let search = hitting_set_tree(&mut oracle, seed, opts)?;++ // ── Minimality, verified rather than argued ─────────────────────────+ //+ // Every element of every reported justification is removed and the engine+ // is run again. The claim in the payload is exactly what these runs show+ // and never more.+ let mut verified = true;+ let mut failures: Vec<serde_json::Value> = Vec::new();+ let mut justifications: Vec<serde_json::Value> = Vec::new();+ for m in &search.minas {+ let sufficient = oracle.ask(m)?.is_some();+ if !sufficient {+ verified = false;+ failures.push(serde_json::json!({+ "kind": "not_sufficient",+ "justification": m.iter().map(triple_out).collect::<Vec<_>>(),+ }));+ }+ let mut necessary = true;+ for e in m.iter() {+ let mut trial = m.clone();+ trial.remove(e);+ if oracle.ask(&trial)?.is_some() {+ necessary = false;+ verified = false;+ failures.push(serde_json::json!({+ "kind": "element_not_necessary",+ "triple": triple_out(e),+ }));+ }+ }+ let sufficiency = if sufficient {+ "re_run_and_reached"+ } else {+ "RE_RUN_AND_NOT_REACHED"+ };+ let minimality = if necessary {+ "verified_by_re_running_the_fixpoint_without_each_element"+ } else {+ "FAILED: the target survived removing an element"+ };+ justifications.push(serde_json::json!({+ "size": m.len(),+ "triples": m.iter().map(triple_out).collect::<Vec<_>>(),+ "sufficiency": sufficiency,+ "minimality": minimality,+ "removal_checks": m.len(),+ }));+ }++ out["searched"] = serde_json::json!(true);+ out["justifications"] = serde_json::json!(justifications);+ out["justification_count"] = serde_json::json!(search.minas.len());+ out["first_justification_from_the_dag"] = serde_json::json!({+ "size": from_dag,+ "means": "the asserted leaves of ONE derivation tree, read off the DAG with no re-run. \+ It is a support and is not necessarily minimal; it was shrunk by the oracle \+ before being reported, and it seeded the hitting-set tree",+ });+ out["truncated"] = serde_json::json!(search.truncated_by.is_some());+ out["complete"] = serde_json::json!(search.truncated_by.is_none());+ match search.truncated_by {+ Some(bound) => {+ let value = if bound == "max_justifications" {+ opts.max_justifications+ } else {+ opts.max_oracle_calls+ };+ out["truncation"] = serde_json::json!({+ "bound": bound,+ "value": value,+ "means": "the hitting-set tree stopped at a bound rather than because it had \+ closed, so there may be justifications this list does not contain. \+ Every justification IN it is still sufficient and minimal, both \+ re-run. Raise the bound to continue",+ });+ }+ None => {+ out["completeness_means"] = serde_json::json!(+ "the hitting-set tree closed without hitting a bound, so under Reiter's \+ construction this is EVERY justification, provided the oracle is monotone. This \+ engine has one non-monotone corner: a restriction node or list node carrying two \+ values for a functional position contributes one, chosen by hash order. Where \+ that occurs a justification can be missed. No listed justification can be \+ wrong, because each was re-run"+ );+ }+ }+ out["minimality_verified"] = serde_json::json!(verified);+ if !verified {+ out["minimality_failures"] = serde_json::json!(failures);+ out["minimality_failure_means"] = serde_json::json!(+ "a justification failed its own re-run check. That is a defect in this tool or a \+ non-monotone corner of the engine, it is reported rather than hidden, and the list \+ above must not be trusted. Please report it"+ );+ }+ out["oracle_calls"] = serde_json::json!(oracle.calls);+ out["oracle"] = serde_json::json!(+ "one full re-run of this engine's fixpoint over a subset of the asserted graph. Nodes \+ expanded and justifications reused are reported so the cost is legible. oracle_calls is \+ the number of runs actually made and can exceed max_oracle_calls, which is checked \+ between nodes and does not stop the verification pass"+ );+ out["nodes_expanded"] = serde_json::json!(search.nodes_expanded);+ out["nodes_answered_without_a_re_run"] = serde_json::json!(search.reused);+ if oracle.hit_iteration_cap {+ out["iteration_cap_hit_during_search"] = serde_json::json!(true);+ out["iteration_cap_means"] = serde_json::json!(+ "at least one re-run stopped at the iteration cap instead of a fixpoint, so at least \+ one answer above is about a partial closure. Raise reasoner.max_iterations and run \+ again before believing the list"+ );+ }++ // ── Certificates, the one half a theorem covers ─────────────────────+ if let Some(dir) = &opts.certificate_dir {+ let mut written: Vec<serde_json::Value> = Vec::new();+ for (i, m) in search.minas.iter().enumerate() {+ let sub = dir.join(format!("justification-{i}"));+ let store = Oracle::store_of(m)?;+ let report = Reasoner::run_full(+ &store,+ &opts.profile,+ false,+ InferenceTarget::DefaultGraph,+ Some(&sub),+ )?;+ let parsed: serde_json::Value = serde_json::from_str(&report)?;+ written.push(serde_json::json!({+ "index": i,+ "dir": sub.display().to_string(),+ "derivations": parsed["certificate"]["derivations"],+ "refutation": parsed["inconsistency"]["refutation"]["written"],+ "check_with": check_command(&sub, &target),+ }));+ }+ out["certificates"] = serde_json::json!(written);+ out["certificates_mean"] = serde_json::json!(+ "one certified run per justification, over exactly that justification's triples. \+ `oo-cert` accepting one establishes SUFFICIENCY under OOCert.certificate_sound: the \+ conclusion really does follow from that subset. It says NOTHING about minimality, \+ which only the removal re-runs above support, and nothing about the list being \+ complete"+ );+ }++ Ok(out)+}++fn check_command(dir: &Path, target: &Target) -> String {+ match target {+ Target::Triple(_) => format!(+ "cd lean && lake exe oo-cert {a} {d}",+ a = dir.join("asserted.tsv").display(),+ d = dir.join("derivations.tsv").display()+ ),+ Target::Inconsistency => format!(+ "cd lean && lake exe oo-refute check {a} {r} (only when refutation is true; \+ cax-dw is the one clash rule the checker has a semantic condition for)",+ a = dir.join("asserted.tsv").display(),+ r = dir.join("refutation.tsv").display()+ ),+ }+}diff --git a/src/lib.rs b/src/lib.rsindex f9b48727..3cd79a46 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -76,6 +76,12 @@ pub mod plugins;pub mod poincare;pub mod reason;pub mod reason_incremental;+/// Provenance semirings over the derivation DAG: what algebraic expression+/// over the asserted triples a derived triple carries.+pub mod provenance;+/// Axiom pinpointing: the minimal sets of asserted triples responsible for a+/// conclusion, or for a clash. Built over `provenance`'s DAG index.+pub mod justify;/// Standard rule syntaxes (SWRL, RIF Core) into the Horn rule table/// `reason::run_horn` evaluates and `lean/`'s `oo-horn` checks.pub mod rulesyntax;diff --git a/src/provenance.rs b/src/provenance.rsnew file mode 100644index 00000000..459fc072--- /dev/null+++ b/src/provenance.rs@@ -0,0 +1,977 @@+//! Provenance semirings over the derivation DAG the reasoner already builds.+//!+//! Every derived triple carries an algebraic expression over the ASSERTED+//! triples, computed by evaluating the fixpoint a second time with the truth+//! values replaced by elements of a commutative semiring. That is Green,+//! Karvounarakis and Tannen's construction, applied to the rule table in+//! [`crate::reason`] rather than to relational algebra.+//!+//! # The substrate is the DAG, not the certificate+//!+//! `derivations.tsv` records ONE step per inferred triple, the first the+//! fixpoint reached. A polynomial built from that file would have one monomial+//! wherever the closure supports several, which is a false statement about+//! where the conclusion came from rather than a coarse one. So this module asks+//! [`Reasoner::derivation_graph`] for every applicable ground rule instance and+//! evaluates over that.+//!+//! # Recursion is where provenance goes wrong quietly+//!+//! Datalog is recursive, and under recursion the provenance series of the free+//! semiring N[X] is INFINITE: a triple on a cycle has arbitrarily many proof+//! trees, so its counting annotation diverges and its how-provenance polynomial+//! does not exist as a polynomial. Producing a finite answer anyway and not+//! saying so is the failure this module is written to avoid.+//!+//! Two honest answers exist and both are implemented.+//!+//! * **Absorptive and finite-lattice semirings converge.** `why`, `lineage`,+//! `boolean`, `trust` (max-min) and `tropical` (min-plus over non-negative+//! weights) all reach a fixpoint in finitely many rounds over a finite+//! closure, and the report says the iteration stabilised. `why`, `trust` and+//! `tropical` are absorptive, so a derivation that goes round a cycle is+//! absorbed by the one that does not. `boolean` and `lineage` are NOT+//! absorptive; they converge because their value lattices are finite and the+//! iteration is monotone in them. Both reasons are stated per semiring rather+//! than collapsed into the word "converges".+//! * **`counting` does not converge, and is bounded and reported.** Round `k`+//! of the iteration computes the annotation over proof trees of HEIGHT AT+//! MOST `k`, so stopping at `depth_bound` gives a LOWER BOUND, the bound is+//! in the payload, and `value_is_exact` is false unless the iteration+//! stabilised on its own. `cycle_in_support` says whether the target's own+//! support contains a cycle, which is the structural reason a count cannot+//! be exact.+//!+//! # What an annotation is a claim about+//!+//! The rule table is this engine's 29 of OWL 2 RL's 78 rules, so a monomial is+//! a claim about what THIS engine derived and not about OWL 2 RL entailment.+//! The soundness of each step is the Lean layer's business+//! (`OOCert.certificate_sound`); nothing here is machine-checked, and the+//! separate `onto_justify` is where a support set is verified by re-running the+//! engine rather than read off an algebra.++use crate::graph::GraphStore;+use crate::projection_entailment::SKOLEM_PREFIX;+use crate::reason::{DerivationGraph, Reasoner, Spelled};+use std::collections::{BTreeMap, BTreeSet, HashMap};+use std::sync::Arc;++/// Rounds of the annotated fixpoint run by default.+///+/// A round is a derivation-depth step, so this is the maximum proof-tree height+/// a non-convergent semiring's answer covers. Absorptive semirings stabilise+/// long before it on every ontology this repository ships.+pub const DEFAULT_DEPTH_BOUND: usize = 32;++/// Monomials kept per fact in the `why` semiring before truncation.+///+/// Why-provenance is worst-case exponential in the size of the closure. When+/// the cap bites, the monomials KEPT are the smallest ones, which is what makes+/// the surviving set still an antichain: a dropped monomial cannot be a proper+/// subset of a kept one, because a proper subset is strictly smaller and would+/// have been kept first.+pub const DEFAULT_MAX_MONOMIALS: usize = 64;++// ───────────────────────────────────────────────────────────────────────────+// The semirings+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub enum Semiring {+ /// `({false, true}, ∨, ∧, false, true)`. Derivability and nothing else.+ Boolean,+ /// Why-provenance: sets of sets of asserted triples, `⊕` union then+ /// absorption, `⊗` pairwise union. The minimal elements are the+ /// justifications.+ Why,+ /// Lineage, Green et al.'s `Which(X)`: `(𝒫(X) ∪ {⊥}, ∪, ∪, ⊥, ∅)`. Which+ /// asserted triples contributed AT ALL, with no record of how they combine.+ Lineage,+ /// `(ℕ, +, ×, 0, 1)`. The number of proof trees. DIVERGES under recursion.+ Counting,+ /// Min-plus over `[0, ∞]`: `⊕ = min`, `⊗ = +`, `0̄ = ∞`, `1̄ = 0`. The+ /// cheapest proof tree, summing the weights of its leaves with+ /// multiplicity. Absorptive only because weights are required to be+ /// non-negative.+ TropicalMinPlus,+ /// Max-min over `[0, 1]`: `⊕ = max`, `⊗ = min`, `0̄ = 0`, `1̄ = 1`. The+ /// confidence of the best derivation, which is the confidence of its+ /// weakest premise. Absorptive.+ TrustMaxMin,+}++impl Semiring {+ pub fn name(self) -> &'static str {+ match self {+ Semiring::Boolean => "boolean",+ Semiring::Why => "why",+ Semiring::Lineage => "lineage",+ Semiring::Counting => "counting",+ Semiring::TropicalMinPlus => "tropical",+ Semiring::TrustMaxMin => "trust",+ }+ }++ pub fn parse(s: &str) -> Option<Semiring> {+ match s {+ "boolean" | "bool" => Some(Semiring::Boolean),+ "why" | "why_provenance" => Some(Semiring::Why),+ "lineage" | "which" => Some(Semiring::Lineage),+ "counting" | "count" | "n" => Some(Semiring::Counting),+ "tropical" | "min_plus" | "min-plus" => Some(Semiring::TropicalMinPlus),+ "trust" | "max_min" | "max-min" | "fuzzy" => Some(Semiring::TrustMaxMin),+ _ => None,+ }+ }++ pub fn all() -> Vec<Semiring> {+ vec![+ Semiring::Boolean,+ Semiring::Why,+ Semiring::Lineage,+ Semiring::Counting,+ Semiring::TropicalMinPlus,+ Semiring::TrustMaxMin,+ ]+ }++ /// Whether `a ⊕ (a ⊗ b) = a`, which is what makes a recursive fixpoint+ /// stop: a derivation that passes through a cycle is absorbed by the+ /// shorter one it contains.+ pub fn absorptive(self) -> bool {+ matches!(+ self,+ Semiring::Why | Semiring::TropicalMinPlus | Semiring::TrustMaxMin+ )+ }++ /// Why this semiring's fixpoint terminates, or that it does not. One+ /// sentence, carried in the payload so a reader never has to infer it.+ pub fn convergence(self) -> &'static str {+ match self {+ Semiring::Boolean =>+ "converges: not absorptive, but its value lattice has two elements and the \+ iteration is monotone in it",+ Semiring::Why =>+ "converges: absorptive, so a derivation that goes round a cycle is absorbed by \+ the one that does not. Worst-case exponential in the size of the closure, which \+ is what max_monomials bounds",+ Semiring::Lineage =>+ "converges: NOT absorptive (a + a·b = a ∪ b, not a), but its values are subsets \+ of a finite set and the iteration only grows them",+ Semiring::Counting =>+ "DOES NOT CONVERGE under recursion: a triple on a cycle has arbitrarily many \+ proof trees. Round k counts proof trees of height at most k, so the answer is a \+ LOWER BOUND whenever the iteration did not stabilise on its own, and \+ depth_bound is in the payload",+ Semiring::TropicalMinPlus =>+ "converges: absorptive PROVIDED every weight is non-negative, since min(a, a+b) \+ = a needs b >= 0. A negative weight is refused rather than silently diverging",+ Semiring::TrustMaxMin =>+ "converges: absorptive, max(a, min(a, b)) = a for all a and b",+ }+ }++ /// What the annotation means, in the payload beside the number.+ pub fn means(self) -> &'static str {+ match self {+ Semiring::Boolean => "true when this engine derives the triple at all",+ Semiring::Why =>+ "each monomial is the set of asserted triples at the leaves of one proof tree, \+ and the set of monomials is an antichain: no monomial contains another. Under \+ an untruncated, stabilised run over a MONOTONE rule table they coincide with the \+ minimal supports. They are computed from the derivation DAG rather than by \+ re-running the engine, and onto_justify is the tool that re-runs it and names \+ the one corner of this engine that is not monotone",+ Semiring::Lineage =>+ "the union of every asserted triple that contributes to any derivation. It is \+ the coarsest useful answer: it says WHICH triples are involved and never how \+ they combine, so it is NOT a justification and is usually far from minimal",+ Semiring::Counting =>+ "the number of distinct proof trees of height at most depth_bound. Read \+ value_is_exact before reading the number",+ Semiring::TropicalMinPlus =>+ "the total weight of the cheapest proof tree, summing the weight of each leaf \+ once per occurrence. Default weight 1.0 per asserted triple, so the default \+ reading is the size of the smallest proof tree counted with multiplicity",+ Semiring::TrustMaxMin =>+ "the confidence of the best derivation, where a derivation is only as good as \+ its weakest premise. Default weight 1.0 per asserted triple, so the default \+ reading is trivially 1.0 and the semiring is only interesting with weights",+ }+ }+}++// ───────────────────────────────────────────────────────────────────────────+// Values+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, PartialEq)]+enum Val {+ Bool(bool),+ /// An antichain of monomials over asserted-variable indices, sorted by+ /// (size, contents) so the representation is canonical.+ Why(Vec<BTreeSet<u32>>),+ /// `None` is `⊥`, the zero.+ Lineage(Option<BTreeSet<u32>>),+ /// The count, and whether it hit the ceiling of the counter.+ Count(u128, bool),+ /// Min-plus. `f64::INFINITY` is the zero.+ Cost(f64),+ /// Max-min. `0.0` is the zero.+ Trust(f64),+}++impl Val {+ fn zero(sem: Semiring) -> Val {+ match sem {+ Semiring::Boolean => Val::Bool(false),+ Semiring::Why => Val::Why(Vec::new()),+ Semiring::Lineage => Val::Lineage(None),+ Semiring::Counting => Val::Count(0, false),+ Semiring::TropicalMinPlus => Val::Cost(f64::INFINITY),+ Semiring::TrustMaxMin => Val::Trust(0.0),+ }+ }++ fn is_zero(&self) -> bool {+ match self {+ Val::Bool(b) => !b,+ Val::Why(ms) => ms.is_empty(),+ Val::Lineage(l) => l.is_none(),+ Val::Count(n, sat) => *n == 0 && !sat,+ Val::Cost(c) => c.is_infinite(),+ Val::Trust(t) => *t == 0.0,+ }+ }++ /// The annotation an asserted triple starts with: its own variable, or its+ /// weight.+ fn base(sem: Semiring, var: u32, weight: f64) -> Val {+ match sem {+ Semiring::Boolean => Val::Bool(true),+ Semiring::Why => Val::Why(vec![BTreeSet::from([var])]),+ Semiring::Lineage => Val::Lineage(Some(BTreeSet::from([var]))),+ Semiring::Counting => Val::Count(1, false),+ Semiring::TropicalMinPlus => Val::Cost(weight),+ Semiring::TrustMaxMin => Val::Trust(weight),+ }+ }++ /// The multiplicative identity, which is what an empty body would+ /// evaluate to. No rule in the table has an empty body; the fold starts+ /// here regardless, so the code says what it means.+ fn one(sem: Semiring) -> Val {+ match sem {+ Semiring::Boolean => Val::Bool(true),+ Semiring::Why => Val::Why(vec![BTreeSet::new()]),+ Semiring::Lineage => Val::Lineage(Some(BTreeSet::new())),+ Semiring::Counting => Val::Count(1, false),+ Semiring::TropicalMinPlus => Val::Cost(0.0),+ Semiring::TrustMaxMin => Val::Trust(1.0),+ }+ }+}++/// `⊕`, with the why-semiring's absorption and truncation folded in. Returns+/// whether the cap discarded a monomial.+fn plus(a: &Val, b: &Val, max_monomials: usize) -> (Val, bool) {+ match (a, b) {+ (Val::Bool(x), Val::Bool(y)) => (Val::Bool(*x || *y), false),+ (Val::Why(x), Val::Why(y)) => {+ let mut all = x.clone();+ all.extend(y.iter().cloned());+ let (v, t) = normalise_why(all, max_monomials);+ (Val::Why(v), t)+ }+ (Val::Lineage(x), Val::Lineage(y)) => (+ Val::Lineage(match (x, y) {+ (None, other) => other.clone(),+ (some, None) => some.clone(),+ (Some(p), Some(q)) => Some(p.union(q).copied().collect()),+ }),+ false,+ ),+ (Val::Count(x, sx), Val::Count(y, sy)) => {+ let (n, over) = x.overflowing_add(*y);+ let saturated = *sx || *sy || over;+ (+ Val::Count(if over { u128::MAX } else { n }, saturated),+ false,+ )+ }+ (Val::Cost(x), Val::Cost(y)) => (Val::Cost(x.min(*y)), false),+ (Val::Trust(x), Val::Trust(y)) => (Val::Trust(x.max(*y)), false),+ // Unreachable: one semiring is chosen per evaluation and every value in+ // it is built by this module. A mismatch would be a bug here, and+ // returning `a` would hide it, so it is loud.+ _ => unreachable!("provenance values of two different semirings were combined"),+ }+}++/// `⊗`.+fn times(a: &Val, b: &Val, max_monomials: usize) -> (Val, bool) {+ match (a, b) {+ (Val::Bool(x), Val::Bool(y)) => (Val::Bool(*x && *y), false),+ (Val::Why(x), Val::Why(y)) => {+ if x.is_empty() || y.is_empty() {+ return (Val::Why(Vec::new()), false);+ }+ let mut prod: Vec<BTreeSet<u32>> = Vec::with_capacity(x.len() * y.len());+ for m in x {+ for n in y {+ prod.push(m.union(n).copied().collect());+ }+ }+ let (v, t) = normalise_why(prod, max_monomials);+ (Val::Why(v), t)+ }+ (Val::Lineage(x), Val::Lineage(y)) => (+ Val::Lineage(match (x, y) {+ (None, _) | (_, None) => None,+ (Some(p), Some(q)) => Some(p.union(q).copied().collect()),+ }),+ false,+ ),+ (Val::Count(x, sx), Val::Count(y, sy)) => {+ let (n, over) = x.overflowing_mul(*y);+ let zero = *x == 0 || *y == 0;+ let saturated = !zero && (*sx || *sy || over);+ (+ Val::Count(if over { u128::MAX } else { n }, saturated),+ false,+ )+ }+ (Val::Cost(x), Val::Cost(y)) => (Val::Cost(x + y), false),+ (Val::Trust(x), Val::Trust(y)) => (Val::Trust(x.min(*y)), false),+ _ => unreachable!("provenance values of two different semirings were combined"),+ }+}++/// Absorb and cap a bag of monomials.+///+/// Sorting by size first is what makes both halves correct at once. Absorption+/// then only ever has to test a candidate against sets no larger than itself,+/// and the cap keeps the SMALLEST monomials, so a discarded monomial can never+/// be a proper subset of a kept one and the survivors are still an antichain.+fn normalise_why(mut ms: Vec<BTreeSet<u32>>, max_monomials: usize) -> (Vec<BTreeSet<u32>>, bool) {+ ms.sort_by(|a, b| {+ a.len()+ .cmp(&b.len())+ .then_with(|| a.iter().cmp(b.iter()))+ });+ ms.dedup();+ let mut kept: Vec<BTreeSet<u32>> = Vec::new();+ for m in ms {+ if kept.iter().any(|k| k.is_subset(&m)) {+ continue;+ }+ kept.push(m);+ }+ let truncated = kept.len() > max_monomials;+ if truncated {+ kept.truncate(max_monomials);+ }+ (kept, truncated)+}++// ───────────────────────────────────────────────────────────────────────────+// The DAG, indexed+// ───────────────────────────────────────────────────────────────────────────++/// The derivation DAG with triples replaced by indices, which is the shape the+/// annotated fixpoint iterates over.+pub struct Dag {+ /// Every triple in the closure, sorted, so ids are deterministic.+ pub facts: Vec<Spelled>,+ index: HashMap<Spelled, u32>,+ /// For each fact, the asserted-variable id when it was asserted.+ var_of: Vec<Option<u32>>,+ /// The asserted triples, sorted. A variable id indexes this.+ pub vars: Vec<Spelled>,+ /// For each fact, one entry per applicable rule instance concluding it.+ bodies: Vec<Vec<Vec<u32>>>,+ /// The rule name of each body, parallel to `bodies`.+ body_rules: Vec<Vec<&'static str>>,+ /// Instances dropped because a premise was not in the closure. Always zero+ /// on a run of this engine, reported because a non-zero value would mean+ /// the capture and the closure disagree and every answer below would be+ /// computed over a DAG missing hyperedges.+ pub instances_dropped: usize,+}++impl Dag {+ pub fn build(dg: &DerivationGraph) -> Dag {+ let mut facts: Vec<Spelled> = dg.closure.iter().cloned().collect();+ facts.sort();+ facts.dedup();+ let index: HashMap<Spelled, u32> = facts+ .iter()+ .enumerate()+ .map(|(i, f)| (f.clone(), i as u32))+ .collect();++ let mut vars: Vec<Spelled> = dg.asserted.clone();+ vars.sort();+ vars.dedup();+ let mut var_of: Vec<Option<u32>> = vec![None; facts.len()];+ for (vi, v) in vars.iter().enumerate() {+ if let Some(&fi) = index.get(v) {+ var_of[fi as usize] = Some(vi as u32);+ }+ }++ let mut bodies: Vec<Vec<Vec<u32>>> = vec![Vec::new(); facts.len()];+ let mut body_rules: Vec<Vec<&'static str>> = vec![Vec::new(); facts.len()];+ let mut dropped = 0usize;+ for inst in &dg.instances {+ let Some(&head) = index.get(&inst.conclusion) else {+ dropped += 1;+ continue;+ };+ let mut body: Vec<u32> = Vec::with_capacity(inst.premises.len());+ let mut ok = true;+ for p in &inst.premises {+ match index.get(p) {+ Some(&pi) => body.push(pi),+ None => {+ ok = false;+ break;+ }+ }+ }+ if !ok {+ dropped += 1;+ continue;+ }+ bodies[head as usize].push(body);+ body_rules[head as usize].push(inst.rule);+ }++ Dag {+ facts,+ index,+ var_of,+ vars,+ bodies,+ body_rules,+ instances_dropped: dropped,+ }+ }++ pub fn id(&self, t: &Spelled) -> Option<u32> {+ self.index.get(t).copied()+ }++ pub fn rules_for(&self, fact: u32) -> &[&'static str] {+ &self.body_rules[fact as usize]+ }++ pub fn bodies_for(&self, fact: u32) -> &[Vec<u32>] {+ &self.bodies[fact as usize]+ }++ /// Does the support of `target` contain a cycle?+ ///+ /// The structural reason a counting annotation cannot be exact. Answered+ /// over the sub-DAG reachable from the target through bodies, with an+ /// explicit stack rather than recursion, because a closure is not bounded+ /// in depth by anything.+ pub fn cycle_in_support(&self, target: u32) -> Option<Spelled> {+ #[derive(Clone, Copy, PartialEq)]+ enum Mark {+ White,+ Grey,+ Black,+ }+ let mut mark = vec![Mark::White; self.facts.len()];+ // (fact, index of the next premise to visit, flattened premise list)+ let mut stack: Vec<(u32, usize, Vec<u32>)> = Vec::new();+ let flat = |f: u32| -> Vec<u32> {+ let mut v: Vec<u32> = self.bodies[f as usize].iter().flatten().copied().collect();+ v.sort_unstable();+ v.dedup();+ v+ };+ mark[target as usize] = Mark::Grey;+ stack.push((target, 0, flat(target)));+ while let Some((f, i, prem)) = stack.pop() {+ if i == prem.len() {+ mark[f as usize] = Mark::Black;+ continue;+ }+ let next = prem[i];+ stack.push((f, i + 1, prem));+ match mark[next as usize] {+ Mark::Grey => return Some(self.facts[next as usize].clone()),+ Mark::Black => {}+ Mark::White => {+ mark[next as usize] = Mark::Grey;+ let p = flat(next);+ stack.push((next, 0, p));+ }+ }+ }+ None+ }+}++// ───────────────────────────────────────────────────────────────────────────+// The annotated fixpoint+// ───────────────────────────────────────────────────────────────────────────++/// What one semiring's evaluation produced.+pub struct Eval {+ values: Vec<Val>,+ /// The iteration reached a round that changed nothing.+ pub stabilised: bool,+ pub rounds: usize,+ pub depth_bound: usize,+ /// The why-semiring's monomial cap discarded something, somewhere.+ pub truncated: bool,+ /// A counter hit its ceiling, so the number below it is meaningless rather+ /// than merely a bound.+ pub saturated: bool,+}++/// Evaluate the whole closure under one semiring.+///+/// Round `k` computes the annotation over proof trees of height at most `k`,+/// which is what makes `depth_bound` a derivation-depth bound and not an+/// implementation detail.+pub fn evaluate(+ dag: &Dag,+ sem: Semiring,+ depth_bound: usize,+ max_monomials: usize,+ weights: &BTreeMap<Spelled, f64>,+) -> Eval {+ let n = dag.facts.len();+ let base: Vec<Val> = (0..n)+ .map(|i| match dag.var_of[i] {+ // An asserted triple with no weight supplied is weighted 1.0 in+ // both scalar semirings. Under min-plus that makes the annotation+ // the size of the smallest proof tree; under max-min it makes every+ // annotation 1.0, which is the honest reading of "nobody said how+ // much they trust anything".+ Some(v) => Val::base(sem, v, weights.get(&dag.facts[i]).copied().unwrap_or(1.0)),+ None => Val::zero(sem),+ })+ .collect();++ let mut cur = base.clone();+ let mut stabilised = false;+ let mut rounds = 0usize;+ let mut truncated = false;+ for _ in 0..depth_bound {+ rounds += 1;+ let mut next = Vec::with_capacity(n);+ for (i, b) in base.iter().enumerate() {+ let mut acc = b.clone();+ for body in &dag.bodies[i] {+ let mut prod = Val::one(sem);+ let mut dead = false;+ for &p in body {+ let (v, t) = times(&prod, &cur[p as usize], max_monomials);+ truncated |= t;+ prod = v;+ if prod.is_zero() {+ dead = true;+ break;+ }+ }+ if dead {+ continue;+ }+ let (v, t) = plus(&acc, &prod, max_monomials);+ truncated |= t;+ acc = v;+ }+ next.push(acc);+ }+ if next == cur {+ stabilised = true;+ break;+ }+ cur = next;+ }+ let saturated = cur+ .iter()+ .any(|v| matches!(v, Val::Count(_, true)));+ Eval {+ values: cur,+ stabilised,+ rounds,+ depth_bound,+ truncated,+ saturated,+ }+}++impl Eval {+ /// The annotation of one fact, rendered for the report.+ fn render(&self, sem: Semiring, dag: &Dag, fact: u32, used: &mut BTreeSet<u32>) -> serde_json::Value {+ let v = &self.values[fact as usize];+ let mut out = serde_json::json!({+ "semiring": sem.name(),+ "absorptive": sem.absorptive(),+ "convergence": sem.convergence(),+ "means": sem.means(),+ "stabilised": self.stabilised,+ "rounds_run": self.rounds,+ "depth_bound": self.depth_bound,+ });+ match v {+ Val::Bool(b) => {+ out["value"] = serde_json::json!(b);+ }+ Val::Why(ms) => {+ for m in ms {+ used.extend(m.iter().copied());+ }+ out["monomial_count"] = serde_json::json!(ms.len());+ out["monomials"] = serde_json::json!(+ ms.iter()+ .map(|m| serde_json::json!({+ "variables": m.iter().map(|v| var_name(*v)).collect::<Vec<_>>(),+ "size": m.len(),+ "triples": m+ .iter()+ .map(|v| triple_json(&dag.vars[*v as usize]))+ .collect::<Vec<_>>(),+ }))+ .collect::<Vec<_>>()+ );+ out["polynomial"] = serde_json::json!(polynomial(ms));+ out["truncated"] = serde_json::json!(self.truncated);+ out["monomials_are_minimal_supports"] = serde_json::json!(+ self.stabilised && !self.truncated+ );+ if self.truncated {+ out["truncation_means"] = serde_json::json!(+ "the monomial cap discarded derivations somewhere in this closure, so \+ this list may be INCOMPLETE and a monomial in it may not be minimal, \+ because the smaller monomial that would have absorbed it may be one of \+ the ones dropped at an intermediate fact. Every monomial listed is \+ still the leaf set of a real derivation. Raise max_monomials, or use \+ onto_justify, which verifies minimality by re-running the engine"+ );+ }+ }+ Val::Lineage(l) => match l {+ None => {+ out["value"] = serde_json::Value::Null;+ out["contributing"] = serde_json::json!([]);+ }+ Some(set) => {+ used.extend(set.iter().copied());+ out["size"] = serde_json::json!(set.len());+ out["contributing"] = serde_json::json!(+ set.iter()+ .map(|v| triple_json(&dag.vars[*v as usize]))+ .collect::<Vec<_>>()+ );+ }+ },+ Val::Count(n, sat) => {+ out["value"] = serde_json::json!(n.to_string());+ out["saturated"] = serde_json::json!(sat);+ out["value_is_exact"] = serde_json::json!(self.stabilised && !sat);+ if *sat {+ out["saturation_means"] = serde_json::json!(+ "the proof-tree count exceeded a 128-bit counter, so the number above is \+ the counter's ceiling and not a count. It also makes `stabilised` \+ meaningless, because saturating arithmetic has a fixed point of its own"+ );+ } else if !self.stabilised {+ out["value_means"] = serde_json::json!(+ "a LOWER BOUND: the number of proof trees of height at most depth_bound. \+ The iteration had not stopped changing when the bound was reached"+ );+ }+ }+ Val::Cost(c) => {+ out["value"] = if c.is_finite() {+ serde_json::json!(c)+ } else {+ serde_json::Value::Null+ };+ out["zero_is"] = serde_json::json!("infinity, meaning no derivation");+ }+ Val::Trust(t) => {+ out["value"] = serde_json::json!(t);+ out["zero_is"] = serde_json::json!("0.0, meaning no derivation");+ }+ }+ out+ }+}++fn var_name(v: u32) -> String {+ format!("x{}", v + 1)+}++fn triple_json(t: &Spelled) -> serde_json::Value {+ serde_json::json!([t.0, t.1, t.2])+}++/// The canonical presentation of a why-provenance value, `x1*x2 + x3`.+fn polynomial(ms: &[BTreeSet<u32>]) -> String {+ if ms.is_empty() {+ return "0".to_string();+ }+ ms.iter()+ .map(|m| {+ if m.is_empty() {+ "1".to_string()+ } else {+ m.iter().map(|v| var_name(*v)).collect::<Vec<_>>().join("*")+ }+ })+ .collect::<Vec<_>>()+ .join(" + ")+}++// ───────────────────────────────────────────────────────────────────────────+// Blank nodes and target parsing, shared with `crate::justify`+// ───────────────────────────────────────────────────────────────────────────++/// Rewrite `_:label` to the Skolem IRI [`crate::projection_entailment::skolemise`]+/// would give it.+///+/// Both explanation tools reason over a skolemised copy of the store, because+/// every oracle call rebuilds a store from a subset of triples and a blank node+/// does not survive that: the parser is free to relabel it, and a target naming+/// `_:b0` would then name a different node in every re-run.+pub fn skolem_term(term: &str) -> String {+ match term.strip_prefix("_:") {+ Some(label) => format!("<{SKOLEM_PREFIX}{label}>"),+ None => term.to_string(),+ }+}++/// The inverse, for output: a reader asked about `_:b0` and must be answered+/// about `_:b0`.+pub fn unskolem_term(term: &str) -> String {+ let inner = term.strip_prefix('<').and_then(|t| t.strip_suffix('>'));+ match inner.and_then(|i| i.strip_prefix(SKOLEM_PREFIX)) {+ Some(label) => format!("_:{label}"),+ None => term.to_string(),+ }+}++pub fn unskolem_triple(t: &Spelled) -> Spelled {+ (+ unskolem_term(&t.0),+ unskolem_term(&t.1),+ unskolem_term(&t.2),+ )+}++pub fn triple_out(t: &Spelled) -> serde_json::Value {+ let u = unskolem_triple(t);+ serde_json::json!([u.0, u.1, u.2])+}++/// Read one N-Triples line into the spelling the store uses.+///+/// Blank nodes are skolemised BEFORE parsing, so the parser never sees one and+/// never gets the chance to relabel it. The round trip through a real store is+/// what makes the result byte-identical to what `asserted.tsv` would carry: a+/// literal written `"1"^^<http://www.w3.org/2001/XMLSchema#integer>` and one+/// written `"1"^^xsd:integer` must not become two different targets.+pub fn parse_triple(text: &str) -> anyhow::Result<Spelled> {+ let skolemised: String = text+ .split_whitespace()+ .map(skolem_term)+ .collect::<Vec<_>>()+ .join(" ");+ let line = if skolemised.trim_end().ends_with('.') {+ skolemised+ } else {+ format!("{skolemised} .")+ };+ let store = GraphStore::new();+ store.load_ntriples(&line).map_err(|e| {+ anyhow::anyhow!(+ "the target is not one N-Triples triple: {e}. Write it as `<s> <p> <o>` with full \+ IRIs in angle brackets, or a literal in quotes; prefixed names are not read here"+ )+ })?;+ let mut triples = store.all_triples()?;+ match triples.len() {+ 1 => Ok(triples.remove(0)),+ 0 => anyhow::bail!("the target parsed to no triple at all"),+ n => anyhow::bail!(+ "the target parsed to {n} triples; ask about one conclusion at a time"+ ),+ }+}++// ───────────────────────────────────────────────────────────────────────────+// The report+// ───────────────────────────────────────────────────────────────────────────++pub struct ProvenanceOptions {+ pub profile: String,+ pub semirings: Vec<Semiring>,+ pub depth_bound: usize,+ pub max_monomials: usize,+ /// Weight per asserted triple for `tropical` and `trust`. Absent means+ /// 1.0. Keys are in the store's own N-Triples spelling.+ pub weights: BTreeMap<Spelled, f64>,+}++impl Default for ProvenanceOptions {+ fn default() -> Self {+ Self {+ profile: "owl-rl".to_string(),+ semirings: Semiring::all(),+ depth_bound: DEFAULT_DEPTH_BOUND,+ max_monomials: DEFAULT_MAX_MONOMIALS,+ weights: BTreeMap::new(),+ }+ }+}++/// The sentence that travels with every provenance answer.+pub const RULE_TABLE_CAVEAT: &str =+ "an annotation is a statement about THIS ENGINE's rule table, 29 of OWL 2 RL's 78 rules, and \+ never about OWL 2 RL entailment. Nothing in this report is machine-checked: the Lean layer \+ certifies that a derivation step is sound, and no theorem here says a monomial is minimal or \+ that the list of them is complete. onto_justify verifies a support set by re-running the \+ engine without each of its elements; this tool does algebra.";++/// Annotate the closure and report the target's expression.+pub fn annotate(+ graph: &Arc<GraphStore>,+ target: Option<&str>,+ opts: &ProvenanceOptions,+) -> anyhow::Result<serde_json::Value> {+ let wants_trust = opts.semirings.contains(&Semiring::TrustMaxMin);+ for (t, w) in &opts.weights {+ if *w < 0.0 || !w.is_finite() {+ anyhow::bail!(+ "weight {w} on <{} {} {}> is not a finite non-negative number. min-plus is \+ absorptive only for non-negative weights, and with a negative one the recursive \+ fixpoint does not converge; refusing rather than looping",+ t.0,+ t.1,+ t.2+ );+ }+ // Max-min is a semiring on [0, 1] and its multiplicative identity is+ // 1. A weight above 1 is not merely unusual: `min(1, w) = 1`, so the+ // identity stops being an identity and a conjunction of premises comes+ // out SMALLER than the semiring says it should. The answer would be+ // wrong rather than surprising, so it is refused.+ if wants_trust && *w > 1.0 {+ anyhow::bail!(+ "weight {w} on <{} {} {}> is above 1.0 and the `trust` semiring was asked for. \+ Max-min is a semiring on [0, 1] whose multiplicative identity is 1, so a weight \+ above it breaks the identity and the annotation would be wrong rather than \+ merely odd. Use confidences in [0, 1] for `trust`, or drop `trust` and keep \+ `tropical`, which takes any non-negative weight",+ t.0,+ t.1,+ t.2+ );+ }+ }+ if opts.semirings.is_empty() {+ anyhow::bail!("no semiring was asked for, so there is nothing to compute");+ }++ let (sk, _map) = crate::projection_entailment::skolemise(graph)?;+ let dg = Reasoner::derivation_graph(&sk, &opts.profile)?;+ let dag = Dag::build(&dg);++ let target_triple = match target {+ Some(t) => Some(parse_triple(t)?),+ None => None,+ };++ let mut out = serde_json::json!({+ "profile_used": dg.profile_used,+ "asserted": dag.vars.len(),+ "closure": dag.facts.len(),+ "derived": dag.facts.len().saturating_sub(dag.vars.len()),+ "rule_instances": dg.instances.len(),+ "fixpoint_reached": dg.fixpoint_reached,+ "iterations": dg.iterations,+ "depth_bound": opts.depth_bound,+ "max_monomials": opts.max_monomials,+ "means": RULE_TABLE_CAVEAT,+ });+ if !dg.fixpoint_reached {+ out["fixpoint_warning"] = serde_json::json!(+ "the reasoner stopped at its iteration cap rather than a fixpoint, so the closure is \+ a LOWER BOUND and every annotation below is computed over a partial DAG. Raise \+ reasoner.max_iterations"+ );+ }+ if dag.instances_dropped > 0 {+ out["instances_dropped"] = serde_json::json!(dag.instances_dropped);+ out["instances_dropped_means"] = serde_json::json!(+ "a captured rule instance cited a premise that is not in the closure, which cannot \+ happen on a correct run and means the DAG below is missing hyperedges. Please report \+ this."+ );+ }++ let Some(tt) = target_triple else {+ out["note"] = serde_json::json!(+ "no target triple was given, so this is the shape of the DAG and nothing was \+ annotated. Pass `triple` to get an expression"+ );+ return Ok(out);+ };++ let Some(fid) = dag.id(&tt) else {+ out["target"] = triple_out(&tt);+ out["in_closure"] = serde_json::json!(false);+ out["note"] = serde_json::json!(+ "this engine does not derive that triple under this profile, so its annotation is \+ the semiring zero in every semiring and there is nothing to show. A triple absent \+ from the closure is NOT a non-entailment result: the rule table is 29 of OWL 2 RL's \+ 78 rules"+ );+ return Ok(out);+ };++ let cycle = dag.cycle_in_support(fid);+ let mut used: BTreeSet<u32> = BTreeSet::new();+ let mut sems = serde_json::Map::new();+ for &sem in &opts.semirings {+ let ev = evaluate(&dag, sem, opts.depth_bound, opts.max_monomials, &opts.weights);+ sems.insert(sem.name().to_string(), ev.render(sem, &dag, fid, &mut used));+ }++ out["target"] = triple_out(&tt);+ out["in_closure"] = serde_json::json!(true);+ out["target_is_asserted"] = serde_json::json!(dag.var_of[fid as usize].is_some());+ out["derivations_of_target"] = serde_json::json!(dag.bodies_for(fid).len());+ let mut by_rule: BTreeMap<&str, usize> = BTreeMap::new();+ for r in dag.rules_for(fid) {+ *by_rule.entry(r).or_default() += 1;+ }+ out["rules_concluding_target"] = serde_json::json!(by_rule);+ out["cycle_in_support"] = serde_json::json!(cycle.is_some());+ if let Some(c) = &cycle {+ out["cycle_witness"] = triple_out(c);+ out["cycle_means"] = serde_json::json!(+ "the target's own support contains a cycle, so it has proof trees of unbounded \+ height and the counting semiring CANNOT be exact here whatever depth_bound is set \+ to. The absorptive semirings are unaffected: a derivation through the cycle is \+ absorbed by the one that does not take it"+ );+ }+ out["variables"] = serde_json::json!(+ used.iter()+ .map(|v| (var_name(*v), triple_out(&dag.vars[*v as usize])))+ .collect::<serde_json::Map<String, serde_json::Value>>()+ );+ out["semirings"] = serde_json::Value::Object(sems);+ Ok(out)+}diff --git a/src/reason.rs b/src/reason.rsindex 0031eb12..4d039dee 100644--- a/src/reason.rs+++ b/src/reason.rs@@ -53,6 +53,109 @@ struct Derivation {premises: Vec<Fact>,}+// ── Reading the derivation DAG back ─────────────────────────────────────────+//+// `derivations.tsv` records ONE step per inferred triple: the first time the+// fixpoint reached it. That is the right thing for a certificate, because a+// checker re-derives and one derivation is all it needs, and it is the WRONG+// thing for explanation. A triple derived two independent ways has two+// justifications and the certificate shows one of them; a provenance polynomial+// with one monomial where the closure supports two is a false statement about+// where the conclusion came from.+//+// So explanation does not read the file. It asks the fixpoint for every ground+// rule instance it found applicable, which is the whole DAG rather than a+// spanning forest of it. The capture is opt-in, costs one branch per candidate+// triple on a run that did not ask for it, and is memory-proportional to the+// number of applicable instances rather than to the number of conclusions.+//+// The instances collected are those applicable in the FIXPOINT closure. The+// last round of the loop runs every rule over the complete closure and adds+// nothing, so every instance applicable at the fixpoint fires at least once and+// is recorded. Deduplication is by (rule, conclusion, premises).++/// A triple in the store's own N-Triples spelling, byte-identical to what+/// [`GraphStore::all_triples`] yields and to what `asserted.tsv` carries.+pub type Spelled = crate::projection_entailment::Spelled;++/// One ground rule instance the fixpoint found applicable: a rule, what it+/// concluded, and the premises it read in the order+/// `lean/OOCert/Rules.lean` documents for that rule.+///+/// Unlike a certificate line this is NOT unique per conclusion. Two instances+/// with the same conclusion are two independent derivations of it, and that is+/// exactly the fact [`crate::justify`] and [`crate::provenance`] exist to read.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RuleInstance {+ pub rule: &'static str,+ pub conclusion: Spelled,+ pub premises: Vec<Spelled>,+}++/// One way the closure contradicts itself, spelled out for a consumer that has+/// no interner.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ClashInstance {+ pub rule: &'static str,+ pub premises: Vec<Spelled>,+ /// Whether `lean/OOCert/Refute.lean` holds a semantic condition for this+ /// rule, so that a refutation naming it can be CHECKED rather than merely+ /// asserted. Exactly one rule qualifies; see [`CLASH_RULES_CERTIFIABLE`].+ pub certifiable: bool,+}++/// Everything one forward-chaining run knows about how it got where it got.+///+/// `closure` is what the run believes, `asserted` is what it started from, and+/// `instances` is every ground rule application that connects the two. The+/// three together are the derivation DAG: nodes are triples, and an instance is+/// a hyperedge from its premises to its conclusion.+#[derive(Clone, Debug)]+pub struct DerivationGraph {+ pub profile_used: String,+ /// Every triple the run started from, in store order.+ pub asserted: Vec<Spelled>,+ /// Every triple the run ended with, asserted ones included.+ pub closure: HashSet<Spelled>,+ /// Every applicable ground rule instance, in the order the fixpoint first+ /// found each one. That order is topological: a rule read its premises out+ /// of the closure as it stood at the START of the round, so every premise+ /// was concluded in a strictly earlier round or asserted.+ pub instances: Vec<RuleInstance>,+ /// False when the run stopped at the iteration cap instead of a fixpoint.+ /// The closure is then a LOWER BOUND and every answer computed from it is+ /// an answer about a partial closure.+ pub fixpoint_reached: bool,+ pub iterations: usize,+ /// The clashes [`find_clashes`] found over the closure. Ten of the+ /// seventeen OWL 2 RL rules that conclude `false` are looked for, so an+ /// empty list is NOT a consistency result.+ pub clashes: Vec<ClashInstance>,+ /// Conclusions refused for being unserialisable, and therefore neither+ /// materialised nor available as premises. A run with a non-zero count here+ /// derived LESS than its rule table licenses.+ pub refused_unserialisable: usize,+}++impl DerivationGraph {+ /// Is this triple in the closure?+ pub fn holds(&self, t: &Spelled) -> bool {+ self.closure.contains(t)+ }+ /// Was this triple asserted rather than derived?+ pub fn is_asserted(&self, t: &Spelled) -> bool {+ self.asserted.iter().any(|a| a == t)+ }+}++/// Collector threaded through the fixpoint when a caller asked for the DAG.+#[derive(Default)]+struct Capture {+ seen: HashSet<(&'static str, Fact, Vec<Fact>)>,+ instances: Vec<(&'static str, Fact, Vec<Fact>)>,+ out: Option<DerivationGraph>,+}+// ── The rules that conclude `false` ─────────────────────────────────────────//@@ -1122,6 +1225,52 @@ impl Reasoner {materialize: bool,target: InferenceTarget,certificate_dir: Option<&std::path::Path>,+ ) -> anyhow::Result<String> {+ Self::run_capturing(graph, profile, materialize, target, certificate_dir, None)+ }++ /// The whole derivation DAG of a run: every asserted triple, every triple+ /// the fixpoint reached, and EVERY applicable ground rule instance rather+ /// than one per conclusion.+ ///+ /// This is the substrate [`crate::justify`] and [`crate::provenance`] read.+ /// Nothing is materialised and no certificate is written: the caller gets+ /// the structure and decides what to do with it.+ ///+ /// Refuses `owl-dl` for the same reason `--certificate` does: the tableaux+ /// path has no rule trace, so there is no DAG to hand back and an empty one+ /// would read as "nothing was derived".+ pub fn derivation_graph(+ graph: &Arc<GraphStore>,+ profile: &str,+ ) -> anyhow::Result<DerivationGraph> {+ if profile == "owl-dl" {+ anyhow::bail!(+ "the owl-dl tableaux path records no rule applications, so there is no derivation \+ DAG to explain from; run rdfs, owl-rl or owl-rl-ext"+ );+ }+ let mut cap = Capture::default();+ Self::run_capturing(+ graph,+ profile,+ false,+ InferenceTarget::DefaultGraph,+ None,+ Some(&mut cap),+ )?;+ cap.out.ok_or_else(|| {+ anyhow::anyhow!("the reasoner returned without filling the derivation DAG; this is a bug")+ })+ }++ fn run_capturing(+ graph: &Arc<GraphStore>,+ profile: &str,+ materialize: bool,+ target: InferenceTarget,+ certificate_dir: Option<&std::path::Path>,+ capture: Option<&mut Capture>,) -> anyhow::Result<String> {// Delegate OWL-DL to tableaux reasonerif profile == "owl-dl" {@@ -1253,7 +1402,13 @@ impl Reasoner {// per inferred triple and `derivations.len() == inferred_count` is an// invariant the tests pin. Nothing here runs unless a certificate was// asked for: the hot path pays one branch per candidate triple.- let certify = certificate_dir.is_some();+ //+ // A capture asks for the same premise lists, so it turns `certify` on+ // too: the per-rule premise vectors are built behind that flag, and a+ // DAG whose hyperedges carried no premises would be a set of+ // disconnected nodes wearing the word "derivation".+ let mut capture = capture;+ let certify = certificate_dir.is_some() || capture.is_some();let mut derivations: Vec<Derivation> = Vec::new();let mut recorded: HashSet<Fact> = HashSet::new();@@ -1434,6 +1589,7 @@ impl Reasoner {let interner_ref = &interner;let refused_ref = &mut refused;let samples_ref = &mut skipped_samples;+ let mut cap_ref = capture.as_mut();let rv = &rule_vocab;let mut emit = |f: Fired| {let (rule, t) = match &f {@@ -1467,16 +1623,36 @@ impl Reasoner {}return;}- if certify && !triple_set.contains(&t) && recorded.insert(t) {- let premises: Vec<Fact> = match &f {+ // Computed ONCE, because two consumers need it and they need+ // the same value: the certificate records the first derivation+ // of a triple, and the DAG records every one. Deriving it twice+ // would let them disagree. Skipped entirely when neither asked,+ // so a run that wants no certificate and no DAG pays one branch.+ let premises: Vec<Fact> = if certify || cap_ref.is_some() {+ match &f {Fired::Bound(r, b) => BUILTIN_RULES[*r as usize].body.iter().map(|a| rv.fill(a, b)).collect(),Fired::Chained(_, _, ps) => ps.to_vec(),- };- derivations.push(Derivation { rule, conclusion: t, premises });+ }+ } else {+ Vec::new()+ };+ if certify && !triple_set.contains(&t) && recorded.insert(t) {+ derivations.push(Derivation { rule, conclusion: t, premises: premises.clone() });+ }+ // The DAG, when one was asked for. Recorded whether or not the+ // conclusion is new, because the SECOND way a triple can be+ // derived is the whole point: it is a second justification and+ // a second monomial, and a log that keeps only firsts cannot+ // see either.+ if let Some(cap) = cap_ref.as_mut() {+ let key = (rule, t, premises.clone());+ if cap.seen.insert(key.clone()) {+ cap.instances.push(key);+ }}new.push(t);};@@ -2320,6 +2496,45 @@ impl Reasoner {result["inconsistency"] = inconsistency;}+ // The DAG, spelled out, for a caller that has no interner. Built here+ // rather than in the loop so that `clashes` and the fixpoint flag are+ // the ones the run finished with.+ if let Some(cap) = capture.as_mut() {+ let spell = |f: &Fact| {+ (+ interner.resolve(f.0).to_string(),+ interner.resolve(f.1).to_string(),+ interner.resolve(f.2).to_string(),+ )+ };+ let instances: Vec<RuleInstance> = cap+ .instances+ .iter()+ .map(|(rule, c, ps)| RuleInstance {+ rule,+ conclusion: spell(c),+ premises: ps.iter().map(&spell).collect(),+ })+ .collect();+ cap.out = Some(DerivationGraph {+ profile_used: profile_used.to_string(),+ asserted: facts.iter().map(&spell).collect(),+ closure: triple_set.iter().map(&spell).collect(),+ instances,+ fixpoint_reached,+ iterations,+ clashes: clashes+ .iter()+ .map(|c| ClashInstance {+ rule: c.rule,+ premises: c.premises.iter().map(&spell).collect(),+ certifiable: clash_is_certifiable(c.rule),+ })+ .collect(),+ refused_unserialisable: refused.len(),+ });+ }+Ok(result.to_string())}}diff --git a/src/server.rs b/src/server.rsindex 7151ac65..885b8367 100644--- a/src/server.rs+++ b/src/server.rs@@ -2085,7 +2085,87 @@ impl OpenOntologiesServer {.unwrap_or_else(Self::err_json)}- #[tool(name = "onto_fol_export", description = "Export the loaded ontology as first-order logic, so it can be handed to the automated-theorem-proving ecosystem. FIVE syntaxes over ONE translation: `tptp` (FOF, what E, Vampire and every other first-order prover read), `clif` (ISO/IEC 24707 Common Logic Interchange Format, restricted to the first-order-equivalent fragment: no sequence markers, fixed arity, no quantification into a predicate position), `cgif` (ISO/IEC 24707 Conceptual Graph Interchange Format, the SECOND of Common Logic's three dialects, in CORE CGIF and in the compact sub-dialect clause 7.1.1 names: no sequence markers, which clause 6.5 says is what takes Common Logic past first order, plus no `#?` type label and no actor. It takes no dialect or comment flag, because CGIF has one spelling of its operators and a lexical comment syntax of its own. `[]` is truth, `~[]` is falsity, conjunction is juxtaposition with no operator and an equation is a coreference concept `[: ?X0 ?X1]`, because CGIF has no `=`. CGIF conformance is pinned by a lexer, parser and checker transcribed from Annex B's EBNF IN THE TEST and NOT by an independent parser, because no installable CGIF parser exists, which is a weaker footing than the CLIF side and is reported rather than blurred. XCL, the third dialect, is still not emitted and the report names it in `common_logic_dialects_not_emitted`), `smtlib` (SMT-LIB 2, what Z3 reads) and `ladr` (what Mace4 reads, with every symbol MANGLED and the table written beside it as symbols.tsv, because LADR reads a name beginning with u, v, w, x, y or z as a VARIABLE and has no quoting construct that survives an IRI). The last two are read by MODEL FINDERS, so they assert the NEGATED goal rather than declaring a conjecture: a countermodel to `G |= phi` is a model of `G + {not phi}`. With `smtlib`, omit `smt_domain` for the UNBOUNDED encoding, where `unsat` really is unsatisfiability, or set it to k for an enumeration carrier of exactly k elements, where a `sat` comes with a structure `oo-folmodel` can CHECK and an `unsat` establishes only that no model of size k exists. Every run also writes `problem.tsv`, the checker's own format, with its digest, so a solver result can be handed to `oo-folmodel` without going back through the engine; use onto_fol_model to do all of that in one call. The translation is the one a MACHINE-CHECKED ADEQUACY THEOREM is about: `OwlLean.adequacy` in the sibling owl-lean project, axioms propext + Classical.choice + Quot.sound, no sorry, no Mathlib. That theorem is why the emitted file means what it says. THE CORRESPONDENCE BETWEEN THIS EMITTER AND THAT LEAN IS PINNED BY TESTS AND IS NOT ITSELF PROVED. The output includes the background axioms (the two domains are disjoint, the object domain is non-empty) and the individual typing axioms `thing(a)`, whose ABSENCE REFUTES ADEQUACY OUTRIGHT (OwlLean.Refutations.adequacy_needs_ind_axioms). Constructs outside the fragment are NOT dropped silently: `exports_a_weaker_axiom_set` and `constructs_not_exported` name every one with its count and the reason, and `reduced_to_fragment` names every construct rewritten before translation. Pass `goals_file` (a TSV of triples, e.g. the `derivations.tsv` from onto_reason with certificate_dir, with goals_skip_columns=1) to also write one problem per conjecture. A PROVER'S VERDICT ON THESE FILES IS AN ORACLE OPINION AND NEVER A CERTIFICATE: checking a superposition refutation needs a verified first-order calculus with unification, which does not exist in core Lean. Use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it.")]+ #[tool(name = "onto_justify", description = "AXIOM PINPOINTING: which ASSERTED triples are responsible for a conclusion, or for a contradiction. Returns the MINIMAL sets (justifications, MinAs), not a support set: a set that is not minimal blames axioms that had nothing to do with the conclusion, and an engineer who deletes one and watches the conclusion survive learns to distrust the tool. Pass `triple` for a conclusion or `inconsistency: true` for the clash, never both. Pass `candidate` to CHECK a set someone else produced instead of searching: it comes back `minimal_justification`, `not_a_justification_not_minimal` with the removable triples named, or `not_a_justification_target_not_reached`. THREE DIFFERENT THINGS ARE CLAIMED HERE AND THEY CARRY THREE DIFFERENT WORDS. Sufficiency is re-run and CAN be machine-checked: every justification was produced by running the engine over exactly that subset, and with `certificate_dir` the run is repeated with a certificate so `lake exe oo-cert` verifies under OOCert.certificate_sound that the subset really does entail the conclusion. Minimality is re-run and is NOT machine-checked: for every element of every justification the engine is run again without it and the conclusion must be gone, which is a property of this engine verified by execution and no theorem. Completeness of the LIST is an algorithm's claim: all justifications are enumerated by Reiter's hitting-set tree over the same oracle, bounded by max_justifications (default 16) and max_oracle_calls (default 400), and `truncated` says when a bound fired and which one. Reiter's construction is complete for a MONOTONE oracle and this engine has one non-monotone corner: a restriction node or list node carrying two values for a functional position contributes one, chosen by hash order, so where that occurs a justification can be MISSED. No justification returned can be wrong, because each was re-run. The first justification costs no re-run at all, because the derivation DAG already carries it; everything after that is one full fixpoint per node, which is the entire cost of this tool on a large ontology. For `inconsistency` the verdict explained is `clash_found_by_this_engine` and NEVER the Lean checker's `unsatisfiable_under_disjointness`: ten of the seventeen OWL 2 RL rules that conclude false are looked for, so no clash found is not a consistency result. A justification is a statement about THIS engine's rule table, 29 of OWL 2 RL's 78 rules. `owl-dl` is refused rather than answered emptily.")]+ async fn onto_justify(&self, Parameters(input): Parameters<OntoJustifyInput>) -> String {+ let mut opts = crate::justify::JustifyOptions {+ profile: input.profile.unwrap_or_else(|| "owl-rl".to_string()),+ ..Default::default()+ };+ if let Some(n) = input.max_justifications {+ opts.max_justifications = n.max(1);+ }+ if let Some(n) = input.max_oracle_calls {+ opts.max_oracle_calls = n.max(1);+ }+ opts.certificate_dir = input+ .certificate_dir+ .as_deref()+ .map(|d| std::path::PathBuf::from(expand_tilde(d)));+ crate::justify::justify(+ &self.graph,+ input.triple.as_deref(),+ input.inconsistency.unwrap_or(false),+ input.candidate.as_deref(),+ &opts,+ )+ .map(|v| v.to_string())+ .unwrap_or_else(Self::err_json)+ }++ #[tool(name = "onto_provenance", description = "PROVENANCE SEMIRINGS: the algebraic expression over the ASSERTED triples that a derived triple carries. Green, Karvounarakis and Tannen's construction applied to this engine's rule table, evaluated over the full derivation DAG rather than over `derivations.tsv`, which records only the FIRST derivation of each triple and would give one monomial wherever the closure supports several. Six semirings: `boolean` (derivability), `why` (sets of sets of asserted triples, absorptive, whose minimal elements are the justifications), `lineage` (Which(X): the union of everything that contributes, which is NOT a justification and is usually far from minimal), `counting` (the number of proof trees), `tropical` (min-plus: the cheapest proof tree, summing leaf weights with multiplicity) and `trust` (max-min: the confidence of the best derivation, which is the confidence of its weakest premise). RECURSION IS WHERE PROVENANCE GOES WRONG QUIETLY AND THIS TOOL DOES NOT. Datalog is recursive, so a triple whose support contains a cycle has arbitrarily many proof trees and its counting annotation DIVERGES. `why`, `trust` and `tropical` are absorptive and converge; `boolean` and `lineage` are NOT absorptive and converge for a different reason, which is that their value lattices are finite, and the payload says which reason applies to which. `counting` does not converge, so round k of the iteration counts proof trees of HEIGHT AT MOST k, `depth_bound` (default 32) is reported beside the number, `value_is_exact` is false unless the iteration stabilised on its own, and `cycle_in_support` names a triple on the cycle when there is one. A saturated 128-bit counter is reported as saturated rather than as a count. `why` is worst-case exponential, so `max_monomials` (default 64) caps it; the monomials KEPT are the smallest, which is what keeps the survivors an antichain, and a truncated run WITHDRAWS the claim that its monomials are minimal supports rather than keeping it. min-plus refuses a negative weight because it is absorptive only for non-negative ones; max-min refuses a weight above 1.0 because its multiplicative identity is 1 and a larger weight would make a conjunction come out smaller than the algebra says. NOTHING HERE IS MACHINE-CHECKED. The Lean layer certifies that a derivation step is sound; no theorem says a monomial is minimal or that the list of them is complete. onto_justify verifies a support set by re-running the engine without each of its elements; this tool does algebra. `owl-dl` is refused.")]+ async fn onto_provenance(&self, Parameters(input): Parameters<OntoProvenanceInput>) -> String {+ let semirings = match input.semirings {+ None => crate::provenance::Semiring::all(),+ Some(names) => {+ let mut out = Vec::new();+ for n in &names {+ match crate::provenance::Semiring::parse(n) {+ Some(s) => out.push(s),+ None => {+ return serde_json::json!({+ "error": format!(+ "unknown semiring {n:?}. One of: boolean, why, lineage, \+ counting, tropical (min-plus), trust (max-min). Refusing \+ rather than silently computing the ones it recognised, \+ because a report missing the semiring the caller asked for \+ looks exactly like one where that semiring said nothing"+ )+ })+ .to_string();+ }+ }+ }+ out+ }+ };+ let mut weights = std::collections::BTreeMap::new();+ for w in input.weights.unwrap_or_default() {+ match crate::provenance::parse_triple(&w.triple) {+ Ok(t) => {+ weights.insert(t, w.weight);+ }+ Err(e) => return Self::err_json(e),+ }+ }+ let opts = crate::provenance::ProvenanceOptions {+ profile: input.profile.unwrap_or_else(|| "owl-rl".to_string()),+ semirings,+ depth_bound: input+ .depth_bound+ .unwrap_or(crate::provenance::DEFAULT_DEPTH_BOUND)+ .max(1),+ max_monomials: input+ .max_monomials+ .unwrap_or(crate::provenance::DEFAULT_MAX_MONOMIALS)+ .max(1),+ weights,+ };+ crate::provenance::annotate(&self.graph, input.triple.as_deref(), &opts)+ .map(|v| v.to_string())+ .unwrap_or_else(Self::err_json)+ }++ #[tool(name = "onto_fol_export", description = "Export the loaded ontology as first-order logic, so it can be handed to the automated-theorem-proving ecosystem. FOUR syntaxes over ONE translation: `tptp` (FOF, what E, Vampire and every other first-order prover read), `clif` (ISO/IEC 24707 Common Logic Interchange Format, restricted to the first-order-equivalent fragment: no sequence markers, fixed arity, no quantification into a predicate position), `smtlib` (SMT-LIB 2, what Z3 reads) and `ladr` (what Mace4 reads, with every symbol MANGLED and the table written beside it as symbols.tsv, because LADR reads a name beginning with u, v, w, x, y or z as a VARIABLE and has no quoting construct that survives an IRI). The last two are read by MODEL FINDERS, so they assert the NEGATED goal rather than declaring a conjecture: a countermodel to `G |= phi` is a model of `G + {not phi}`. With `smtlib`, omit `smt_domain` for the UNBOUNDED encoding, where `unsat` really is unsatisfiability, or set it to k for an enumeration carrier of exactly k elements, where a `sat` comes with a structure `oo-folmodel` can CHECK and an `unsat` establishes only that no model of size k exists. Every run also writes `problem.tsv`, the checker's own format, with its digest, so a solver result can be handed to `oo-folmodel` without going back through the engine; use onto_fol_model to do all of that in one call. The translation is the one a MACHINE-CHECKED ADEQUACY THEOREM is about: `OwlLean.adequacy` in the sibling owl-lean project, axioms propext + Classical.choice + Quot.sound, no sorry, no Mathlib. That theorem is why the emitted file means what it says. THE CORRESPONDENCE BETWEEN THIS EMITTER AND THAT LEAN IS PINNED BY TESTS AND IS NOT ITSELF PROVED. The output includes the background axioms (the two domains are disjoint, the object domain is non-empty) and the individual typing axioms `thing(a)`, whose ABSENCE REFUTES ADEQUACY OUTRIGHT (OwlLean.Refutations.adequacy_needs_ind_axioms). Constructs outside the fragment are NOT dropped silently: `exports_a_weaker_axiom_set` and `constructs_not_exported` name every one with its count and the reason, and `reduced_to_fragment` names every construct rewritten before translation. Pass `goals_file` (a TSV of triples, e.g. the `derivations.tsv` from onto_reason with certificate_dir, with goals_skip_columns=1) to also write one problem per conjecture. A PROVER'S VERDICT ON THESE FILES IS AN ORACLE OPINION AND NEVER A CERTIFICATE: checking a superposition refutation needs a verified first-order calculus with unification, which does not exist in core Lean. Use tools/fol_differential.py, which reports disagreement between this engine and an ATP and does not adjudicate it.")]async fn onto_fol_export(&self, Parameters(input): Parameters<OntoFolExportInput>) -> String {let syntax = match crate::tptp::Syntax::parse(input.format.as_deref().unwrap_or("tptp"),diff --git a/tests/justify_test.rs b/tests/justify_test.rsnew file mode 100644index 00000000..0b417b1c--- /dev/null+++ b/tests/justify_test.rs@@ -0,0 +1,625 @@+//! Axiom pinpointing, on graphs whose answer is known by hand.+//!+//! Every fixture here is small enough that the minimal set can be worked out on+//! paper, which is the only way to test a minimiser: a test that asserts+//! whatever the implementation returned tests nothing at all.+//!+//! The negative tests matter more than the positive ones. A pinpointer that+//! returns a superset is not a slightly worse pinpointer, it is a tool that+//! blames the wrong axiom, so there is a test that a non-minimal candidate is+//! REJECTED and a test that a set which does not reach the target is rejected+//! for a different reason and with a different word.++use open_ontologies::graph::GraphStore;+use open_ontologies::justify::{justify, JustifyOptions};+use open_ontologies::reason::Reasoner;+use std::collections::BTreeSet;+use std::sync::Arc;++const NS: &str = "https://example.org/";+const TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";+const SUBCLASS: &str = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";+const DISJOINT: &str = "<http://www.w3.org/2002/07/owl#disjointWith>";+const TRANSITIVE: &str = "<http://www.w3.org/2002/07/owl#TransitiveProperty>";++fn t(name: &str) -> String {+ format!("<{NS}{name}>")+}++fn store(nt: &str) -> Arc<GraphStore> {+ let g = GraphStore::new();+ g.load_ntriples(nt).expect("the fixture must parse");+ Arc::new(g)+}++fn opts(profile: &str) -> JustifyOptions {+ JustifyOptions {+ profile: profile.to_string(),+ ..Default::default()+ }+}++/// The justifications as sets of `"s p o"` strings, sorted, so an assertion can+/// name the expected set literally.+fn sets(v: &serde_json::Value) -> Vec<BTreeSet<String>> {+ v["justifications"]+ .as_array()+ .expect("justifications must be an array")+ .iter()+ .map(|j| {+ j["triples"]+ .as_array()+ .unwrap()+ .iter()+ .map(|t| {+ let a = t.as_array().unwrap();+ format!(+ "{} {} {}",+ a[0].as_str().unwrap(),+ a[1].as_str().unwrap(),+ a[2].as_str().unwrap()+ )+ })+ .collect()+ })+ .collect()+}++fn expect(items: &[String]) -> BTreeSet<String> {+ items.iter().cloned().collect()+}++// ───────────────────────────────────────────────────────────────────────────+// A chain, with noise beside it+// ───────────────────────────────────────────────────────────────────────────++/// Six asserted triples, three of which are responsible. A pinpointer that+/// returned all six would be correct about sufficiency and useless.+fn chain_fixture() -> Arc<GraphStore> {+ store(&format!(+ "{a} {TYPE} {c} .\n\+ {c} {SUBCLASS} {d} .\n\+ {d} {SUBCLASS} {e} .\n\+ {b} {TYPE} {f} .\n\+ {f} {SUBCLASS} {g} .\n\+ {g} {SUBCLASS} {h} .\n",+ a = t("a"),+ b = t("b"),+ c = t("C"),+ d = t("D"),+ e = t("E"),+ f = t("F"),+ g = t("G"),+ h = t("H"),+ ))+}++#[test]+fn the_justification_is_the_chain_and_not_the_graph() {+ let g = chain_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let out = justify(&g, Some(&target), false, None, &opts("rdfs")).unwrap();++ assert_eq!(out["reached"], true, "{out:#}");+ assert_eq!(out["asserted"], 6);+ let js = sets(&out);+ assert_eq!(js.len(), 1, "one derivation path, one justification: {out:#}");+ assert_eq!(+ js[0],+ expect(&[+ format!("{} {TYPE} {}", t("a"), t("C")),+ format!("{} {SUBCLASS} {}", t("C"), t("D")),+ format!("{} {SUBCLASS} {}", t("D"), t("E")),+ ]),+ "{out:#}"+ );+ // The point of the tool, stated as a number: strictly fewer than the+ // asserted graph.+ assert!(js[0].len() < 6);+ assert_eq!(out["minimality_verified"], true);+ assert_eq!(out["truncated"], false);+ assert_eq!(out["complete"], true);+ assert_eq!(out["justifications"][0]["removal_checks"], 3);+ assert_eq!(+ out["justifications"][0]["minimality"],+ "verified_by_re_running_the_fixpoint_without_each_element"+ );+}++/// The whole tool in one line of evidence: the FIRST justification costs no+/// re-run, because the derivation DAG already carries it.+#[test]+fn the_first_support_set_is_read_off_the_dag_before_any_re_run() {+ let g = chain_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let out = justify(&g, Some(&target), false, None, &opts("rdfs")).unwrap();+ assert_eq!(out["first_justification_from_the_dag"]["size"], 3, "{out:#}");+}++// ───────────────────────────────────────────────────────────────────────────+// The negative tests+// ───────────────────────────────────────────────────────────────────────────++#[test]+fn a_non_minimal_candidate_is_rejected_and_the_useless_triple_is_named() {+ let g = chain_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ // The real justification, plus one triple that has nothing to do with it.+ let candidate = vec![+ format!("{} {TYPE} {}", t("a"), t("C")),+ format!("{} {SUBCLASS} {}", t("C"), t("D")),+ format!("{} {SUBCLASS} {}", t("D"), t("E")),+ format!("{} {TYPE} {}", t("b"), t("F")),+ ];+ let out = justify(&g, Some(&target), false, Some(&candidate), &opts("rdfs")).unwrap();++ assert_eq!(+ out["candidate"]["verdict"], "not_a_justification_not_minimal",+ "a superset of a justification is NOT a justification: {out:#}"+ );+ let removable = out["candidate"]["removable"].as_array().unwrap();+ assert_eq!(removable.len(), 1, "{out:#}");+ assert_eq!(removable[0][0].as_str().unwrap(), t("b"));+ assert_eq!(out["searched"], false, "a candidate is checked, not searched");+}++#[test]+fn a_candidate_that_does_not_reach_the_target_is_rejected_under_a_different_word() {+ let g = chain_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ // The chain with its last link missing.+ let candidate = vec![+ format!("{} {TYPE} {}", t("a"), t("C")),+ format!("{} {SUBCLASS} {}", t("C"), t("D")),+ ];+ let out = justify(&g, Some(&target), false, Some(&candidate), &opts("rdfs")).unwrap();+ assert_eq!(+ out["candidate"]["verdict"], "not_a_justification_target_not_reached",+ "{out:#}"+ );+ assert!(+ out["candidate"]["removable"].as_array().unwrap().is_empty(),+ "nothing is removable from a set that is not a support"+ );+}++#[test]+fn the_real_justification_passes_the_same_check_that_rejects_the_others() {+ // A gate that only ever says no is not a gate. The same code path must+ // accept the set that IS minimal.+ let g = chain_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let candidate = vec![+ format!("{} {TYPE} {}", t("a"), t("C")),+ format!("{} {SUBCLASS} {}", t("C"), t("D")),+ format!("{} {SUBCLASS} {}", t("D"), t("E")),+ ];+ let out = justify(&g, Some(&target), false, Some(&candidate), &opts("rdfs")).unwrap();+ assert_eq!(out["candidate"]["verdict"], "minimal_justification", "{out:#}");+ assert_eq!(out["candidate"]["checks_run"], 4);+}++// ───────────────────────────────────────────────────────────────────────────+// Two independent derivations are two justifications+// ───────────────────────────────────────────────────────────────────────────++fn two_ways_fixture() -> Arc<GraphStore> {+ store(&format!(+ "{a} {TYPE} {c} .\n\+ {c} {SUBCLASS} {e} .\n\+ {a} {TYPE} {d} .\n\+ {d} {SUBCLASS} {e} .\n",+ a = t("a"),+ c = t("C"),+ d = t("D"),+ e = t("E"),+ ))+}++#[test]+fn a_triple_derived_two_ways_has_two_justifications() {+ let g = two_ways_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let out = justify(&g, Some(&target), false, None, &opts("rdfs")).unwrap();++ let js = sets(&out);+ assert_eq!(+ js.len(),+ 2,+ "the certificate records ONE derivation and there are two; this is the test that \+ reading the certificate back would fail: {out:#}"+ );+ assert!(js.contains(&expect(&[+ format!("{} {TYPE} {}", t("a"), t("C")),+ format!("{} {SUBCLASS} {}", t("C"), t("E")),+ ])));+ assert!(js.contains(&expect(&[+ format!("{} {TYPE} {}", t("a"), t("D")),+ format!("{} {SUBCLASS} {}", t("D"), t("E")),+ ])));+ assert_eq!(out["minimality_verified"], true);+ assert_eq!(out["complete"], true);+}++/// The substrate claim, tested where it lives: the DAG carries both rule+/// instances, and `derivations.tsv` would carry one.+#[test]+fn the_derivation_dag_carries_both_instances_where_a_certificate_carries_one() {+ let g = two_ways_fixture();+ let dg = Reasoner::derivation_graph(&g, "rdfs").unwrap();+ let target = (+ t("a"),+ TYPE.to_string(),+ t("E"),+ );+ let n = dg+ .instances+ .iter()+ .filter(|i| i.conclusion == target)+ .count();+ assert_eq!(n, 2, "two applicable rule instances conclude the same triple");++ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().to_path_buf();+ let json = Reasoner::run_full(+ &g,+ "rdfs",+ false,+ open_ontologies::reason::InferenceTarget::DefaultGraph,+ Some(&dir),+ )+ .unwrap();+ let v: serde_json::Value = serde_json::from_str(&json).unwrap();+ let lines = std::fs::read_to_string(dir.join("derivations.tsv")).unwrap();+ let recorded = lines+ .lines()+ .filter(|l| {+ let f: Vec<&str> = l.split('\t').collect();+ f.len() > 3 && f[1] == t("a") && f[3] == t("E")+ })+ .count();+ assert_eq!(+ recorded, 1,+ "the certificate records the first derivation only, which is why explanation does not \+ read it: {}",+ v["certificate"]+ );+}++// ───────────────────────────────────────────────────────────────────────────+// The bound, shown firing+// ───────────────────────────────────────────────────────────────────────────++fn six_ways_fixture() -> Arc<GraphStore> {+ let mut nt = String::new();+ for i in 1..=6 {+ nt.push_str(&format!(+ "{a} {TYPE} {c} .\n{c} {SUBCLASS} {e} .\n",+ a = t("a"),+ c = t(&format!("C{i}")),+ e = t("E"),+ ));+ }+ store(&nt)+}++#[test]+fn six_independent_derivations_give_six_justifications() {+ let g = six_ways_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let out = justify(&g, Some(&target), false, None, &opts("rdfs")).unwrap();+ assert_eq!(out["justification_count"], 6, "{out:#}");+ assert_eq!(out["truncated"], false, "{out:#}");+ assert_eq!(out["complete"], true);+ assert_eq!(out["minimality_verified"], true);+ for j in out["justifications"].as_array().unwrap() {+ assert_eq!(j["size"], 2);+ }+}++#[test]+fn the_truncation_flag_fires_when_the_bound_is_hit() {+ let g = six_ways_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let out = justify(+ &g,+ Some(&target),+ false,+ None,+ &JustifyOptions {+ max_justifications: 3,+ ..opts("rdfs")+ },+ )+ .unwrap();+ assert_eq!(out["truncated"], true, "{out:#}");+ assert_eq!(out["complete"], false);+ assert_eq!(out["truncation"]["bound"], "max_justifications");+ assert_eq!(out["truncation"]["value"], 3);+ assert_eq!(out["justification_count"], 3);+ // Truncated is not the same as wrong: every justification returned is+ // still sufficient and still minimal, and both were re-run.+ assert_eq!(out["minimality_verified"], true);+}++#[test]+fn the_other_bound_fires_under_its_own_name() {+ let g = six_ways_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let out = justify(+ &g,+ Some(&target),+ false,+ None,+ &JustifyOptions {+ max_oracle_calls: 6,+ ..opts("rdfs")+ },+ )+ .unwrap();+ assert_eq!(out["truncated"], true, "{out:#}");+ assert_eq!(out["truncation"]["bound"], "max_oracle_calls");+ assert_eq!(out["truncation"]["value"], 6);+}++// ───────────────────────────────────────────────────────────────────────────+// Inconsistency, the half that is worth more+// ───────────────────────────────────────────────────────────────────────────++fn clash_fixture() -> Arc<GraphStore> {+ store(&format!(+ "{c} {DISJOINT} {d} .\n\+ {a} {TYPE} {c0} .\n\+ {c0} {SUBCLASS} {c} .\n\+ {a} {TYPE} {d} .\n\+ {b} {TYPE} {c} .\n",+ a = t("a"),+ b = t("b"),+ c = t("C"),+ c0 = t("C0"),+ d = t("D"),+ ))+}++#[test]+fn the_axioms_responsible_for_a_clash_are_four_of_the_five() {+ let g = clash_fixture();+ let out = justify(&g, None, true, None, &opts("owl-rl")).unwrap();++ assert_eq!(out["reached"], true, "{out:#}");+ assert_eq!(+ out["verdict_explained"], "clash_found_by_this_engine",+ "never the checker's word"+ );+ let js = sets(&out);+ assert_eq!(js.len(), 1, "{out:#}");+ assert_eq!(+ js[0],+ expect(&[+ format!("{} {DISJOINT} {}", t("C"), t("D")),+ format!("{} {TYPE} {}", t("a"), t("C0")),+ format!("{} {SUBCLASS} {}", t("C0"), t("C")),+ format!("{} {TYPE} {}", t("a"), t("D")),+ ]),+ "{out:#}"+ );+ // The individual that is in one of the two classes and not the other is+ // not responsible for anything.+ assert!(!js[0].contains(&format!("{} {TYPE} {}", t("b"), t("C"))));+ assert_eq!(out["minimality_verified"], true);+}++#[test]+fn a_consistent_graph_gets_the_sentence_that_is_not_a_consistency_result() {+ let g = chain_fixture();+ let out = justify(&g, None, true, None, &opts("owl-rl")).unwrap();+ assert_eq!(out["reached"], false, "{out:#}");+ assert!(+ out["note"].as_str().unwrap().contains("NOT a consistency result"),+ "{out:#}"+ );+ assert!(out["justifications"].as_array().unwrap().is_empty());+}++// ───────────────────────────────────────────────────────────────────────────+// Recursion terminates+// ───────────────────────────────────────────────────────────────────────────++/// A transitive property round a three-cycle. Every derived edge's support+/// contains a cycle, which is the case a naive proof-tree walk does not come+/// back from.+pub fn cycle_fixture() -> Arc<GraphStore> {+ store(&format!(+ "{p} {TYPE} {TRANSITIVE} .\n\+ {x} {p} {y} .\n\+ {y} {p} {z} .\n\+ {z} {p} {x} .\n",+ p = t("p"),+ x = t("x"),+ y = t("y"),+ z = t("z"),+ ))+}++#[test]+fn pinpointing_terminates_on_a_cyclic_derivation() {+ let g = cycle_fixture();+ let target = format!("{} {} {}", t("x"), t("p"), t("z"));+ let out = justify(&g, Some(&target), false, None, &opts("owl-rl")).unwrap();++ assert_eq!(out["reached"], true, "{out:#}");+ let js = sets(&out);+ assert_eq!(js.len(), 1, "{out:#}");+ assert_eq!(+ js[0],+ expect(&[+ format!("{} {TYPE} {TRANSITIVE}", t("p")),+ format!("{} {} {}", t("x"), t("p"), t("y")),+ format!("{} {} {}", t("y"), t("p"), t("z")),+ ]),+ "the third edge closes the cycle and is not needed for this conclusion: {out:#}"+ );+ assert_eq!(out["minimality_verified"], true);+ assert_eq!(out["complete"], true);+}++// ───────────────────────────────────────────────────────────────────────────+// Refusals+// ───────────────────────────────────────────────────────────────────────────++#[test]+fn owl_dl_is_refused_rather_than_answered_emptily() {+ let g = chain_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let err = justify(&g, Some(&target), false, None, &opts("owl-dl")).unwrap_err();+ assert!(+ err.to_string().contains("no rule applications"),+ "got: {err}"+ );+}++#[test]+fn asking_for_both_targets_at_once_is_refused() {+ let g = chain_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let err = justify(&g, Some(&target), true, None, &opts("rdfs")).unwrap_err();+ assert!(err.to_string().contains("exactly one"), "got: {err}");+ let err = justify(&g, None, false, None, &opts("rdfs")).unwrap_err();+ assert!(err.to_string().contains("exactly one"), "got: {err}");+}++#[test]+fn a_triple_the_engine_does_not_derive_is_said_so_and_not_explained() {+ let g = chain_fixture();+ let target = format!("{} {TYPE} {}", t("b"), t("E"));+ let out = justify(&g, Some(&target), false, None, &opts("rdfs")).unwrap();+ assert_eq!(out["reached"], false, "{out:#}");+ assert!(+ out["note"]+ .as_str()+ .unwrap()+ .contains("not a non-entailment result"),+ "{out:#}"+ );+}++// ───────────────────────────────────────────────────────────────────────────+// Certificates: the one half a theorem covers+// ───────────────────────────────────────────────────────────────────────────++#[test]+fn a_certificate_is_written_per_justification_over_that_justification_alone() {+ let g = two_ways_fixture();+ let target = format!("{} {TYPE} {}", t("a"), t("E"));+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().to_path_buf();+ let out = justify(+ &g,+ Some(&target),+ false,+ None,+ &JustifyOptions {+ certificate_dir: Some(dir.clone()),+ ..opts("rdfs")+ },+ )+ .unwrap();++ let certs = out["certificates"].as_array().unwrap();+ assert_eq!(certs.len(), 2, "{out:#}");+ for (i, c) in certs.iter().enumerate() {+ let d = dir.join(format!("justification-{i}"));+ let asserted = std::fs::read_to_string(d.join("asserted.tsv")).unwrap();+ assert_eq!(+ asserted.lines().count(),+ 2,+ "the certificate is over the justification and nothing else"+ );+ let derivations = std::fs::read_to_string(d.join("derivations.tsv")).unwrap();+ assert!(+ derivations.lines().any(|l| {+ let f: Vec<&str> = l.split('\t').collect();+ f.len() > 3 && f[1] == t("a") && f[3] == t("E")+ }),+ "the target must appear as a CONCLUSION, or the certificate proves nothing about it"+ );+ assert!(c["check_with"].as_str().unwrap().contains("oo-cert"));+ }+}++// ───────────────────────────────────────────────────────────────────────────+// A real ontology+// ───────────────────────────────────────────────────────────────────────────++mod common;++fn repo() -> std::path::PathBuf {+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++/// Six-triple fixtures prove the answer is right. This one proves the thing+/// runs at all on an ontology somebody wrote, and it measures the claim the+/// whole design rests on: the DAG carries MORE hyperedges than a certificate+/// carries lines, because a certificate keeps one derivation per conclusion.+#[test]+fn on_a_real_ontology_the_dag_carries_more_than_the_certificate_would() {+ let path = repo().join("benchmark/reference/pizza-reference.owl");+ if common::skip_unless(+ path.is_file(),+ "benchmark/reference/pizza-reference.owl",+ "it ships with the repository; a sparse checkout may have skipped benchmark/",+ ) {+ return;+ }+ let g = Arc::new(GraphStore::new());+ g.load_file(&path.display().to_string()).unwrap();++ let dg = Reasoner::derivation_graph(&g, "rdfs").unwrap();+ assert!(dg.fixpoint_reached, "the fixture must reach a fixpoint");+ let conclusions: BTreeSet<_> = dg.instances.iter().map(|i| &i.conclusion).collect();+ assert!(+ dg.instances.len() > conclusions.len(),+ "a certificate would have {} lines and the DAG has {} hyperedges; if these were equal \+ there would be nothing here that reading derivations.tsv could not do",+ conclusions.len(),+ dg.instances.len()+ );++ // Explain one triple with more than one derivation, since that is the case+ // the certificate cannot represent. Deterministic: the sorted first one.+ let multi: BTreeSet<_> = dg+ .instances+ .iter()+ .map(|i| i.conclusion.clone())+ .filter(|c| dg.instances.iter().filter(|i| &i.conclusion == c).count() > 1)+ .collect();+ let target = multi.iter().next().expect("some triple is derived twice").clone();++ let out = justify(+ &g,+ Some(&format!("{} {} {}", target.0, target.1, target.2)),+ false,+ None,+ &JustifyOptions {+ profile: "rdfs".to_string(),+ max_justifications: 4,+ max_oracle_calls: 60,+ ..Default::default()+ },+ )+ .unwrap();++ assert_eq!(out["reached"], true, "{out:#}");+ assert_eq!(+ out["minimality_verified"], true,+ "every element of every justification was removed and re-run: {out:#}"+ );+ let js = sets(&out);+ assert!(!js.is_empty(), "{out:#}");+ for j in &js {+ assert!(+ j.len() < dg.asserted.len(),+ "a justification the size of the ontology explains nothing"+ );+ }+}diff --git a/tests/provenance_test.rs b/tests/provenance_test.rsnew file mode 100644index 00000000..09bb79ff--- /dev/null+++ b/tests/provenance_test.rs@@ -0,0 +1,492 @@+//! Provenance semirings, on graphs whose annotation is known by hand.+//!+//! The polynomials here are checked EXACTLY, string and all. A test that+//! asserts "two monomials" and not which two would pass on an implementation+//! that lost one derivation and invented another.+//!+//! The recursion test is the one that matters. Datalog is recursive, the+//! counting semiring diverges on a cycle, and the failure mode this whole file+//! exists to prevent is a finite number printed with no indication that the+//! true one is infinite.++use open_ontologies::graph::GraphStore;+use open_ontologies::justify::{justify, JustifyOptions};+use open_ontologies::provenance::{annotate, ProvenanceOptions, Semiring};+use open_ontologies::reason::Spelled;+use std::collections::{BTreeMap, BTreeSet};+use std::sync::Arc;++const NS: &str = "https://example.org/";+const TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";+const SUBCLASS: &str = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";+const TRANSITIVE: &str = "<http://www.w3.org/2002/07/owl#TransitiveProperty>";++fn t(name: &str) -> String {+ format!("<{NS}{name}>")+}++fn store(nt: &str) -> Arc<GraphStore> {+ let g = GraphStore::new();+ g.load_ntriples(nt).expect("the fixture must parse");+ Arc::new(g)+}++fn rdfs(semirings: Vec<Semiring>) -> ProvenanceOptions {+ ProvenanceOptions {+ profile: "rdfs".to_string(),+ semirings,+ ..Default::default()+ }+}++/// `a rdf:type E` derived two independent ways, and nothing else.+fn two_ways() -> Arc<GraphStore> {+ store(&format!(+ "{a} {TYPE} {c} .\n\+ {c} {SUBCLASS} {e} .\n\+ {a} {TYPE} {d} .\n\+ {d} {SUBCLASS} {e} .\n",+ a = t("a"),+ c = t("C"),+ d = t("D"),+ e = t("E"),+ ))+}++fn target_ae() -> String {+ format!("{} {TYPE} {}", t("a"), t("E"))+}++/// A monomial as a sorted set of `"s p o"` strings.+fn monomials(v: &serde_json::Value) -> Vec<BTreeSet<String>> {+ v["semirings"]["why"]["monomials"]+ .as_array()+ .expect("why must have monomials")+ .iter()+ .map(|m| {+ m["triples"]+ .as_array()+ .unwrap()+ .iter()+ .map(|tr| {+ let a = tr.as_array().unwrap();+ format!(+ "{} {} {}",+ a[0].as_str().unwrap(),+ a[1].as_str().unwrap(),+ a[2].as_str().unwrap()+ )+ })+ .collect()+ })+ .collect()+}++fn weight(map: &[(&str, &str, &str, f64)]) -> BTreeMap<Spelled, f64> {+ map.iter()+ .map(|(s, p, o, w)| ((s.to_string(), p.to_string(), o.to_string()), *w))+ .collect()+}++// ───────────────────────────────────────────────────────────────────────────+// Two derivations, two monomials, checked exactly+// ───────────────────────────────────────────────────────────────────────────++#[test]+fn a_triple_derived_two_ways_has_a_polynomial_with_exactly_two_monomials() {+ let out = annotate(&two_ways(), Some(&target_ae()), &rdfs(vec![Semiring::Why])).unwrap();+ let why = &out["semirings"]["why"];++ assert_eq!(why["monomial_count"], 2, "{out:#}");+ // Variables are numbered over the asserted triples in sorted order, so the+ // polynomial is canonical and can be pinned as a string.+ assert_eq!(why["polynomial"], "x1*x3 + x2*x4", "{out:#}");+ assert_eq!(out["variables"]["x1"][0], t("C"));+ assert_eq!(out["variables"]["x2"][0], t("D"));+ assert_eq!(out["variables"]["x3"][2], t("C"));+ assert_eq!(out["variables"]["x4"][2], t("D"));++ let ms = monomials(&out);+ assert!(ms.contains(&BTreeSet::from([+ format!("{} {TYPE} {}", t("a"), t("C")),+ format!("{} {SUBCLASS} {}", t("C"), t("E")),+ ])));+ assert!(ms.contains(&BTreeSet::from([+ format!("{} {TYPE} {}", t("a"), t("D")),+ format!("{} {SUBCLASS} {}", t("D"), t("E")),+ ])));+ assert_eq!(why["stabilised"], true);+ assert_eq!(why["truncated"], false);+ assert_eq!(why["monomials_are_minimal_supports"], true);+}++#[test]+fn the_counting_semiring_counts_both_proof_trees_and_says_the_number_is_exact() {+ let out = annotate(&two_ways(), Some(&target_ae()), &rdfs(vec![Semiring::Counting])).unwrap();+ let c = &out["semirings"]["counting"];+ assert_eq!(c["value"], "2", "{out:#}");+ assert_eq!(c["value_is_exact"], true);+ assert_eq!(c["saturated"], false);+ assert_eq!(out["cycle_in_support"], false);+}++#[test]+fn lineage_is_the_union_and_is_therefore_not_a_justification() {+ // The honest limit of the coarsest semiring, tested rather than only+ // documented: lineage says four triples are involved, and neither+ // justification has four triples in it.+ let out = annotate(&two_ways(), Some(&target_ae()), &rdfs(vec![Semiring::Lineage])).unwrap();+ assert_eq!(out["semirings"]["lineage"]["size"], 4, "{out:#}");++ let j = justify(+ &two_ways(),+ Some(&target_ae()),+ false,+ None,+ &JustifyOptions {+ profile: "rdfs".to_string(),+ ..Default::default()+ },+ )+ .unwrap();+ for jj in j["justifications"].as_array().unwrap() {+ assert_eq!(jj["size"], 2);+ }+}++#[test]+fn the_boolean_semiring_is_derivability_and_nothing_more() {+ let out = annotate(&two_ways(), Some(&target_ae()), &rdfs(vec![Semiring::Boolean])).unwrap();+ assert_eq!(out["semirings"]["boolean"]["value"], true, "{out:#}");+ assert_eq!(out["semirings"]["boolean"]["absorptive"], false);+}++/// Feature 1 and feature 2 must agree on the same graph, or one of them is+/// wrong. The why-semiring's monomials and the verified justifications are the+/// same sets.+#[test]+fn the_why_monomials_are_the_justifications_the_re_runs_verify() {+ let g = two_ways();+ let prov = annotate(&g, Some(&target_ae()), &rdfs(vec![Semiring::Why])).unwrap();+ let algebra: BTreeSet<BTreeSet<String>> = monomials(&prov).into_iter().collect();++ let j = justify(+ &g,+ Some(&target_ae()),+ false,+ None,+ &JustifyOptions {+ profile: "rdfs".to_string(),+ ..Default::default()+ },+ )+ .unwrap();+ let verified: BTreeSet<BTreeSet<String>> = j["justifications"]+ .as_array()+ .unwrap()+ .iter()+ .map(|x| {+ x["triples"]+ .as_array()+ .unwrap()+ .iter()+ .map(|tr| {+ let a = tr.as_array().unwrap();+ format!(+ "{} {} {}",+ a[0].as_str().unwrap(),+ a[1].as_str().unwrap(),+ a[2].as_str().unwrap()+ )+ })+ .collect()+ })+ .collect();++ assert_eq!(+ algebra, verified,+ "the algebra and the re-runs disagree about who is responsible"+ );+}++// ───────────────────────────────────────────────────────────────────────────+// The scalar semirings, with weights+// ───────────────────────────────────────────────────────────────────────────++#[test]+fn min_plus_takes_the_cheapest_proof_tree_and_max_min_its_weakest_link() {+ let weights = weight(&[+ (&t("a"), TYPE, &t("C"), 5.0),+ (&t("C"), SUBCLASS, &t("E"), 5.0),+ (&t("a"), TYPE, &t("D"), 1.0),+ (&t("D"), SUBCLASS, &t("E"), 1.5),+ ]);+ let out = annotate(+ &two_ways(),+ Some(&target_ae()),+ &ProvenanceOptions {+ weights: weights.clone(),+ ..rdfs(vec![Semiring::TropicalMinPlus])+ },+ )+ .unwrap();+ // min(5 + 5, 1 + 1.5) = 2.5+ assert_eq!(out["semirings"]["tropical"]["value"], 2.5, "{out:#}");++ // The same weights with `trust` asked for are refused, because max-min is+ // a semiring on [0, 1] and a weight above its multiplicative identity+ // would make a conjunction come out smaller than the algebra says.+ let err = annotate(+ &two_ways(),+ Some(&target_ae()),+ &ProvenanceOptions {+ weights,+ ..rdfs(vec![Semiring::TrustMaxMin])+ },+ )+ .unwrap_err();+ assert!(err.to_string().contains("above 1.0"), "got: {err}");++ // With confidences in [0,1] the max-min reading is the natural one.+ let conf = weight(&[+ (&t("a"), TYPE, &t("C"), 0.4),+ (&t("C"), SUBCLASS, &t("E"), 0.9),+ (&t("a"), TYPE, &t("D"), 0.7),+ (&t("D"), SUBCLASS, &t("E"), 0.6),+ ]);+ let out = annotate(+ &two_ways(),+ Some(&target_ae()),+ &ProvenanceOptions {+ weights: conf,+ ..rdfs(vec![Semiring::TrustMaxMin])+ },+ )+ .unwrap();+ // max(min(0.4, 0.9), min(0.7, 0.6)) = max(0.4, 0.6) = 0.6+ assert_eq!(out["semirings"]["trust"]["value"], 0.6, "{out:#}");+}++#[test]+fn the_default_weight_makes_min_plus_the_size_of_the_smallest_proof_tree() {+ let out = annotate(+ &two_ways(),+ Some(&target_ae()),+ &rdfs(vec![Semiring::TropicalMinPlus]),+ )+ .unwrap();+ assert_eq!(out["semirings"]["tropical"]["value"], 2.0, "{out:#}");+}++#[test]+fn a_negative_weight_is_refused_rather_than_allowed_to_diverge() {+ // min-plus is absorptive only for non-negative weights: with a negative+ // one, going round a cycle keeps lowering the cost and the fixpoint does+ // not converge. Refusing is the honest answer; looping is not.+ let bad = weight(&[(&t("a"), TYPE, &t("C"), -1.0)]);+ let err = annotate(+ &two_ways(),+ Some(&target_ae()),+ &ProvenanceOptions {+ weights: bad,+ ..rdfs(vec![Semiring::TropicalMinPlus])+ },+ )+ .unwrap_err();+ assert!(+ err.to_string().contains("non-negative"),+ "got: {err}"+ );+}++// ───────────────────────────────────────────────────────────────────────────+// Recursion: the honest half+// ───────────────────────────────────────────────────────────────────────────++/// A transitive property round a three-cycle, so every derived edge's support+/// contains a cycle.+fn cycle() -> Arc<GraphStore> {+ store(&format!(+ "{p} {TYPE} {TRANSITIVE} .\n\+ {x} {p} {y} .\n\+ {y} {p} {z} .\n\+ {z} {p} {x} .\n",+ p = t("p"),+ x = t("x"),+ y = t("y"),+ z = t("z"),+ ))+}++fn owl(semirings: Vec<Semiring>, depth: usize) -> ProvenanceOptions {+ ProvenanceOptions {+ profile: "owl-rl".to_string(),+ semirings,+ depth_bound: depth,+ ..Default::default()+ }+}++#[test]+fn a_cycle_is_named_as_a_cycle_before_any_number_is_read() {+ let target = format!("{} {} {}", t("x"), t("p"), t("z"));+ let out = annotate(&cycle(), Some(&target), &owl(vec![Semiring::Why], 8)).unwrap();+ assert_eq!(out["cycle_in_support"], true, "{out:#}");+ assert!(out["cycle_witness"].is_array(), "{out:#}");+ assert!(out["cycle_means"]+ .as_str()+ .unwrap()+ .contains("CANNOT be exact"));+}++#[test]+fn the_counting_semiring_reports_its_bound_instead_of_a_finite_lie() {+ let target = format!("{} {} {}", t("x"), t("p"), t("z"));++ let at3 = annotate(&cycle(), Some(&target), &owl(vec![Semiring::Counting], 3)).unwrap();+ let at5 = annotate(&cycle(), Some(&target), &owl(vec![Semiring::Counting], 5)).unwrap();++ // The numbers are the count of proof trees of height at most the bound,+ // which is why they are different. Pinned exactly: a run that returned the+ // same number for both bounds would not be bounding anything.+ assert_eq!(at3["semirings"]["counting"]["value"], "4", "{at3:#}");+ assert_eq!(at5["semirings"]["counting"]["value"], "289", "{at5:#}");++ for out in [&at3, &at5] {+ let c = &out["semirings"]["counting"];+ assert_eq!(c["stabilised"], false, "{out:#}");+ assert_eq!(c["value_is_exact"], false, "{out:#}");+ assert!(c["value_means"]+ .as_str()+ .unwrap()+ .contains("LOWER BOUND"));+ }+ assert_eq!(at3["semirings"]["counting"]["depth_bound"], 3);+ assert_eq!(at5["semirings"]["counting"]["depth_bound"], 5);+ assert_eq!(at3["semirings"]["counting"]["rounds_run"], 3);+}++#[test]+fn the_absorptive_semiring_converges_on_the_same_cycle() {+ let target = format!("{} {} {}", t("x"), t("p"), t("z"));+ let out = annotate(&cycle(), Some(&target), &owl(vec![Semiring::Why], 32)).unwrap();+ let why = &out["semirings"]["why"];+ assert_eq!(why["stabilised"], true, "{out:#}");+ assert_eq!(why["monomial_count"], 1, "{out:#}");+ assert_eq!(why["polynomial"], "x1*x2*x3");+ // It stopped long before the bound, which is what "converges" has to mean+ // if the word is to carry any weight.+ assert!(why["rounds_run"].as_u64().unwrap() < 32);+ assert_eq!(monomials(&out)[0].len(), 3);+}++#[test]+fn an_asserted_triple_absorbs_its_own_cyclic_derivation() {+ // `x p y` is asserted AND derivable, round the cycle, infinitely many+ // ways. Absorption is the reason the answer is one monomial of size one+ // rather than a series.+ let target = format!("{} {} {}", t("x"), t("p"), t("y"));+ let out = annotate(&cycle(), Some(&target), &owl(vec![Semiring::Why], 32)).unwrap();+ assert_eq!(out["target_is_asserted"], true, "{out:#}");+ assert_eq!(out["semirings"]["why"]["monomial_count"], 1, "{out:#}");+ assert_eq!(monomials(&out)[0].len(), 1);+ assert!(out["derivations_of_target"].as_u64().unwrap() >= 1);+}++// ───────────────────────────────────────────────────────────────────────────+// The monomial cap+// ───────────────────────────────────────────────────────────────────────────++fn six_ways() -> Arc<GraphStore> {+ let mut nt = String::new();+ for i in 1..=6 {+ nt.push_str(&format!(+ "{a} {TYPE} {c} .\n{c} {SUBCLASS} {e} .\n",+ a = t("a"),+ c = t(&format!("C{i}")),+ e = t("E"),+ ));+ }+ store(&nt)+}++#[test]+fn six_derivations_give_six_monomials_and_the_cap_says_when_it_bit() {+ let full = annotate(&six_ways(), Some(&target_ae()), &rdfs(vec![Semiring::Why])).unwrap();+ assert_eq!(full["semirings"]["why"]["monomial_count"], 6, "{full:#}");+ assert_eq!(full["semirings"]["why"]["truncated"], false);+ assert_eq!(full["semirings"]["why"]["monomials_are_minimal_supports"], true);++ let capped = annotate(+ &six_ways(),+ Some(&target_ae()),+ &ProvenanceOptions {+ max_monomials: 2,+ ..rdfs(vec![Semiring::Why])+ },+ )+ .unwrap();+ let why = &capped["semirings"]["why"];+ assert_eq!(why["monomial_count"], 2, "{capped:#}");+ assert_eq!(why["truncated"], true, "{capped:#}");+ assert_eq!(+ why["monomials_are_minimal_supports"], false,+ "a truncated run must withdraw the minimality claim, not keep it"+ );+ assert!(why["truncation_means"].as_str().unwrap().contains("INCOMPLETE"));+}++// ───────────────────────────────────────────────────────────────────────────+// Refusals and the empty cases+// ───────────────────────────────────────────────────────────────────────────++#[test]+fn a_triple_outside_the_closure_gets_a_sentence_and_no_expression() {+ let target = format!("{} {TYPE} {}", t("zzz"), t("E"));+ let out = annotate(&two_ways(), Some(&target), &rdfs(vec![Semiring::Why])).unwrap();+ assert_eq!(out["in_closure"], false, "{out:#}");+ assert!(out.get("semirings").is_none(), "{out:#}");+ assert!(out["note"]+ .as_str()+ .unwrap()+ .contains("NOT a non-entailment result"));+}++#[test]+fn no_target_reports_the_shape_of_the_dag_and_annotates_nothing() {+ let out = annotate(&two_ways(), None, &rdfs(vec![Semiring::Why])).unwrap();+ assert_eq!(out["asserted"], 4, "{out:#}");+ assert_eq!(out["derived"], 1);+ assert_eq!(out["rule_instances"], 2);+ assert!(out.get("semirings").is_none());+}++#[test]+fn asking_for_no_semiring_is_refused() {+ let err = annotate(&two_ways(), Some(&target_ae()), &rdfs(vec![])).unwrap_err();+ assert!(err.to_string().contains("nothing to compute"), "got: {err}");+}++#[test]+fn owl_dl_is_refused_here_too() {+ let err = annotate(+ &two_ways(),+ Some(&target_ae()),+ &ProvenanceOptions {+ profile: "owl-dl".to_string(),+ ..Default::default()+ },+ )+ .unwrap_err();+ assert!(err.to_string().contains("derivation DAG"), "got: {err}");+}++#[test]+fn every_semiring_name_round_trips() {+ for s in Semiring::all() {+ assert_eq!(Semiring::parse(s.name()), Some(s), "{}", s.name());+ assert!(!s.convergence().is_empty());+ assert!(!s.means().is_empty());+ }+ assert_eq!(Semiring::parse("not_a_semiring"), None);+}