Skip to content

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

modules: a subset that carries a theorem, and a change that carries a consequence

FABIOTESS08449c1d2b5f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a0e39c9..23be423d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,47 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
+### Added
+- **A module carries a theorem; a slice carries a measurement.** `onto_module_extract` computes a
+ syntactic locality module over a signature: `⊥`, `⊤` or the iterated `⊥⊤*`, the standard OWL API
+ algorithm. Unlike `onto_segment_retrieve`, whose loss then has to be measured by
+ `onto_closure_diff`, a locality module CANNOT lose an entailment over its signature, and the
+ difference is a theorem rather than a metric (Cuenca Grau, Horrocks, Kazakov and Sattler, JAIR 31,
+ 2008). That theorem is CITED and is not machine-checked, nothing under `lean/` being about
+ locality, so the report names a paper and never a Lean theorem, and
+ `the_module_report_never_names_a_lean_theorem` asserts that over the serialised report. What can
+ be checked is the consequence: `verify_out_dir` reasons the ontology and the module to a fixpoint
+ through the existing closure diff and reports every conclusion over the signature the module does
+ not reach, which must be none. Measured on `benchmark/reference/pizza-reference.owl`: 238 of 1,345
+ axioms and 510 of 2,332 triples, nothing unclassified, and zero of the 2,583 differences lost
+ over the signature. The locality test is written per
+ axiom type and an axiom that cannot be classified is INCLUDED rather than dropped, since any `M'`
+ with `M ⊆ M' ⊆ O` keeps the coverage property; the kinds and counts are in the payload so a small
+ module and an unreadable one cannot render the same. The negative test is the one that matters:
+ a naive slice keeping every triple that MENTIONS a signature term is five triples against the
+ module's four and has lost `Cat ⊑ LivingThing`, because the chain runs through an axiom that
+ mentions neither signature term. Running the verification found two places where the OWL 2 direct
+ semantics and this engine's rule table disagree, both now resolved towards the rule table, and one
+ of them (`X rdf:type owl:Thing`, a tautology the table does not regenerate) was not predicted.
+- **`onto_conservative_check`, and the same check inside `onto_plan`.** Does adding these axioms
+ change anything the ontology already said, over the names it already used? It is
+ `closure_diff` run in the extension direction: source `base ∪ extension`, projection `base`, and
+ the difference restricted to the old signature, with the rule and the premises the base lacked
+ already attached by the existing code. A non-conservative extension is a FINDING and never an
+ error, and every plan now carries a `conservativity` block that either has the answer or says it
+ did not look, because a missing block and a clean block read the same to a dashboard. This is the
+ only part of a plan that is about MEANING: one `rdfs:domain` triple retypes every existing
+ individual of that property while adding no class, removing nothing, and scoring `low` risk.
+ THE FRAGMENT IS NAMED IN THE PAYLOAD. What is computed is conservativity with respect to the Horn
+ rule table the engine evaluates. It is not deductive conservativity in a description logic
+ (ExpTime-complete for `EL`, 2ExpTime-complete for `ALC`, undecidable for `ALCQIO`) and not model
+ conservativity (undecidable already for `EL`), so the verdict field is `conservativity_verdict`
+ with four words, the boolean beside it is `conservative_under_rule_table` and is null when
+ undecided, and there is deliberately no field called `conservative`. See decision 0011.
+- `projection_entailment::skolemise_with_prefix`, so two graphs that are about to be merged can be
+ skolemised without `_:b0` on both sides becoming one IRI naming two different existentials.
+ `skolemise` is unchanged for every existing caller.
+
### Changed
- **A binding is data, and a certificate that admits two readings is refused.** Running the
Lean checker in `lean/OOCert/Horn.lean` and the independent Isabelle/HOL one in `isabelle/`
diff --git a/CLAUDE.md b/CLAUDE.md
index ba7953a9..a68b008f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -80,8 +80,10 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `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_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 |
+| `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 |
| `onto_apply` | After plan + enforce — applies changes in `safe` or `migrate` mode |
+| `onto_module_extract` | To take a subset of an ontology that CANNOT lose an entailment over a signature, as opposed to a slice whose loss then has to be measured. Syntactic locality: `bottom` (⊥), `top` (⊤) or `star` (the iterated ⊥⊤*, default and smallest). The coverage theorem is Cuenca Grau, Horrocks, Kazakov and Sattler (JAIR 31, 2008) and is CITED, NOT machine-checked (nothing under `lean/` is about locality), so pass `verify_out_dir` to have the consequence measured instead: it reasons the ontology and the module to a fixpoint and reports every conclusion over the signature the module does not reach, which must be none. The guarantee covers subclass, equivalence, disjointness, disjoint union, subproperty, property chains, domain, range, inverses, the seven property characteristics, `owl:hasKey`, class/property/negative-property assertions, declarations and annotations, over the full OWL 2 class-expression grammar. `owl:sameAs`, `owl:differentFrom`, `owl:AllDifferent`, any unrecognised RDF/RDFS/OWL predicate, any unrecognised blank-node structure and any malformed `rdf:List` are included CONSERVATIVELY with no locality test, and are counted and named in the report so a small module and an unreadable one cannot look the same |
+| `onto_conservative_check` | To ask whether adding axioms changes what the ontology ALREADY said, over the names it already used. This is the semantic safety net for the plan/apply lifecycle. Reports every new consequence over the old signature with the rule and the premises the base lacked; a non-conservative extension is a FINDING, not an error. Read the verdict from `conservativity_verdict` (`conservative_under_rule_table`, `not_conservative_under_rule_table`, `undecided_scan_truncated`, `undecided_not_an_extension`) and note there is deliberately no field called `conservative`: what is computed is conservativity with respect to the Horn rule table the engine evaluates, which is NOT deductive conservativity in a description logic (ExpTime-complete for EL, 2ExpTime-complete for ALC, undecidable for ALCQIO) and NOT model conservativity (undecidable already for EL). A finding is real; finding nothing proves only that this rule table derives nothing new. `mode` is `delta` or `replacement` and is never guessed |
| `onto_lock` | To protect production IRIs from removal |
| `onto_drift` | To compare two versions — rename detection, drift velocity, self-calibrating confidence |
| `onto_enforce` | After loading — design pattern checks: `generic`, `boro`, `value_partition`, `hierarchy`, or custom rules |
diff --git a/README.md b/README.md
index 1c27972d..fb5b7e80 100644
--- a/README.md
+++ b/README.md
@@ -95,6 +95,19 @@ is a proxy that rises as the slice grows, so a retriever tuned on it learns to f
than the right thing. Entailment preservation is the property, it is decidable here, and it
carries a certificate per claim. See [decision 0007](docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md).
+Measuring the loss is the second-best answer. The best one is a subset that cannot lose anything,
+and `onto_module_extract` computes one: a syntactic locality module over a signature, where every
+entailment of the whole ontology over those terms is still an entailment of the subset. That
+guarantee is a theorem of Cuenca Grau, Horrocks, Kazakov and Sattler, JAIR 31 (2008), and it is
+CITED rather than machine-checked, because nothing under [lean/](lean/) is about locality. The
+report says exactly that, names no theorem of this project, and offers to measure the consequence
+instead: reason the ontology and the module to a fixpoint and report every conclusion over the
+signature the module does not reach. On this repository's own pizza ontology that is 238 of 1,345
+axioms, and zero lost out of 2,583 differences examined. `onto_conservative_check` is the same
+machinery pointed at the lifecycle: does adding these axioms change any consequence over the names
+the ontology already used? See
+[decision 0011](docs/decisions/0011-a-module-carries-a-theorem-and-a-slice-carries-a-measurement.md).
+
## What is NOT proved
Every line above is worth less if this section is missing, so it is here rather than in a file
@@ -239,8 +252,8 @@ Restart, and the `onto_*` tools are available. Cursor, Windsurf, Zed and VS Code
## What is in the box
-**114 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 all 114 tools.
+**116 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 all 116 tools.
Eight need an optional Cargo feature and return an error without it: four need `embeddings`, two
need `plugins`, two need `postgres` or `duckdb`. The published binaries and the GHCR image are
built with the default feature set, so they do not carry those eight.
@@ -277,6 +290,7 @@ a Protégé-style inspector. No JVM. No Protégé.
| Schema alignment | [docs/alignment.md](docs/alignment.md) |
| Data pipeline | [docs/data-pipeline.md](docs/data-pipeline.md) |
| Ontology lifecycle | [docs/lifecycle.md](docs/lifecycle.md) |
+| Locality modules and conservative extensions | [docs/modules-and-conservativity.md](docs/modules-and-conservativity.md) |
| Semantic embeddings | [docs/embeddings.md](docs/embeddings.md) |
| Clinical crosswalks | [docs/clinical.md](docs/clinical.md) |
| IES support | [ecosystem](docs/ies-ecosystem.md) · [alignment](docs/ies-alignment.md) · [SPARQL examples](docs/ies-examples.md) |
diff --git a/docs/architecture.md b/docs/architecture.md
index 04e5e140..7911fc2a 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -24,7 +24,7 @@ flowchart TD
REST["REST API\n/api/query · /api/update\n/api/save · /api/load · /api/lineage"]
end
- subgraph ToolGroups["114 Tools"]
+ subgraph ToolGroups["116 Tools"]
direction LR
Core["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.md
index 6fecc873..352309f1 100644
--- a/docs/ci-gates.md
+++ b/docs/ci-gates.md
@@ -75,6 +75,13 @@ job invokes the file at all.
`fol_model_ingest_test.rs` runs in the `lean` job under the same variable and has
no skip path at all, which is why it is not in the table.
+`module_extract_test.rs` and `conservativity_test.rs` are absent for a different
+reason: they need nothing the tree does not already carry. Both run the reasoner
+and the closure diff with no checker on the path, take `engine_opinion` for the
+certificate verdict, and assert nothing that depends on Lean, so there is no skip
+path to make strict. `module_extract_test.rs` reads
+`benchmark/reference/pizza-reference.owl`, which is tracked.
+
### Python — `python/tests/*.py`
| test file | needs | provided by | in CI |
diff --git a/docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md b/docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md
index 7275db72..b6d02423 100644
--- a/docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md
+++ b/docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md
@@ -251,3 +251,35 @@ test fails if the gate is disarmed on more than half the corpus.
- **`closure_diff` has no Horn arm.** A supplied rule table is supported in the goal-directed form
only. The closure-diff form would need to read `horn.tsv` on both sides and run `oo-horn check`,
which is the same shape and is simply not written.
+
+## What happened next: decision 0011
+
+This record measures loss. It does not offer a way to AVOID loss, because
+`onto_segment_retrieve` is a hop-bounded neighbourhood walk and a neighbourhood has no theorem
+behind it, so the honest summary of the state this record leaves behind is that the damage is
+measured well and cannot be avoided. Decision 0011 adds the other half:
+`onto_module_extract` computes a syntactic locality module, which is a subset with a coverage
+theorem rather than a slice with a measurement, and there is nothing left to measure once you have
+one.
+
+Three things in this record change status as a result.
+
+1. **`lost_in_projection_vocabulary` is still the right headline FOR A SLICE**, and item 13's
+ gaming direction still stands. For a module the number is zero by construction, so it is not a
+ headline at all: `onto_module_extract` reports module size against ontology size and the
+ signature closure, and `module_fraction` is documented as a reading aid with no gaming direction
+ because nothing is tuned on it.
+
+2. **The machinery here is reused literally, twice.** `closure_diff` is called with the module as
+ the projection to VERIFY a module's coverage empirically, and it is called with the extension as
+ the source and the base as the projection to compute deductive conservativity. Neither reimplements
+ a closure, a certificate or a verdict word, so item 12's "exactly one place in the crate where
+ each verdict word is produced" survives both features.
+
+3. **`skolemise` gained a prefix parameter**, because the conservativity direction merges two graphs
+ and two graphs skolemised separately under the same prefix collide on `_:b0`. `skolemise` itself
+ is unchanged for every existing caller.
+
+The `not_compared` bucket, the disarming conditions, the datatype caveat and the "nothing about the
+negative side" limit all carry over unchanged, because both new features are built on exactly this
+code.
diff --git a/docs/decisions/0011-a-module-carries-a-theorem-and-a-slice-carries-a-measurement.md b/docs/decisions/0011-a-module-carries-a-theorem-and-a-slice-carries-a-measurement.md
new file mode 100644
index 00000000..d18d40db
--- /dev/null
+++ b/docs/decisions/0011-a-module-carries-a-theorem-and-a-slice-carries-a-measurement.md
@@ -0,0 +1,241 @@
+# 0011 · A module carries a theorem, a slice carries a measurement
+
+- **Status**: implemented, both features · `src/module_extract.rs`
+ (`onto_module_extract`) and `src/conservativity.rs` (`onto_conservative_check`, and the
+ `conservativity` block of `onto_plan`) · both reuse `src/closure_diff.rs` rather than
+ recomputing a closure, a certificate or a verdict word, so there is still exactly ONE place in
+ the crate where `checked` is produced · gated by `tests/module_extract_test.rs` (9) and
+ `tests/conservativity_test.rs` (10), plus 11 unit tests in `src/module_extract.rs` and 3 in
+ `src/conservativity.rs`
+- **Written**: 2026-09-15
+- **Related**: decision 0007 (a slice preserves a conclusion, or it does not), whose machinery this
+ reuses unchanged and whose story it completes; decision 0002 (an inference carries a
+ certificate), whose verdict discipline the conservativity report follows; decision 0003 (a rule
+ is data), whose `entailed_under_supplied_rules` habit is why the conservativity verdict is
+ `conservative_under_rule_table` and never `conservative`
+
+## On the number
+
+0011, not 0009 and not 0010. Both are taken in working trees on other branches, and 0009 is taken
+TWICE (`a-clash-is-a-condition-and-twelve-of-seventeen-have-one` and
+`a-translation-between-logics-carries-its-satisfaction-condition`), so the collision this repository
+already has is not one to join. 0004 is the known gap decision 0007 records and is left alone.
+
+## The problem
+
+Decision 0007 built the right instrument for the wrong half of the question. It can tell you, for
+any slice, exactly which conclusions it lost, with the rule and the blocking premises, and it can
+do it with a Lean-checked certificate behind the source closure. What it cannot do is produce a
+slice that loses nothing, because `onto_segment_retrieve` is a hop-bounded neighbourhood walk and a
+neighbourhood has no theorem behind it. The honest summary of the state before this change was: we
+measure the damage well and we have no way to avoid it.
+
+Worse, the measurement has a failure mode the decision record itself names. `closure(G) \ closure(P)`
+grows with `|G|`, so minimising it means retrieving more. A user who wants "the part of the ontology
+that matters for these terms" and is handed a loss report is being asked to tune a number whose
+gradient points at retrieving the whole file.
+
+The second gap was in the lifecycle. `onto_plan` reports added classes, removed classes, blast
+radius and a risk score, and every one of those is about SHAPE. A change that adds one
+`rdfs:domain` triple adds no class, removes nothing, has a blast radius of zero and scores `low`,
+while retyping every existing individual of that property. There was no tool in the repository that
+could see it, and the engine that computes exactly this difference was already sitting in
+`closure_diff` pointed the other way round.
+
+## Decisions
+
+1. **A module is a different object from a slice, and the tool names say so.** `onto_module_extract`
+ computes a syntactic locality module: the smallest subset of the axioms the locality test can
+ justify, such that `M ⊨ α iff O ⊨ α` for every axiom `α` over the signature. That is a coverage
+ theorem, so there is nothing to measure afterwards; `onto_closure_diff` stays for slices, which
+ have no theorem and therefore still need the measurement. The two are not competitors and the
+ descriptions cross-reference each other.
+
+2. **The theorem is CITED and is not machine-checked, and the report says so in a field.** Syntactic
+ locality is Cuenca Grau, Horrocks, Kazakov and Sattler, JAIR 31 (2008). Nothing under `lean/` is
+ about locality, so `ModuleReport` names the paper, carries
+ `guarantee_is_not_machine_checked`, and `the_module_report_never_names_a_lean_theorem` asserts
+ over the SERIALISED report that the strings `OOCert.`, `OwlLean.` and `Fol.` do not appear in it.
+ That test is the one that stops a future edit from borrowing a word the work has not earned,
+ which is decision 0002's rule applied to somebody else's theorem.
+
+3. **What CAN be checked is the consequence, and it is, on a file this repository ships.**
+ `verify_module` reasons the whole ontology and the module to a fixpoint under one rule table and
+ reports every conclusion over the signature closure the module does not reach, which must be
+ zero. It is `closure_diff` unchanged, called with the module as the projection, because a second
+ implementation of "what did this subset lose" would be a second place for the answer to be
+ wrong. `the_guarantee_holds_on_the_pizza_ontology` runs it over
+ `benchmark/reference/pizza-reference.owl`: a 238-axiom, 510-triple module of a 1,345-axiom,
+ 2,332-triple ontology, zero conclusions lost over the signature out of 2,583 examined, nothing
+ unclassified, and 60 annotation triples dropped by design and counted separately.
+
+4. **An axiom that cannot be classified is INCLUDED, and the count is in the payload.** Any `M'` with
+ `M ⊆ M' ⊆ O` still has the coverage property, so over-including costs size and under-including
+ costs the theorem. Every recovery failure resolves the same way: an unrecognised predicate in the
+ RDF, RDFS, OWL or XSD namespaces, an unrecognised blank-node structure, a malformed `rdf:List`, a
+ class expression nested past the depth bound. `owl:sameAs`, `owl:differentFrom` and
+ `owl:AllDifferent` join them for a different reason: they mention no class and no property name,
+ so no replacement can make them tautologies. All of it is counted under
+ `included_conservatively` and named under `unclassified_axioms`, because "the module is small"
+ and "the module is small because half the file was unreadable" must not render the same.
+
+5. **An unrecognised predicate in a USER namespace is a property assertion, and that is not the same
+ decision.** If every unknown predicate were kept, the module would be the ontology and the
+ guarantee would be free. `ex:a ex:p ex:b` is an `ObjectPropertyAssertion` under OWL 2 semantics
+ and replacing `ex:p` by the universal property makes it a tautology, so it is `⊤`-local and may
+ go. `an_unrecognised_user_predicate_is_a_property_assertion_and_can_be_dropped` pins the
+ distinction from the other side, so the conservative rule cannot quietly widen into "keep
+ everything".
+
+6. **A datatype is not an external class name.** Replacing `xsd:integer` by `⊥` makes
+ `∃hasAge.xsd:integer` look `⊥`-equivalent and drops the axiom, and the module still parses, so
+ nothing looks broken. Data ranges are neither `⊥`-equivalent nor `⊤`-equivalent under any
+ signature, detected by namespace, by `rdfs:Literal`, and by `owl:onDatatype` /
+ `owl:datatypeComplementOf` / `owl:withRestrictions` on a blank node.
+
+7. **The extraction pass iterates to a fixpoint, and that is the soundness condition rather than an
+ optimisation.** The working signature grows with every axiom taken, and an axiom that was local
+ against `Σ` stops being local once a name it mentions has been pulled in. A single sweep would
+ drop `a p₁ b` from a module that kept `p₁ ⊑ p₂`, losing `a p₂ b` over a signature containing
+ `p₂`, `a` and `b`. `the_top_pass_iterates_rather_than_sweeping_once` is the case, on the `⊤` pass
+ where the first sweep finds every axiom local.
+
+8. **Two places where the OWL 2 direct semantics and this engine's rule table disagree, both
+ resolved towards the rule table.** A declaration (`X rdf:type owl:Class`) is logically vacuous in
+ OWL 2 and is a PREMISE of OWL 2 RL's `scm-cls`, so it is kept whenever the declared term is in
+ the working signature. `X rdf:type owl:Thing` is a tautology in OWL 2 and the rule table does not
+ REGENERATE it, so dropping it removes a member of the closure; it is read as a declaration for
+ the same reason. The second one was not predicted: it was found by running the verification over
+ the pizza ontology, which reported five entailment losses over the signature that were
+ `Germany rdf:type owl:Thing` and four like it.
+
+9. **Annotation losses are COUNTED, never filtered.** The extractor treats `rdfs:label`,
+ `rdfs:comment` and the other OWL 2 annotation properties as vacuous, so the module drops them and
+ the verification sees them as differences over the signature. They are partitioned into
+ `lost_over_signature_annotation_only` rather than removed from the scan, and the pizza test
+ asserts that number is NON-ZERO, because a partition that silently swallowed everything would
+ make every module verify clean. The vacuity is checked rather than assumed: an annotation
+ predicate the ontology gives a domain, a range, a superproperty or an equivalent is read as a
+ property assertion instead, and `annotation_predicates_treated_as_vacuous` says in the payload
+ which ones were not.
+
+10. **The negative test is the whole point of shipping this.** A module and a neighbourhood look
+ identical from outside, so `a_naive_signature_slice_drops_an_entailment_the_module_keeps` builds
+ the slice a sensible retriever produces (every triple MENTIONING a signature term), shows it is
+ FIVE triples against the module's four, and shows it has lost `Cat ⊑ LivingThing` because
+ `Mammal ⊑ Animal` mentions neither signature term and the chain runs through it. Bigger and
+ wrong, against smaller and right. Without that test the feature is indistinguishable from a
+ rename.
+
+11. **Conservativity is `closure_diff` run in the extension direction, and it reuses it literally.**
+ Take `G` to be `base ∪ extension` and `P` to be the base, and `closure(G) \ closure(P)` is
+ exactly the set of consequences the extension introduced, with the rule and the blocking
+ premises already attached by the existing code. Restricting it to triples every name of which
+ the base already used gives the conservativity finding. No closure, certificate or verdict word
+ is recomputed.
+
+12. **The base is skolemised under its OWN prefix before the extension is merged in.** Two graphs
+ skolemised separately under the same prefix collide: the map is `_:label ↦ prefix + label`, so
+ `_:b0` in the base and `_:b0` in the extension would become one IRI naming two different
+ existentials. `skolemise_with_prefix` is the shared refactor that makes this expressible, and
+ the discriminator ends in `/`, which cannot occur in an N-Triples blank node label, so no
+ default-prefix skolem IRI can spell a base-prefix one. The payoff is measured rather than
+ claimed: `blank_nodes_in_the_base_do_not_disarm_the_gate` puts a restriction on both sides and
+ asserts the monotonicity gate still runs.
+
+13. **The verdict is a WORD, and the boolean beside it is null when undecided.** There is no field
+ called `conservative`. `conservativity_verdict` takes one of
+ `conservative_under_rule_table`, `not_conservative_under_rule_table`,
+ `undecided_scan_truncated`, `undecided_not_an_extension` and
+ `undecided_engine_soundness_violation`, and `conservative_under_rule_table` is `Option<bool>` so
+ "we could not tell" can never render as `false`, which a reader would take for a finding.
+ `the_payload_never_carries_a_bare_conservative_flag` asserts over the serialised report. The
+ last word exists because the monotonicity gate rides along for free: the base is a subset by
+ construction and the rule table is monotone, so a conclusion the base reaches and the extension
+ does not is an engine soundness bug, it is checked FIRST, and folding it into
+ `not_conservative` would send it to the ontology's author instead of the engine's.
+
+14. **The fragment travels in the payload, not only in the docs.** `what_this_is_not` states, as a
+ field, that this is conservativity with respect to the Horn rule table named in `rule_table`;
+ that deductive conservativity in a description logic is ExpTime-complete for `EL`,
+ 2ExpTime-complete for `ALC` (Ghilardi, Lutz and Wolter, KR 2006) and UNDECIDABLE for `ALCQIO`
+ (Lutz, Walther and Wolter, IJCAI 2007); and that model conservativity is undecidable already for
+ `EL` (Lutz and Wolter, JSC 2010). The asymmetry is stated in the same field: a new consequence
+ found IS a real change to what this engine derives over the old names, while finding none
+ establishes only that this rule table derives nothing new.
+
+15. **A non-conservative extension is a FINDING and never an error.** Changing what the ontology says
+ about existing terms is often the intended change. Exit 1 means "there is something to look at",
+ exit 2 means "the question could not be answered", and `finding_not_an_error` says so in the
+ payload. Every row names the rule and `premises_the_base_lacked`, so the decision is made on the
+ derivation rather than on the verdict word.
+
+16. **Delta or replacement is ASKED FOR, never guessed.** A delta that restates one triple of the
+ base and a replacement that dropped everything else are the same bytes, and the two answers are
+ opposite. `onto_plan` fixes the mode to `replacement` because that is what it receives;
+ `onto_conservative_check` defaults to `delta` and refuses an unknown word by name.
+
+17. **The plan is where the feature lives, and it is opt-in and says when it did not run.**
+ `check_conservativity: true` adds the block; without it the block is still present and reads
+ `ran: false` with the reason, because a missing block and a clean block look the same to a
+ dashboard. It is never fatal: a check that fails to run leaves `conservativity.skipped` set and
+ still returns the plan, since a diagnostic that can block a plan is a diagnostic people turn
+ off.
+
+## What was found on the way
+
+1. **The pizza ontology is not in the namespace it is cited by.**
+ `benchmark/reference/pizza-reference.owl` declares
+ `xml:base="https://raw.githubusercontent.com/owlcs/pizza-ontology/refs/heads/master/pizza.owl"`,
+ not the `co-ode.org` IRI everything in the literature uses. A signature spelled the usual way
+ selects nothing, the module comes back empty, and the empty module verifies perfectly clean. The
+ `signature_not_in_ontology` field exists because of this: a module over a misspelled IRI is
+ correct and useless, and that is the most expensive way to learn about a typo.
+
+2. **`X rdf:type owl:Thing` is a tautology the rule table does not regenerate.** Decision 8 above.
+ Found by running the verification rather than by reading the code.
+
+3. **A verification capped at `max_rows` is a SAMPLE.** The first version reported "0 lost over the
+ signature" on pizza while examining 200 of 2,588 differences. `not_examined` now rides in the
+ verification report and `scan_rows` bounds the scan separately from the rendering, so a clean
+ result over a truncated scan cannot read as a clean result.
+
+4. **The MCP server's own instructions string claimed 114 tools in one sentence and 112 in the
+ next.** `tests/readme_claims_test.rs` checks four phrasings and neither of those two matched the
+ second shape, so a stale number had been sitting inside the string the server tells every client
+ about itself. Corrected to 116 with the rest.
+
+## What this does not claim
+
+- **The locality theorem is not proved here.** It is a citation. The measured verification is a
+ consequence of it under ONE rule table and is not a substitute for it.
+- **The module is not minimal.** Syntactic locality gives the smallest set the syntactic test can
+ justify. A minimal module is a different and harder problem, and `guarantee` says so in the
+ payload rather than leaving "smallest" to be read as minimality.
+- **Conservativity here is not conservativity in a description logic**, and decision 14 is the long
+ form of that sentence.
+- **`module_fraction` is not a score.** A module is not better for being smaller; it is correct or
+ it is not, and its size is what the signature costs. The field is documented as a reading aid,
+ and unlike `coverage_ratio` it has no gaming direction because nothing is tuned on it.
+
+## Still not done
+
+- **No Horn arm.** Like `closure_diff` (decision 0007's own "still not done"), neither feature reads
+ a supplied rule table. The conservativity verdict would then have to be
+ `conservative_under_supplied_rules`, which is decision 0003's word and is simply not written.
+- **`owl:hasKey` is decided on the class only.** `HasKey(C, (p))` with an empty `p` is vacuously
+ true and could be local, which is what the OWL API does. The more conservative test is used
+ instead, so some `hasKey` axioms are in modules that need not be.
+- **`≥n R.C` for `n ≥ 2` is never `⊤`-equivalent here.** `≥2 ⊤.⊤` fails in a one-element domain, so
+ the bound is left alone rather than reasoned about. Conservative, and it costs a handful of
+ axioms on ontologies that use qualified cardinalities heavily.
+- **The module verification has a blank-node blind spot.** The module is serialised with the store's
+ own blank node labels and the closure diff skolemises the source, so a conclusion carrying a blank
+ node or a Skolem IRI has no term whose name means the same thing on both sides and cannot be
+ decided against the signature. `not_decided_blank_node_bearing` counts it rather than hiding it,
+ the pizza test asserts it is non-zero so the coverage of the clean result can be read, and
+ extracting the module from a skolemised store would empty it. That is decision 0007's
+ `not_compared` bucket in a new place, and the same NP-complete reason not to close it by matching.
+- **No CI leg installs Lean for these tests either.** Both run without a checker and report
+ `engine_opinion` for the certificate; nothing skips, because neither feature's claim depends on
+ the checker.
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index ff417201..a55c2431 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -33,6 +33,24 @@ therefore survive the process that computed them: `plan` and `apply` are
separate CLI invocations and separate MCP calls, and neither shares memory with
the other. The 100 most recent plans are retained.
+### Conservativity: the one part of a plan that is about meaning
+
+Everything above is about SHAPE. A change that adds one `rdfs:domain` triple adds
+no class, removes nothing, has a blast radius of zero and scores `low`, while
+retyping every existing individual of that property. Pass
+`check_conservativity: true` and the plan also reports whether the change alters
+any consequence over the names the store already uses, with the rule and the
+premises the base lacked behind every row.
+
+It is opt-in because it reasons both graphs to a fixpoint, and when it is off the
+`conservativity` block is still there and reads `ran: false` with the reason: a
+missing block and a clean block look the same to a dashboard. It is never fatal;
+a check that cannot run leaves `conservativity.skipped` set and the plan is still
+returned. The verdict is a WORD rather than a boolean, and it is conservativity
+with respect to a Horn rule table rather than in a description logic, which
+[docs/modules-and-conservativity.md](modules-and-conservativity.md) states in
+full.
+
## Enforce
Design pattern checks. Built-in packs: `generic` (orphan classes, missing labels), `boro` (IES4/BORO compliance), `value_partition` (disjointness). Custom SPARQL rules supported.
diff --git a/docs/modules-and-conservativity.md b/docs/modules-and-conservativity.md
new file mode 100644
index 00000000..5b06dc3b
--- /dev/null
+++ b/docs/modules-and-conservativity.md
@@ -0,0 +1,268 @@
+# A subset with a theorem, and a change with a consequence
+
+Two questions the rest of this repository could measure but not answer.
+
+1. *Give me the part of this ontology that matters for these terms, and do not lose anything.*
+ `onto_segment_retrieve` gives a neighbourhood and `onto_closure_diff` tells you what the
+ neighbourhood dropped, which is the right pair when you are auditing a retriever and the wrong
+ pair when you want a subset you can rely on. `onto_module_extract` gives one.
+2. *I am about to add these axioms. Does anything I already said change?* `onto_plan` reports added
+ classes, removed classes, blast radius and a risk score, and every one of those is about SHAPE.
+ `onto_conservative_check`, and the `conservativity` block of `onto_plan`, answers the semantic
+ question.
+
+The design and its limits are in
+[decision 0011](decisions/0011-a-module-carries-a-theorem-and-a-slice-carries-a-measurement.md).
+
+## Modules
+
+### What the guarantee is
+
+For a signature `Σ`, an axiom is `⊥`-local when replacing every class and property name outside `Σ`
+by `⊥` turns it into a tautology, and `⊤`-local when the same replacement with `⊤` does. Take every
+axiom that is NOT local with respect to `Σ ∪ sig(M)`, repeat until the set stops growing, and the
+result `M` satisfies
+
+> `M ⊨ α` if and only if `O ⊨ α`, for every axiom `α` over `Σ`.
+
+That is the locality theorem of Cuenca Grau, Horrocks, Kazakov and Sattler, JAIR 31 (2008),
+*Modular Reuse of Ontologies: Theory and Practice*. It holds for OWL 2 DL and therefore for every
+profile inside it. It is a COVERAGE guarantee, not a MINIMALITY one: a locality module is the
+smallest set the syntactic test can justify, not the smallest set that would do.
+
+**The theorem is cited, not machine-checked.** Nothing under `lean/` is about syntactic locality, so
+the report names a paper and never names a Lean theorem, and
+`the_module_report_never_names_a_lean_theorem` asserts that over the serialised report rather than
+leaving it to good intentions.
+
+### Running it
+
+Both features are MCP tools over the loaded store; there is no CLI subcommand for either yet, so
+load the ontology with `onto_load` (or `onto_repo_load`) and then call the tool.
+
+```json
+{
+ "tool": "onto_module_extract",
+ "signature": [
+ "https://raw.githubusercontent.com/owlcs/pizza-ontology/refs/heads/master/pizza.owl#Veneziana",
+ "https://raw.githubusercontent.com/owlcs/pizza-ontology/refs/heads/master/pizza.owl#Food"
+ ],
+ "locality": "star",
+ "verify_out_dir": "/tmp/pizza-module"
+}
+```
+
+`locality` is `bottom` (`⊥`), `top` (`⊤`) or `star` (the iterated `⊥⊤*`, the default and never
+larger than either).
+
+### What it says, measured
+
+From `tests/module_extract_test.rs::the_guarantee_holds_on_the_pizza_ontology`, over the two-term
+signature above:
+
+| | |
+|---|---|
+| ontology | 1,345 axioms, 2,332 triples |
+| `⊥⊤*` module | **238 axioms, 510 triples** |
+| axioms this file could not classify | **0** |
+| conclusions over the signature the module does not reach | **0**, out of 2,583 examined |
+| annotation triples the module drops by design | 60, counted separately |
+
+The last two rows are the point. `verify_out_dir` runs `onto_closure_diff` with the module as the
+projection, so the guarantee is EXERCISED against the engine's own closure rather than asserted; a
+non-zero `lost_over_signature_total` would be a defect in the extractor, not a property of the file.
+Annotation triples are partitioned into `lost_over_signature_annotation_only` rather than filtered
+out, because a silent filter is how a real loss would eventually hide there.
+
+The verification has a blind spot and it is COUNTED. The module is serialised with the store's own
+blank node labels and the closure diff skolemises the source before comparing, so a conclusion
+carrying a blank node or a Skolem IRI has no term whose name means the same thing on both sides and
+the signature question cannot be asked of it. `not_decided_blank_node_bearing` is that number, and
+it is non-zero on pizza, which is full of blank-node restrictions. Skolemising the store before
+extracting the module empties the bucket; nothing does that yet. This is the same complexity
+[decision 0007](decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md) documents and
+declines to close.
+
+### Why not a neighbourhood
+
+A module and a neighbourhood look identical from outside, so here is the case that separates them.
+
+```turtle
+ex:Cat rdfs:subClassOf ex:Mammal .
+ex:Mammal rdfs:subClassOf ex:Animal .
+ex:Animal rdfs:subClassOf ex:LivingThing .
+ex:Plant rdfs:subClassOf ex:LivingThing .
+ex:Fungus rdfs:subClassOf ex:LivingThing .
+ex:tom a ex:Cat .
+ex:tom ex:eats ex:fish .
+```
+
+Signature `{Cat, LivingThing}`. The goal is `Cat ⊑ LivingThing`, which the whole ontology derives.
+
+| | triples | `Cat ⊑ LivingThing` |
+|---|---|---|
+| every triple MENTIONING a signature term | **5** | **lost** |
+| the `⊥⊤*` module | **4** | **preserved** |
+
+The naive slice is BIGGER and still wrong. It loses because `Mammal ⊑ Animal` mentions neither
+signature term while the chain runs through it; the module keeps that link because once
+`Cat ⊑ Mammal` has been taken, `Mammal` is in the working signature and the next link stops being
+local. Both rows are
+`tests/module_extract_test.rs::a_naive_signature_slice_drops_an_entailment_the_module_keeps`.
+
+### What is classified, and what is included without being classified
+
+An RDF graph is not a list of OWL axioms, so the axioms have to be recovered from triples. Every
+recovery failure resolves the same way: an axiom that cannot be classified is NEVER local, so it is
+INCLUDED. Any `M'` with `M ⊆ M' ⊆ O` still has the coverage property, so including too much costs
+size and excluding too much costs the theorem.
+
+**Classified**, each with a locality test written for that kind: `rdfs:subClassOf`,
+`owl:equivalentClass`, `owl:disjointWith`, `owl:AllDisjointClasses`, `owl:disjointUnionOf`,
+`rdfs:subPropertyOf`, `owl:propertyChainAxiom`, `owl:equivalentProperty`,
+`owl:propertyDisjointWith`, `owl:AllDisjointProperties`, `rdfs:domain`, `rdfs:range`,
+`owl:inverseOf`, the seven property characteristics, `owl:hasKey`, class assertions, property
+assertions, `owl:NegativePropertyAssertion`, declarations and annotations. Class expressions are
+read through `owl:intersectionOf`, `owl:unionOf`, `owl:complementOf`, `owl:oneOf`,
+`owl:someValuesFrom`, `owl:allValuesFrom`, `owl:hasValue`, `owl:hasSelf` and the six cardinality
+forms, with `owl:inverseOf` on property expressions.
+
+**Included conservatively**, with no locality test: `owl:sameAs`, `owl:differentFrom` and
+`owl:AllDifferent`, which mention no class and no property name, so no replacement can make them
+tautologies; every unrecognised predicate in the RDF, RDFS, OWL or XSD namespaces; every
+blank-node structure whose shape is not one of the above; every malformed `rdf:List`; every class
+expression nested past the depth bound. The counts are in `included_conservatively` and the rows in
+`unclassified_axioms`, so "the module is small" and "the module is small because half the file was
+unreadable" cannot render the same.
+
+An unrecognised predicate in a USER namespace is a different decision: `ex:a ex:p ex:b` is an
+`ObjectPropertyAssertion` under OWL 2 semantics, so it is `⊤`-local and may go. If every unknown
+predicate were kept, the module would be the ontology and the guarantee would be free.
+
+### Three places the direct semantics and this engine disagree
+
+Resolved towards the rule table in all three, because the module has to satisfy both readings.
+
+- **`X rdf:type owl:Class`** is logically vacuous in OWL 2 and is a PREMISE of OWL 2 RL's `scm-cls`.
+ Kept whenever the declared term is in the working signature.
+- **`X rdf:type owl:Thing`** is a tautology in OWL 2 and the rule table does not REGENERATE it, so
+ dropping it removes a member of the closure. Read as a declaration for the same reason. This one
+ was not predicted: the pizza verification reported five entailment losses over the signature and
+ they were `Germany rdf:type owl:Thing` and four like it.
+- **A datatype is not an external class name.** Replacing `xsd:integer` by `⊥` makes
+ `∃hasAge.xsd:integer` look `⊥`-equivalent and drops the axiom, and the module still parses, so
+ nothing looks broken. Data ranges are neither `⊥`- nor `⊤`-equivalent under any signature.
+
+## Conservativity
+
+### The question
+
+An ontology is EXTENDED. Does it now say anything different about the terms that were already
+there? This is `onto_closure_diff` pointed the other way: source `base ∪ extension`, projection
+`base`, and `closure(G) \ closure(P)` restricted to triples every name of which the base already
+used. Nothing is recomputed, so the rule, the blocking premises and the verdict discipline all come
+from the existing code.
+
+```json
+{
+ "tool": "onto_conservative_check",
+ "extension_ttl": "@prefix ex: <http://ex.org/> . ex:hasParent rdfs:domain ex:Person .",
+ "mode": "delta",
+ "out_dir": "/tmp/cx"
+}
+```
+
+Or, where it belongs, inside a plan:
+
+```json
+{"tool": "onto_plan", "new_turtle": "...", "check_conservativity": true}
+```
+
+### The one-triple change every other number misses
+
+Base: `ex:Person a owl:Class`, `ex:hasParent a owl:ObjectProperty`, `ex:Alice ex:hasParent ex:Bob`.
+Extension: one triple, `ex:hasParent rdfs:domain ex:Person`.
+
+| what `onto_plan` reports | |
+|---|---|
+| `added_classes` | 0 |
+| `removed_classes` | 0 |
+| `risk_score` | `low` |
+| `conservativity.conservativity_verdict` | **`not_conservative_under_rule_table`** |
+| the row | `ex:Alice rdf:type ex:Person`, rule `rdfs2`, premise the base lacked: the domain axiom |
+
+That is `tests/conservativity_test.rs::a_plan_reports_conservativity_or_reports_that_it_did_not_look`.
+Every shape number stays green while every existing subject of the property is retyped.
+
+A non-conservative extension is a **finding, not an error**. Changing what the ontology says about
+existing terms is often the intended change; the point is that it should be intended rather than
+discovered later. Exit 1 means there is something to look at, exit 2 means the question could not be
+answered.
+
+### The verdict words
+
+`conservativity_verdict` is one of:
+
+| word | meaning | `conservative_under_rule_table` | exit |
+|---|---|---|---|
+| `conservative_under_rule_table` | this rule table derives nothing new over the old names | `true` | 0 |
+| `not_conservative_under_rule_table` | it does, and the rows say what | `false` | 1 |
+| `undecided_scan_truncated` | the difference was larger than `scan_rows` | `null` | 2 |
+| `undecided_not_an_extension` | the proposal REMOVES asserted triples, so the question does not apply | `null` | 2 |
+| `undecided_engine_soundness_violation` | the base derived something the extended graph did not, which is impossible unless the engine is wrong | `null` | 2 |
+
+There is deliberately no field called `conservative`, and the boolean is null rather than false
+whenever the answer is "we could not tell", because a reader takes `false` for a finding.
+
+The last row gets its own word rather than being folded into `not_conservative_under_rule_table`.
+The base is a subset of the extended graph by construction and the rule table is monotone, so a
+conclusion the base reaches and the extension does not is a soundness bug in the engine. Reporting
+it as a non-conservative extension would send it to the ontology's author instead of the engine's,
+which is the same mistake decision 0007 refuses to make about a lossy retriever and a hallucinating
+generator.
+
+### What this is NOT
+
+Conservativity here is **with respect to the Horn rule table named in `rule_table`**, which derives
+only positive ground triples. It is not deductive conservativity in a description logic, which is
+ExpTime-complete for `EL`, 2ExpTime-complete for `ALC` (Ghilardi, Lutz and Wolter, KR 2006) and
+UNDECIDABLE for `ALCQIO` (Lutz, Walther and Wolter, IJCAI 2007); and it is not model conservativity,
+which is undecidable already for `EL` (Lutz and Wolter, JSC 2010).
+
+The asymmetry is the point, and it travels in the payload as `what_this_is_not` rather than only
+here:
+
+- a new consequence reported **is** a real change to what this engine derives over the old names;
+- finding none establishes only that this rule table derives nothing new, and never that the
+ extension is conservative in any logic.
+
+### Delta or replacement, asked for rather than guessed
+
+A delta that restates one triple of the base and a replacement that dropped everything else are the
+same bytes, and the two answers are opposite. `onto_plan` fixes the mode to `replacement`, because
+that is what it receives. `onto_conservative_check` defaults to `delta` and refuses an unknown word
+by name.
+
+### Blank nodes
+
+The base is skolemised under its OWN prefix before the extension is merged in. Two graphs
+skolemised separately under the same prefix collide: the map is `_:label ↦ prefix + label`, so
+`_:b0` on both sides would become one IRI naming two different existentials. The discriminator ends
+in `/`, which cannot occur in an N-Triples blank node label, so no default-prefix skolem IRI can
+spell a base-prefix one. The result is that the monotonicity gate stays ARMED on ontologies full of
+restrictions, which `blank_nodes_in_the_base_do_not_disarm_the_gate` pins.
+
+## Known limits
+
+- **Neither feature reads a supplied rule table.** The conservativity verdict would then have to be
+ `conservative_under_supplied_rules`, which is decision 0003's word, and it is not written.
+- **`owl:hasKey` is decided on the class only.** `HasKey(C, (p))` with an empty `p` is vacuously
+ true and could be local; the more conservative test is used, so some `hasKey` axioms sit in
+ modules that do not need them.
+- **`≥n R.C` for `n ≥ 2` is never treated as `⊤`-equivalent**, because `≥2 ⊤.⊤` fails in a
+ one-element domain. Conservative, and it costs a few axioms on ontologies that lean on qualified
+ cardinalities.
+- **The module is not minimal**, and `guarantee` says so in the payload rather than leaving
+ "smallest" to be read as minimality.
+- **`module_fraction` is not a score.** A module is not better for being smaller; it is correct or
+ it is not, and its size is what the signature costs.
diff --git a/docs/projection-entailment.md b/docs/projection-entailment.md
index 6b5c327d..72c56eee 100644
--- a/docs/projection-entailment.md
+++ b/docs/projection-entailment.md
@@ -13,6 +13,11 @@ Lean checker accepts.
This page is the how-to. The design and its limits are in
[decision 0007](decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md).
+Everything here MEASURES what a slice lost, which is the right thing to do to a retriever and the
+wrong thing to want from a subset. If what you need is a part of the ontology that cannot lose an
+entailment over a set of terms, extract a locality module instead:
+[docs/modules-and-conservativity.md](modules-and-conservativity.md).
+
## The number that cannot see the damage
Measured on `benchmark/reference/pizza-reference.owl`, which this repository ships. Seeds are the
diff --git a/src/conservativity.rs b/src/conservativity.rs
new file mode 100644
index 00000000..4daf72ec
--- /dev/null
+++ b/src/conservativity.rs
@@ -0,0 +1,497 @@
+//! Does adding these axioms change anything I could already say?
+//!
+//! [`crate::closure_diff`] already computes `closure(G) \ closure(P)` for a
+//! `P ⊆ G`, with the rule and the premises behind every row and the
+//! monotonicity gate running for free. Conservativity is that computation
+//! pointed the other way: take `G` to be the EXTENDED ontology and `P` to be
+//! the one that was there before, and the difference is exactly the set of
+//! consequences the extension introduced. Restrict it to the old signature and
+//! the finding is "this change alters what the ontology says about terms that
+//! already existed".
+//!
+//! Nothing here recomputes a closure, a certificate or a verdict word:
+//! [`crate::closure_diff::SourceClosure`] does all of it, so there is still
+//! exactly ONE place in this crate where `checked` is produced.
+//!
+//! # What this is NOT, said once here and again in the payload
+//!
+//! Deductive conservativity in a description logic is a different problem from
+//! the one this file solves, and it is a hard one: ExpTime-complete for `EL`,
+//! 2ExpTime-complete for `ALC` (Ghilardi, Lutz and Wolter, KR 2006, "Did I
+//! Damage My Ontology?"), and UNDECIDABLE for `ALCQIO` (Lutz, Walther and
+//! Wolter, IJCAI 2007). Model conservativity is stronger again and is
+//! undecidable already for `EL` (Lutz and Wolter, JSC 2010).
+//!
+//! What is computed here is conservativity WITH RESPECT TO THE RULE TABLE the
+//! engine evaluates, which is a Horn approximation of OWL and derives only
+//! positive ground triples. It is sound in one direction only and the report
+//! says so in a field, not a doc comment: a new consequence found IS a real
+//! change to what the ontology derives, while finding none does NOT establish
+//! that the extension is conservative in any description logic. The field is
+//! called `conservative_under_rule_table` and there is deliberately no
+//! `conservative` anywhere in the payload.
+
+use crate::closure_diff::{CertificateVerdict, DiffOptions, NtTriple, SourceClosure, Warrant};
+use crate::graph::GraphStore;
+use crate::projection_entailment as pe;
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeSet;
+use std::sync::Arc;
+
+/// Skolem prefix for the BASE graph.
+///
+/// The base is skolemised before the extension is merged in, so that the merged
+/// store has blank nodes from the extension only and the base is a literal
+/// subset of it. A distinct prefix is what stops `_:b0` in the base and `_:b0`
+/// in the extension mapping onto the same IRI, which would silently identify
+/// two different existentials. `/` cannot occur in an N-Triples blank node
+/// label, so no default-prefix skolem IRI can collide with one of these.
+const BASE_SKOLEM_PREFIX: &str = "https://open-ontologies.org/.well-known/genid/base/";
+
+/// Namespaces whose IRIs are logical vocabulary rather than names of the
+/// ontology's own things. A conclusion is "over the old signature" when every
+/// IRI in it is either one of these or a name the base already used: otherwise
+/// `ex:Old rdfs:subClassOf ex:Older` would count as outside the signature
+/// because `rdfs:subClassOf` is not a class the base declared.
+const LOGICAL_NAMESPACES: &[&str] = &[
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+ "http://www.w3.org/2000/01/rdf-schema#",
+ "http://www.w3.org/2002/07/owl#",
+ "http://www.w3.org/2001/XMLSchema#",
+];
+
+pub const WHAT_THIS_IS_NOT: &str =
+ "this is conservativity WITH RESPECT TO THE RULE TABLE named in rule_table, and nothing else. \
+ It is computed as closure(base ∪ extension) minus closure(base) under that table, restricted \
+ to triples every name of which the base already used. It is NOT deductive conservativity in a \
+ description logic (ExpTime-complete for EL, 2ExpTime-complete for ALC, and UNDECIDABLE for \
+ ALCQIO) and it is NOT model conservativity (undecidable already for EL). The asymmetry is the \
+ point: a new consequence reported here IS a real change to what this engine derives over the \
+ old names, while finding none establishes only that this rule table derives nothing new, and \
+ never that the extension is conservative in any logic.";
+
+pub const FINDING_NOT_AN_ERROR: &str =
+ "a non-conservative extension is a FINDING, not a failure. Adding axioms that change what the \
+ ontology says about existing terms is often exactly the intended change; the point of \
+ reporting it is that it should be intended rather than discovered later. Each row names the \
+ rule that produced it and the premises the base did not have, so the decision can be made on \
+ the derivation rather than on the verdict word.";
+
+/// Five words, never collapsed into a boolean and never into each other.
+pub const CONSERVATIVE: &str = "conservative_under_rule_table";
+pub const NOT_CONSERVATIVE: &str = "not_conservative_under_rule_table";
+pub const UNDECIDED_TRUNCATED: &str = "undecided_scan_truncated";
+pub const UNDECIDED_NOT_AN_EXTENSION: &str = "undecided_not_an_extension";
+/// The engine derived something for the base that it did not derive for the
+/// EXTENDED graph. The base is a subset by construction and the rule table is
+/// monotone, so that cannot happen unless the engine is wrong, and no answer
+/// computed from those two closures means anything. It is never folded into
+/// `not_conservative`, because a soundness bug and a finding about the ontology
+/// go to opposite teams.
+pub const UNDECIDED_ENGINE_UNSOUND: &str = "undecided_engine_soundness_violation";
+
+// ───────────────────────────────────────────────────────────────────────────
+// Options
+// ───────────────────────────────────────────────────────────────────────────
+
+/// How to read the turtle the caller supplied.
+///
+/// Guessing it is not an option. A delta that happens to restate one triple of
+/// the base looks exactly like a replacement that dropped everything else, and
+/// the two answers are opposite, so the caller says which it meant.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ExtensionMode {
+ /// The turtle holds the axioms being ADDED. The result is an extension by
+ /// construction and nothing can be dropped.
+ Delta,
+ /// The turtle is the WHOLE proposed graph, as `onto_plan` receives it. Any
+ /// asserted triple of the base it does not contain is a removal, and a
+ /// change that removes is not an extension.
+ Replacement,
+}
+
+impl ExtensionMode {
+ pub fn parse(s: &str) -> anyhow::Result<ExtensionMode> {
+ match s {
+ "delta" | "added" => Ok(ExtensionMode::Delta),
+ "replacement" | "full" => Ok(ExtensionMode::Replacement),
+ other => anyhow::bail!(
+ "unknown extension mode {other:?}: pass \"delta\" (the turtle holds only what is \
+ being added) or \"replacement\" (the turtle is the whole proposed graph)"
+ ),
+ }
+ }
+ pub fn name(self) -> &'static str {
+ match self {
+ ExtensionMode::Delta => "delta",
+ ExtensionMode::Replacement => "replacement",
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct ConservativityOptions {
+ pub mode: ExtensionMode,
+ /// `rdfs`, `owl-rl` or `owl-rl-ext`. `owl-dl` is refused upstream, because
+ /// the tableaux path emits no rule trace.
+ pub profile: String,
+ /// Where both certificates land. A run is reproducible by hand from what it
+ /// leaves behind.
+ pub out: std::path::PathBuf,
+ /// How many new consequences are examined for signature membership. The
+ /// verdict is `undecided_scan_truncated` when the difference is larger,
+ /// because a verdict computed from a prefix of the difference is not a
+ /// verdict.
+ pub scan_rows: usize,
+ /// Rows rendered. Totals are always exact.
+ pub max_rows: usize,
+}
+
+impl Default for ConservativityOptions {
+ fn default() -> Self {
+ ConservativityOptions {
+ mode: ExtensionMode::Delta,
+ profile: "owl-rl".into(),
+ out: std::path::PathBuf::from("conservativity"),
+ scan_rows: 200_000,
+ max_rows: 100,
+ }
+ }
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Findings
+// ───────────────────────────────────────────────────────────────────────────
+
+/// A conclusion the extended ontology reaches and the base does not.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct NewConsequence {
+ pub triple: NtTriple,
+ /// True when every name in the triple is one the base already used, so this
+ /// row changes what the ontology says about terms that already existed.
+ /// That is the conservativity finding; the rest are the ordinary effect of
+ /// adding new terms.
+ pub over_old_signature: bool,
+ pub warrant: Warrant,
+ pub warrant_word: &'static str,
+ /// Named only where a machine-checked theorem stands behind the row.
+ pub theorem: Option<&'static str>,
+ /// The rule that first derived it in the extended ontology. `None` when the
+ /// extension ASSERTED it outright rather than deriving it.
+ pub rule: Option<String>,
+ /// The premises of that derivation the base's own closure does not hold:
+ /// what the extension had to add for this conclusion to appear. The
+ /// actionable half.
+ pub premises_the_base_lacked: Vec<NtTriple>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ConservativityReport {
+ pub format: &'static str,
+ /// One sentence the reader cannot miss, first after `format`.
+ pub headline: String,
+ /// `conservative_under_rule_table`, `not_conservative_under_rule_table`,
+ /// `undecided_scan_truncated`, `undecided_not_an_extension` or
+ /// `undecided_engine_soundness_violation`.
+ pub conservativity_verdict: &'static str,
+ /// `null` when the verdict is one of the undecided words. Never a bare
+ /// `conservative`, and never `false` standing in for "we could not tell".
+ pub conservative_under_rule_table: Option<bool>,
+ /// What the verdict is about. Not a decoration: the verdict means nothing
+ /// without it.
+ pub rule_table: String,
+ pub what_this_is_not: &'static str,
+ pub finding_not_an_error: &'static str,
+ /// How the supplied turtle was read: `delta` or `replacement`.
+ pub mode: &'static str,
+
+ /// True when the proposed graph contains every asserted triple of the base,
+ /// so applying it is a pure addition. False means the change also REMOVES,
+ /// and removal is not what conservativity is about: the verdict is then
+ /// undecided and the removals are counted.
+ pub is_an_extension: bool,
+ pub base_triples_the_proposal_drops: usize,
+ pub dropped_examples: Vec<String>,
+ /// Base triples whose blank nodes could not be matched against the
+ /// proposal, so `base_triples_the_proposal_drops` was decided over the
+ /// ground ones only. Counted, never folded into the denominator.
+ pub not_compared_blank_node_bearing: usize,
+
+ pub base_signature_size: usize,
+ /// Names the extension introduces that the base never used.
+ pub signature_added: Vec<String>,
+ pub signature_added_total: usize,
+
+ pub new_consequences_over_old_signature: Vec<NewConsequence>,
+ pub new_consequences_over_old_signature_total: usize,
+ /// Every new consequence, including those that mention a new name. Bigger
+ /// by construction and NOT the headline: a new class brings new conclusions
+ /// about itself, which is what adding a class is.
+ pub new_consequences_total: usize,
+ /// New consequences the scan did not examine, because the difference was
+ /// larger than `scan_rows`. Non-zero forces the undecided verdict.
+ pub not_examined: usize,
+
+ /// The engine's own soundness gate, run for free by the closure diff: a
+ /// conclusion the BASE reaches that the EXTENDED ontology does not. The
+ /// rule table is monotone and the base is a subset, so this must be empty,
+ /// and a non-empty list is an engine bug rather than a finding about the
+ /// ontology.
+ pub engine_soundness_violations: Vec<String>,
+ /// Non-null when the monotonicity gate did NOT run, with the reason, so an
+ /// empty violation list can never mean "we did not look".
+ pub engine_soundness_gate_skipped: Option<String>,
+
+ pub base_certificate: CertificateVerdict,
+ pub extended_certificate: CertificateVerdict,
+ pub seconds: f64,
+ /// 0 conservative under the rule table, 1 a finding, 2 undecided.
+ pub exit_code: i32,
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// The check
+// ───────────────────────────────────────────────────────────────────────────
+
+fn iri_of(term: &str) -> Option<&str> {
+ term.strip_prefix('<').and_then(|t| t.strip_suffix('>'))
+}
+
+fn is_logical(iri: &str) -> bool {
+ LOGICAL_NAMESPACES.iter().any(|ns| iri.starts_with(ns))
+}
+
+fn names_of<'a>(triples: impl Iterator<Item = &'a (String, String, String)>) -> BTreeSet<String> {
+ let mut out = BTreeSet::new();
+ for (s, p, o) in triples {
+ for t in [s, p, o] {
+ if let Some(i) = iri_of(t)
+ && !is_logical(i)
+ {
+ out.insert(i.to_string());
+ }
+ }
+ }
+ out
+}
+
+fn nt_of(triples: &[(String, String, String)]) -> String {
+ triples.iter().map(|(s, p, o)| format!("{s} {p} {o} .\n")).collect()
+}
+
+/// Does adding `extension_ttl` to `base` change any consequence over the names
+/// the base already used?
+///
+/// `extension_ttl` is read as the graph to MERGE IN, so the extended ontology
+/// is `base ∪ extension` and the subset precondition the monotonicity gate
+/// needs holds by construction. When the caller's turtle is a full REPLACEMENT
+/// rather than a delta — which is what `onto_plan` receives — the triples it
+/// drops are reported in `base_triples_the_proposal_drops` and the verdict
+/// becomes `undecided_not_an_extension`, because a change that removes is not
+/// an extension and this question is not the one to ask about it.
+pub fn conservativity_check(
+ base: &Arc<GraphStore>,
+ extension_ttl: &str,
+ opts: &ConservativityOptions,
+) -> anyhow::Result<ConservativityReport> {
+ let started = std::time::Instant::now();
+
+ // ── Ground both sides so every comparison is exact ───────────────────
+ let (base_sk, _) = pe::skolemise_with_prefix(base, BASE_SKOLEM_PREFIX)?;
+ let base_triples = base_sk.all_triples()?;
+ let base_nt = nt_of(&base_triples);
+
+ let extended = Arc::new(GraphStore::new());
+ extended.load_ntriples(&base_nt)?;
+ extended.load_turtle(extension_ttl, None).map_err(|e| {
+ anyhow::anyhow!("the proposed extension is not readable as Turtle: {e}")
+ })?;
+
+ // ── Is it an extension at all? Decided over the ORIGINAL base ────────
+ //
+ // Only in `Replacement` mode is the question meaningful. A delta says
+ // nothing about the triples it does not mention, so counting them as
+ // removals would report every delta as a removal of the entire ontology.
+ let proposed = Arc::new(GraphStore::new());
+ proposed.load_turtle(extension_ttl, None)?;
+ let original = base.all_triples()?;
+ let bn = |t: &(String, String, String)| {
+ pe::is_blank(&t.0) || pe::is_blank(&t.1) || pe::is_blank(&t.2)
+ };
+ let (dropped, not_compared_blank_node_bearing) = match opts.mode {
+ ExtensionMode::Delta => (Vec::new(), 0),
+ ExtensionMode::Replacement => {
+ let proposed_set: BTreeSet<(String, String, String)> =
+ proposed.all_triples()?.into_iter().collect();
+ let unmatched = original.iter().filter(|t| bn(t)).count()
+ + proposed_set.iter().filter(|t| bn(t)).count();
+ let gone: Vec<String> = original
+ .iter()
+ .filter(|t| !bn(t) && !proposed_set.contains(*t))
+ .map(|(s, p, o)| format!("{s} {p} {o}"))
+ .collect();
+ (gone, unmatched)
+ }
+ };
+ let is_an_extension = dropped.is_empty();
+ let mut dropped_examples: Vec<String> = dropped.iter().take(10).cloned().collect();
+ dropped_examples.sort();
+
+ // ── One closure diff, in the extension direction ─────────────────────
+ let diff_opts = DiffOptions {
+ profile: opts.profile.clone(),
+ out: opts.out.clone(),
+ checker: None,
+ // The base is already ground and the extension's blank nodes are
+ // skolemised by the diff itself, under the DEFAULT prefix, which cannot
+ // collide with BASE_SKOLEM_PREFIX.
+ skolemise_source: true,
+ max_rows: opts.scan_rows,
+ seed_iris: Vec::new(),
+ };
+ let ext_closure = SourceClosure::build(&extended, &diff_opts)?;
+ let report = ext_closure.diff(&base_nt, &diff_opts)?;
+
+ // ── Partition the difference by the OLD signature ────────────────────
+ let base_names = names_of(base_triples.iter());
+ let extension_names = names_of(proposed.all_triples()?.iter());
+ let signature_added: Vec<String> =
+ extension_names.difference(&base_names).cloned().collect();
+
+ let over_old = |t: &NtTriple| -> bool {
+ [&t.0, &t.1, &t.2].into_iter().all(|term| match iri_of(term) {
+ Some(i) => is_logical(i) || base_names.contains(i),
+ // A literal is a value, not a name. A blank node has no name that
+ // survives a graph boundary and is never waved through.
+ None => term.starts_with('"'),
+ })
+ };
+
+ let mut rows: Vec<NewConsequence> = Vec::new();
+ let mut over_old_total = 0usize;
+ for lost in &report.entailments_lost {
+ let is_over = over_old(&lost.triple);
+ if !is_over {
+ continue;
+ }
+ over_old_total += 1;
+ if rows.len() < opts.max_rows {
+ rows.push(NewConsequence {
+ triple: lost.triple.clone(),
+ over_old_signature: true,
+ warrant: lost.warrant,
+ warrant_word: lost.warrant_word,
+ theorem: lost.theorem,
+ rule: lost.rule.clone(),
+ premises_the_base_lacked: lost.blocking_premises.clone(),
+ });
+ }
+ }
+ let not_examined = report.lost_total.saturating_sub(report.entailments_lost.len());
+
+ let engine_soundness_violations: Vec<String> = report
+ .monotonicity_violations
+ .iter()
+ .map(|v| format!("{} {} {}", v.triple.0, v.triple.1, v.triple.2))
+ .collect();
+
+ // ── The verdict, never a bare boolean, and never collapsed ───────────
+ //
+ // The engine check comes FIRST. A monotonicity violation means the two
+ // closures this answer was computed from cannot both be right, so every
+ // count below it is meaningless, and reporting "not conservative" would
+ // send a soundness bug to the ontology's author.
+ let (verdict, flag, exit_code) = if !engine_soundness_violations.is_empty() {
+ (UNDECIDED_ENGINE_UNSOUND, None, 2)
+ } else if !is_an_extension {
+ (UNDECIDED_NOT_AN_EXTENSION, None, 2)
+ } else if not_examined > 0 {
+ (UNDECIDED_TRUNCATED, None, 2)
+ } else if over_old_total > 0 {
+ (NOT_CONSERVATIVE, Some(false), 1)
+ } else {
+ (CONSERVATIVE, Some(true), 0)
+ };
+
+ let headline = format!(
+ "{verdict}: {over_old_total} new consequence(s) over the {} name(s) the base already used, \
+ out of {} new consequence(s) in total, under the {} rule table. Extended certificate: \
+ {}{}. {}",
+ base_names.len(),
+ report.lost_total,
+ opts.profile,
+ report.source_certificate.verdict,
+ match report.source_certificate.theorem {
+ Some(t) => format!(" ({t})"),
+ None => String::new(),
+ },
+ WHAT_THIS_IS_NOT,
+ );
+
+ Ok(ConservativityReport {
+ format: "oo-conservativity/1",
+ headline,
+ conservativity_verdict: verdict,
+ conservative_under_rule_table: flag,
+ rule_table: opts.profile.clone(),
+ what_this_is_not: WHAT_THIS_IS_NOT,
+ finding_not_an_error: FINDING_NOT_AN_ERROR,
+ mode: opts.mode.name(),
+ is_an_extension,
+ base_triples_the_proposal_drops: dropped.len(),
+ dropped_examples,
+ not_compared_blank_node_bearing,
+ base_signature_size: base_names.len(),
+ signature_added_total: signature_added.len(),
+ signature_added: signature_added.into_iter().take(opts.max_rows).collect(),
+ new_consequences_over_old_signature: rows,
+ new_consequences_over_old_signature_total: over_old_total,
+ new_consequences_total: report.lost_total,
+ not_examined,
+ engine_soundness_violations,
+ engine_soundness_gate_skipped: report.monotonicity_gate_skipped.clone(),
+ base_certificate: report.projection_certificate.clone(),
+ extended_certificate: report.source_certificate.clone(),
+ seconds: started.elapsed().as_secs_f64(),
+ exit_code,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_logical_namespace_is_not_a_name() {
+ assert!(is_logical("http://www.w3.org/2000/01/rdf-schema#subClassOf"));
+ assert!(is_logical("http://www.w3.org/2002/07/owl#Thing"));
+ assert!(!is_logical("http://ex.org/Cat"));
+ }
+
+ #[test]
+ fn the_base_skolem_prefix_cannot_collide_with_the_default_one() {
+ // The default prefix maps `_:label` to `<PREFIX + label>` and an
+ // N-Triples blank node label cannot contain `/`, so no default-prefix
+ // skolem IRI can ever spell a base-prefix one.
+ assert!(BASE_SKOLEM_PREFIX.starts_with(pe::SKOLEM_PREFIX));
+ let tail = &BASE_SKOLEM_PREFIX[pe::SKOLEM_PREFIX.len()..];
+ assert!(tail.contains('/'), "the discriminator must be unspellable as a label: {tail:?}");
+ }
+
+ #[test]
+ fn five_verdict_words_and_no_bare_conservative() {
+ let words = [
+ CONSERVATIVE,
+ NOT_CONSERVATIVE,
+ UNDECIDED_TRUNCATED,
+ UNDECIDED_NOT_AN_EXTENSION,
+ UNDECIDED_ENGINE_UNSOUND,
+ ];
+ for w in words {
+ assert_ne!(w, "conservative", "a bare word is the one spelling that may not appear");
+ }
+ let distinct: BTreeSet<&str> = words.into_iter().collect();
+ assert_eq!(distinct.len(), words.len(), "two verdicts must never share a spelling");
+ }
+}
diff --git a/src/inputs.rs b/src/inputs.rs
index b75ce110..f7c1a312 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -417,6 +417,84 @@ pub struct OntoExtendInput {
pub struct OntoPlanInput {
/// New ontology as inline Turtle content
pub new_turtle: String,
+ /// Also answer whether the change alters any consequence over the names the
+ /// store ALREADY uses, under the rule table in `conservativity_profile`.
+ /// Default false: it reasons both graphs to a fixpoint, so it costs seconds
+ /// rather than milliseconds. When it is false the plan says so rather than
+ /// staying silent.
+ #[serde(default)]
+ pub check_conservativity: Option<bool>,
+ /// Rule table for the conservativity check: `rdfs`, `owl-rl` (default) or
+ /// `owl-rl-ext`. `owl-dl` is refused, because the tableaux path emits no
+ /// rule trace and every row would be unchecked.
+ #[serde(default)]
+ pub conservativity_profile: Option<String>,
+ /// Where the conservativity check's two certificates land, so the run is
+ /// reproducible by hand. Defaults to a temporary directory.
+ #[serde(default)]
+ pub conservativity_out_dir: Option<String>,
+}
+
+/// Input for `onto_module_extract` — a locality module, not a slice.
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoModuleExtractInput {
+ /// The IRIs the module must cover. Not optional and not defaulted: the
+ /// module over the empty signature is a real answer and never the wanted
+ /// one.
+ pub signature: Vec<String>,
+ /// `star` (the iterated ⊥⊤*, default and smallest), `bottom` or `top`.
+ #[serde(default)]
+ pub locality: Option<String>,
+ /// Re-attach `rdfs:label` / `rdfs:comment` for the terms the module keeps.
+ /// They are not part of the logical module and are counted separately.
+ #[serde(default)]
+ pub include_annotations: Option<bool>,
+ /// Reason the whole ontology and the module to a fixpoint and report every
+ /// conclusion over the signature the module does not reach, which must be
+ /// none. Writes both certificates here. Omit to skip the verification and
+ /// say so.
+ #[serde(default)]
+ pub verify_out_dir: Option<String>,
+ /// Rule table for the verification: `rdfs`, `owl-rl` or `owl-rl-ext`
+ /// (default).
+ #[serde(default)]
+ pub verify_profile: Option<String>,
+ /// How many of the conclusions the module does not reach are examined for
+ /// signature membership. Default 200,000. A verification computed from a
+ /// prefix of the difference is a SAMPLE, and `not_examined` says when the
+ /// bound bit, so a clean result over a truncated scan cannot read as a
+ /// clean result.
+ #[serde(default)]
+ pub verify_scan_rows: Option<usize>,
+ #[serde(default)]
+ pub max_rows: Option<usize>,
+}
+
+/// Input for `onto_conservative_check` — does adding these axioms change what
+/// the ontology already said?
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoConservativeCheckInput {
+ /// The proposed axioms, as Turtle.
+ pub extension_ttl: String,
+ /// Directory for both certificates and the report.
+ pub out_dir: String,
+ /// `delta` (default) reads `extension_ttl` as the axioms being ADDED.
+ /// `replacement` reads it as the whole proposed graph, the way `onto_plan`
+ /// receives it, and then reports any asserted triple of the base it drops.
+ /// This is not guessed: a delta that restates one base triple and a
+ /// replacement that dropped everything else look identical.
+ #[serde(default)]
+ pub mode: Option<String>,
+ /// `rdfs`, `owl-rl` (default) or `owl-rl-ext`. `owl-dl` is refused.
+ #[serde(default)]
+ pub profile: Option<String>,
+ /// How many new consequences are examined for signature membership. The
+ /// verdict is `undecided_scan_truncated` when there are more, because a
+ /// verdict computed from a prefix of the difference is not a verdict.
+ #[serde(default)]
+ pub scan_rows: Option<usize>,
+ #[serde(default)]
+ pub max_rows: Option<usize>,
}
#[derive(Deserialize, JsonSchema)]
diff --git a/src/lib.rs b/src/lib.rs
index 40a6e944..16d5c156 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -31,6 +31,12 @@ pub mod support;
pub mod temporal;
pub mod policy;
pub mod closure_diff;
+/// Deductive conservativity of an EXTENSION, under the rule table the engine
+/// evaluates and never under a stronger reading than that.
+pub mod conservativity;
+/// Syntactic locality modules (`⊥`, `⊤`, `⊥⊤*`): a subset of the axioms with a
+/// coverage theorem, as opposed to a slice with a measured loss.
+pub mod module_extract;
pub mod projection_check;
pub mod projection_entailment;
pub mod shape_combinatorics;
diff --git a/src/module_extract.rs b/src/module_extract.rs
new file mode 100644
index 00000000..e687ee32
--- /dev/null
+++ b/src/module_extract.rs
@@ -0,0 +1,1558 @@
+//! Syntactic locality modules: `⊥`, `⊤`, and the iterated `⊥⊤*`.
+//!
+//! [`crate::segment_retrieve`] produces a SLICE, and [`crate::closure_diff`]
+//! measures what a slice lost. This module produces a MODULE, which is a
+//! different kind of object: a subset of the axioms carrying a coverage
+//! theorem, so there is nothing left to measure afterwards.
+//!
+//! # The theorem, and whose it is
+//!
+//! For a signature `Σ`, an axiom is `⊥`-local when replacing every class and
+//! property name outside `Σ` by `⊥` turns it into a tautology, and `⊤`-local
+//! when the same replacement with `⊤` does. A module is extracted by repeatedly
+//! taking every axiom that is NOT local with respect to `Σ ∪ sig(M)`, until the
+//! set stops growing. Cuenca Grau, Horrocks, Kazakov and Sattler (JAIR 31,
+//! 2008, "Modular Reuse of Ontologies: Theory and Practice") prove that the
+//! result `M` satisfies `O ⊨ α iff M ⊨ α` for every axiom `α` over `Σ`, and
+//! that alternating the two extractions (`⊥⊤*`) preserves that property while
+//! shrinking the result.
+//!
+//! THAT THEOREM IS CITED, NOT CHECKED HERE. Nothing under `lean/` is about
+//! syntactic locality, and this file does not pretend otherwise: the report
+//! names a paper and never names a Lean theorem, and [`verify_module`] is
+//! supplied so the guarantee can be EXERCISED against the engine's own closure
+//! rather than asserted. `tests/module_extract_test.rs` runs that verification
+//! over the shipped pizza ontology, which is the difference between "we
+//! implemented an algorithm out of a paper" and "we ran it and nothing over the
+//! signature was lost".
+//!
+//! # Conservative wherever it cannot classify
+//!
+//! An RDF graph is not a list of OWL axioms, so the axioms have to be recovered
+//! from triples, and every recovery step has a failure mode. Each one resolves
+//! the same way: an axiom this file cannot classify is NEVER local, so it is
+//! INCLUDED. That direction is free, because any `M'` with `M ⊆ M' ⊆ O` still
+//! has the coverage property — a superset entails everything `M` entails, and
+//! `O` entails everything `M'` entails. Including too much costs size.
+//! Excluding too much costs the theorem.
+//!
+//! The counts are in the report and the kinds are named, so "the module is
+//! small" and "the module is small because half the file was unreadable" cannot
+//! render the same.
+
+use crate::graph::GraphStore;
+use crate::projection_entailment::{SKOLEM_PREFIX, Spelled};
+use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
+use std::sync::Arc;
+
+// ───────────────────────────────────────────────────────────────────────────
+// Vocabulary
+// ───────────────────────────────────────────────────────────────────────────
+
+const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
+const RDFS: &str = "http://www.w3.org/2000/01/rdf-schema#";
+const OWL: &str = "http://www.w3.org/2002/07/owl#";
+const XSD: &str = "http://www.w3.org/2001/XMLSchema#";
+
+/// Predicates OWL 2 fixes as annotation properties, plus the RDFS ones. A
+/// triple over one of these carries no logical content — UNLESS the ontology
+/// itself gives the property a domain, a range, a superproperty or an
+/// equivalent, which is legal RDF and makes the assertion load-bearing again.
+/// That case is detected in [`Index::build`] rather than assumed away.
+const ANNOTATION_PREDICATES: &[&str] = &[
+ "http://www.w3.org/2000/01/rdf-schema#label",
+ "http://www.w3.org/2000/01/rdf-schema#comment",
+ "http://www.w3.org/2000/01/rdf-schema#seeAlso",
+ "http://www.w3.org/2000/01/rdf-schema#isDefinedBy",
+ "http://www.w3.org/2002/07/owl#versionInfo",
+ "http://www.w3.org/2002/07/owl#deprecated",
+ "http://www.w3.org/2002/07/owl#priorVersion",
+ "http://www.w3.org/2002/07/owl#backwardCompatibleWith",
+ "http://www.w3.org/2002/07/owl#incompatibleWith",
+];
+
+/// `rdf:type` objects that DECLARE a term rather than assert membership of a
+/// user class.
+///
+/// `owl:Thing` and `rdfs:Resource` are in this list, and the reason is measured
+/// rather than aesthetic. `x rdf:type owl:Thing` is a TAUTOLOGY in the OWL 2
+/// direct semantics, so the locality test says it is `⊤`-local and drops it,
+/// and the paper's theorem is untouched. The OWL 2 RL rule table this engine
+/// evaluates does not REGENERATE it, so dropping it removes a member of the
+/// closure, and the verification then reports an entailment loss over the
+/// signature that is not one. Reading it as a declaration keeps it whenever the
+/// individual is in the signature, which makes the DL guarantee and the
+/// measured one hold at the same time. Found on
+/// `benchmark/reference/pizza-reference.owl`, where five individuals are
+/// asserted this way.
+const DECLARATION_TYPES: &[&str] = &[
+ "http://www.w3.org/2002/07/owl#Thing",
+ "http://www.w3.org/2000/01/rdf-schema#Resource",
+ "http://www.w3.org/2002/07/owl#Class",
+ "http://www.w3.org/2000/01/rdf-schema#Class",
+ "http://www.w3.org/2002/07/owl#ObjectProperty",
+ "http://www.w3.org/2002/07/owl#DatatypeProperty",
+ "http://www.w3.org/2002/07/owl#AnnotationProperty",
+ "http://www.w3.org/2002/07/owl#OntologyProperty",
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property",
+ "http://www.w3.org/2002/07/owl#NamedIndividual",
+ "http://www.w3.org/2002/07/owl#Ontology",
+ "http://www.w3.org/2000/01/rdf-schema#Datatype",
+ "http://www.w3.org/2002/07/owl#DataRange",
+];
+
+fn iri_of(term: &str) -> Option<&str> {
+ term.strip_prefix('<').and_then(|t| t.strip_suffix('>'))
+}
+fn is_bnode(term: &str) -> bool {
+ term.starts_with("_:")
+}
+fn is_literal(term: &str) -> bool {
+ term.starts_with('"')
+}
+fn is_builtin(iri: &str) -> bool {
+ iri.starts_with(RDF) || iri.starts_with(RDFS) || iri.starts_with(OWL) || iri.starts_with(XSD)
+}
+/// Allocation-free "is this exactly `owl:<local>`".
+fn owl_is(iri: &str, local: &str) -> bool {
+ iri.strip_prefix(OWL) == Some(local)
+}
+fn rdfs_is(iri: &str, local: &str) -> bool {
+ iri.strip_prefix(RDFS) == Some(local)
+}
+fn rdf_is(iri: &str, local: &str) -> bool {
+ iri.strip_prefix(RDF) == Some(local)
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Expressions
+// ───────────────────────────────────────────────────────────────────────────
+
+/// Which symbol a name outside the signature is replaced by.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Side {
+ /// `⊥`-locality: an external class becomes `owl:Nothing`, an external
+ /// property the empty property.
+ Bottom,
+ /// `⊤`-locality: an external class becomes `owl:Thing`, an external
+ /// property the universal property.
+ Top,
+}
+
+/// A class expression, as far as it could be read off the RDF.
+#[derive(Clone, Debug)]
+enum Ce {
+ Named(String),
+ Thing,
+ Nothing,
+ /// A datatype or data range. NOT a class name and NOT replaceable, so it is
+ /// neither `⊥`-equivalent nor `⊤`-equivalent under any signature. Treating
+ /// `xsd:integer` as an external class name and replacing it by `⊥` would
+ /// make `∃hasAge.xsd:integer` look local and drop the axiom: unsound, and
+ /// invisible, because the module still parses.
+ DataRange,
+ And(Vec<Ce>),
+ Or(Vec<Ce>),
+ Not(Box<Ce>),
+ /// `owl:oneOf`, carrying only the length: `{a₁ … aₙ}` is `⊥` exactly when
+ /// the list is empty, and is never `⊤`.
+ OneOf(usize),
+ Exists(Pe, Box<Ce>),
+ Forall(Pe, Box<Ce>),
+ HasValue(Pe),
+ HasSelf(Pe),
+ Min(u32, Pe, Box<Ce>),
+ /// `≤n R.C`. The number is deliberately NOT carried: `≤n R.C` is `⊤`
+ /// exactly when `R` is empty or `C` is empty, for EVERY `n`, and it is
+ /// never `⊥`, so the bound contributes nothing a locality test can read.
+ Max(Pe, Box<Ce>),
+ Exact(u32, Pe, Box<Ce>),
+ /// A term whose shape this file does not recognise. Neither `⊥` nor `⊤`,
+ /// which makes every axiom mentioning it non-local.
+ Unreadable,
+}
+
+/// A property expression.
+#[derive(Clone, Debug)]
+enum Pe {
+ Named(String),
+ /// `owl:inverseOf` applied to a named property. The locality of `R⁻` is the
+ /// locality of `R`.
+ Inverse(String),
+ TopProperty,
+ BottomProperty,
+ Unreadable,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Characteristic {
+ Transitive,
+ Symmetric,
+ Asymmetric,
+ Reflexive,
+ Irreflexive,
+ Functional,
+ InverseFunctional,
+}
+
+impl Characteristic {
+ fn name(self) -> &'static str {
+ match self {
+ Characteristic::Transitive => "transitive_property",
+ Characteristic::Symmetric => "symmetric_property",
+ Characteristic::Asymmetric => "asymmetric_property",
+ Characteristic::Reflexive => "reflexive_property",
+ Characteristic::Irreflexive => "irreflexive_property",
+ Characteristic::Functional => "functional_property",
+ Characteristic::InverseFunctional => "inverse_functional_property",
+ }
+ }
+}
+
+/// The OWL 2 axiom a root triple was read as.
+#[derive(Clone, Debug)]
+enum Form {
+ SubClassOf(Ce, Ce),
+ EquivalentClasses(Vec<Ce>),
+ DisjointClasses(Vec<Ce>),
+ DisjointUnion(Ce, Vec<Ce>),
+ SubPropertyOf(Pe, Pe),
+ PropertyChain(Vec<Pe>, Pe),
+ EquivalentProperties(Vec<Pe>),
+ DisjointProperties(Vec<Pe>),
+ Domain(Pe, Ce),
+ Range(Pe, Ce),
+ InverseProperties(Pe, Pe),
+ Characteristic(Characteristic, Pe),
+ HasKey(Ce),
+ ClassAssertion(Ce),
+ PropertyAssertion(Pe),
+ NegativePropertyAssertion(Pe),
+ /// `owl:sameAs`, `owl:differentFrom`, `owl:AllDifferent`. These mention no
+ /// class and no property name, so NO replacement can make them tautologies
+ /// and they are never local.
+ IndividualIdentity(&'static str),
+ /// `X rdf:type owl:Class` and friends. Vacuous in the OWL 2 direct
+ /// semantics; NOT vacuous for the OWL 2 RL rule table this engine
+ /// evaluates, where `scm-cls` reads it as a premise. Kept whenever the
+ /// declared term is in the working signature, which is the conservative
+ /// reading of the two.
+ Declaration(String),
+ Annotation,
+ Unclassified(String),
+}
+
+impl Form {
+ fn kind(&self) -> &'static str {
+ match self {
+ Form::SubClassOf(..) => "sub_class_of",
+ Form::EquivalentClasses(..) => "equivalent_classes",
+ Form::DisjointClasses(..) => "disjoint_classes",
+ Form::DisjointUnion(..) => "disjoint_union",
+ Form::SubPropertyOf(..) => "sub_property_of",
+ Form::PropertyChain(..) => "property_chain",
+ Form::EquivalentProperties(..) => "equivalent_properties",
+ Form::DisjointProperties(..) => "disjoint_properties",
+ Form::Domain(..) => "property_domain",
+ Form::Range(..) => "property_range",
+ Form::InverseProperties(..) => "inverse_properties",
+ Form::Characteristic(k, _) => k.name(),
+ Form::HasKey(..) => "has_key",
+ Form::ClassAssertion(..) => "class_assertion",
+ Form::PropertyAssertion(..) => "property_assertion",
+ Form::NegativePropertyAssertion(..) => "negative_property_assertion",
+ Form::IndividualIdentity(w) => w,
+ Form::Declaration(..) => "declaration",
+ Form::Annotation => "annotation",
+ Form::Unclassified(..) => "unclassified",
+ }
+ }
+}
+
+/// One axiom: the triples that spell it, the form it was read as, and the
+/// non-logical names it mentions.
+struct Axiom {
+ triples: Vec<Spelled>,
+ form: Form,
+ signature: BTreeSet<String>,
+ /// The root triple, rendered, for the unclassified report.
+ root: String,
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Locality
+// ───────────────────────────────────────────────────────────────────────────
+
+type Sig = BTreeSet<String>;
+
+fn c_bottom(c: &Ce, sig: &Sig, side: Side) -> bool {
+ match c {
+ Ce::Named(a) => side == Side::Bottom && !sig.contains(a),
+ Ce::Thing => false,
+ Ce::Nothing => true,
+ Ce::DataRange => false,
+ // An empty intersection is `owl:Thing`, so `any` is right: false on the
+ // empty list.
+ Ce::And(v) => v.iter().any(|x| c_bottom(x, sig, side)),
+ // An empty union is `owl:Nothing`, so `all` is right: true on the empty
+ // list.
+ Ce::Or(v) => v.iter().all(|x| c_bottom(x, sig, side)),
+ Ce::Not(x) => c_top(x, sig, side),
+ Ce::OneOf(n) => *n == 0,
+ Ce::Exists(p, f) => p_bottom(p, sig, side) || c_bottom(f, sig, side),
+ // `∀R.⊥` is "has no R-successor", which is satisfiable, so a universal
+ // restriction is never bottom-equivalent.
+ Ce::Forall(..) => false,
+ Ce::HasValue(p) => p_bottom(p, sig, side),
+ Ce::HasSelf(p) => p_bottom(p, sig, side),
+ Ce::Min(n, p, f) => *n >= 1 && (p_bottom(p, sig, side) || c_bottom(f, sig, side)),
+ Ce::Max(..) => false,
+ Ce::Exact(n, p, f) => *n >= 1 && (p_bottom(p, sig, side) || c_bottom(f, sig, side)),
+ Ce::Unreadable => false,
+ }
+}
+
+fn c_top(c: &Ce, sig: &Sig, side: Side) -> bool {
+ match c {
+ Ce::Named(a) => side == Side::Top && !sig.contains(a),
+ Ce::Thing => true,
+ Ce::Nothing => false,
+ Ce::DataRange => false,
+ Ce::And(v) => v.iter().all(|x| c_top(x, sig, side)),
+ Ce::Or(v) => v.iter().any(|x| c_top(x, sig, side)),
+ Ce::Not(x) => c_bottom(x, sig, side),
+ Ce::OneOf(_) => false,
+ Ce::Exists(p, f) => p_top(p, sig, side) && c_top(f, sig, side),
+ Ce::Forall(p, f) => c_top(f, sig, side) || p_bottom(p, sig, side),
+ Ce::HasValue(p) => p_top(p, sig, side),
+ Ce::HasSelf(p) => p_top(p, sig, side),
+ // `≥0 R.C` is `⊤`, and `≥1 ⊤.⊤` is `⊤` because the domain is non-empty.
+ // `≥2 ⊤.⊤` is NOT, in a one-element domain, so it is left non-top.
+ Ce::Min(n, p, f) => *n == 0 || (*n == 1 && p_top(p, sig, side) && c_top(f, sig, side)),
+ Ce::Max(p, f) => p_bottom(p, sig, side) || c_bottom(f, sig, side),
+ Ce::Exact(n, p, f) => *n == 0 && (p_bottom(p, sig, side) || c_bottom(f, sig, side)),
+ Ce::Unreadable => false,
+ }
+}
+
+fn p_bottom(p: &Pe, sig: &Sig, side: Side) -> bool {
+ match p {
+ Pe::Named(x) | Pe::Inverse(x) => side == Side::Bottom && !sig.contains(x),
+ Pe::TopProperty => false,
+ Pe::BottomProperty => true,
+ Pe::Unreadable => false,
+ }
+}
+
+fn p_top(p: &Pe, sig: &Sig, side: Side) -> bool {
+ match p {
+ Pe::Named(x) | Pe::Inverse(x) => side == Side::Top && !sig.contains(x),
+ Pe::TopProperty => true,
+ Pe::BottomProperty => false,
+ Pe::Unreadable => false,
+ }
+}
+
+/// Is this axiom a tautology once every name outside `sig` has been replaced?
+fn is_local(a: &Axiom, sig: &Sig, side: Side) -> bool {
+ let cb = |c: &Ce| c_bottom(c, sig, side);
+ let ct = |c: &Ce| c_top(c, sig, side);
+ let pb = |p: &Pe| p_bottom(p, sig, side);
+ let pt = |p: &Pe| p_top(p, sig, side);
+ match &a.form {
+ Form::SubClassOf(c, d) => cb(c) || ct(d),
+ Form::EquivalentClasses(v) => v.iter().all(cb) || v.iter().all(ct),
+ // `Disjoint(C₁ … Cₙ)` is a tautology when at most one operand is
+ // non-empty: nothing overlaps `⊥`.
+ Form::DisjointClasses(v) => v.iter().filter(|c| !cb(c)).count() <= 1,
+ Form::DisjointUnion(a, v) => cb(a) && v.iter().all(cb),
+ Form::SubPropertyOf(p, q) => pb(p) || pt(q),
+ Form::PropertyChain(chain, q) => pt(q) || chain.iter().any(pb),
+ Form::EquivalentProperties(v) => v.iter().all(pb) || v.iter().all(pt),
+ Form::DisjointProperties(v) => v.iter().filter(|p| !pb(p)).count() <= 1,
+ Form::Domain(p, c) => pb(p) || ct(c),
+ Form::Range(p, c) => pb(p) || ct(c),
+ Form::InverseProperties(p, q) => (pb(p) && pb(q)) || (pt(p) && pt(q)),
+ Form::Characteristic(k, p) => match k {
+ // The universal property is transitive and symmetric; the empty one
+ // vacuously is.
+ Characteristic::Transitive | Characteristic::Symmetric => pb(p) || pt(p),
+ // Only the universal property is reflexive.
+ Characteristic::Reflexive => pt(p),
+ // The universal property is none of these; the empty one is all of
+ // them, vacuously.
+ Characteristic::Asymmetric
+ | Characteristic::Irreflexive
+ | Characteristic::Functional
+ | Characteristic::InverseFunctional => pb(p),
+ },
+ Form::HasKey(c) => cb(c),
+ Form::ClassAssertion(c) => ct(c),
+ Form::PropertyAssertion(p) => pt(p),
+ Form::NegativePropertyAssertion(p) => pb(p),
+ Form::IndividualIdentity(_) => false,
+ // The empty name belongs to a declaration whose subject is not an IRI,
+ // which is not a shape this file reads. `!sig.contains("")` would be
+ // true against EVERY signature, so the empty case is spelled out rather
+ // than left to fall through to "local".
+ Form::Declaration(iri) => !iri.is_empty() && !sig.contains(iri),
+ Form::Annotation => true,
+ Form::Unclassified(_) => false,
+ }
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Reading axioms out of RDF
+// ───────────────────────────────────────────────────────────────────────────
+
+/// How deep a class expression is followed before it is declared unreadable. A
+/// cyclic blank-node structure is illegal OWL and legal RDF, so this is a
+/// termination guard rather than an expressiveness limit.
+const MAX_DEPTH: usize = 40;
+
+/// Longest `rdf:List` followed. Beyond it the list is unreadable, which makes
+/// the axiom non-local, which includes it.
+const MAX_LIST: usize = 5_000;
+
+struct Index {
+ triples: Vec<Spelled>,
+ by_subject: HashMap<String, Vec<usize>>,
+ object_terms: HashSet<String>,
+ /// Annotation predicates this ontology has given logical force, by
+ /// declaring a domain, a range, a superproperty or an equivalent for them.
+ /// Assertions over these are read as property assertions, not annotations.
+ loaded_annotation_predicates: BTreeSet<String>,
+}
+
+impl Index {
+ fn build(store: &Arc<GraphStore>) -> anyhow::Result<Index> {
+ let triples = store.all_triples()?;
+ let mut by_subject: HashMap<String, Vec<usize>> = HashMap::new();
+ let mut object_terms: HashSet<String> = HashSet::new();
+ for (i, (s, _, o)) in triples.iter().enumerate() {
+ by_subject.entry(s.clone()).or_default().push(i);
+ object_terms.insert(o.clone());
+ }
+ // An annotation property with a domain, a range, a superproperty or an
+ // equivalent is not an annotation property any more, whatever OWL 2
+ // says: the rule table will read assertions over it.
+ let mut loaded_annotation_predicates = BTreeSet::new();
+ for (s, p, _) in &triples {
+ let (Some(si), Some(pi)) = (iri_of(s), iri_of(p)) else { continue };
+ let loading = rdfs_is(pi, "domain")
+ || rdfs_is(pi, "range")
+ || rdfs_is(pi, "subPropertyOf")
+ || owl_is(pi, "equivalentProperty");
+ if loading && ANNOTATION_PREDICATES.contains(&si) {
+ loaded_annotation_predicates.insert(si.to_string());
+ }
+ }
+ Ok(Index { triples, by_subject, object_terms, loaded_annotation_predicates })
+ }
+
+ /// Triple indices with this subject. Elision ties the borrow to `&self`,
+ /// not to `subject`, which is what lets the results be returned.
+ fn rows(&self, subject: &str) -> &[usize] {
+ self.by_subject.get(subject).map(Vec::as_slice).unwrap_or(&[])
+ }
+
+ /// The first object of `subject <predicate> ?`, where `predicate` is
+ /// matched by a closure so no IRI has to be allocated to look one up.
+ fn object_where(&self, subject: &str, matches: impl Fn(&str) -> bool) -> Option<&str> {
+ self.rows(subject)
+ .iter()
+ .map(|i| &self.triples[*i])
+ .find(|t| iri_of(&t.1).is_some_and(&matches))
+ .map(|t| t.2.as_str())
+ }
+
+ fn owl_object(&self, subject: &str, local: &'static str) -> Option<&str> {
+ self.object_where(subject, move |p| owl_is(p, local))
+ }
+
+ fn has_type(&self, subject: &str, is_type: impl Fn(&str) -> bool) -> bool {
+ self.rows(subject).iter().any(|i| {
+ let t = &self.triples[*i];
+ iri_of(&t.1).is_some_and(|p| rdf_is(p, "type"))
+ && iri_of(&t.2).is_some_and(&is_type)
+ })
+ }
+
+ /// Follow an `rdf:List`. `None` when the structure is not a well-formed
+ /// list, which makes the containing axiom unreadable and therefore
+ /// non-local.
+ fn list(&self, head: &str) -> Option<Vec<String>> {
+ let mut out = Vec::new();
+ let mut cur = head.to_string();
+ let mut seen: HashSet<String> = HashSet::new();
+ while !iri_of(&cur).is_some_and(|i| rdf_is(i, "nil")) {
+ if out.len() > MAX_LIST || !seen.insert(cur.clone()) {
+ return None;
+ }
+ let f = self.object_where(&cur, |p| rdf_is(p, "first"))?.to_string();
+ out.push(f);
+ cur = self.object_where(&cur, |p| rdf_is(p, "rest"))?.to_string();
+ }
+ Some(out)
+ }
+
+ /// True when the term denotes a data range rather than a class.
+ fn is_data_range(&self, term: &str) -> bool {
+ if is_literal(term) {
+ return true;
+ }
+ if let Some(i) = iri_of(term) {
+ return i.starts_with(XSD) || rdfs_is(i, "Literal");
+ }
+ if is_bnode(term) {
+ return self.has_type(term, |t| rdfs_is(t, "Datatype"))
+ || self.owl_object(term, "onDatatype").is_some()
+ || self.owl_object(term, "datatypeComplementOf").is_some()
+ || self.owl_object(term, "withRestrictions").is_some();
+ }
+ false
+ }
+
+ fn property_expr(&self, term: &str) -> Pe {
+ if let Some(i) = iri_of(term) {
+ if owl_is(i, "topObjectProperty") || owl_is(i, "topDataProperty") {
+ return Pe::TopProperty;
+ }
+ if owl_is(i, "bottomObjectProperty") || owl_is(i, "bottomDataProperty") {
+ return Pe::BottomProperty;
+ }
+ return Pe::Named(i.to_string());
+ }
+ if is_bnode(term)
+ && let Some(inner) = self.owl_object(term, "inverseOf")
+ && let Some(i) = iri_of(inner)
+ {
+ return Pe::Inverse(i.to_string());
+ }
+ Pe::Unreadable
+ }
+
+ fn class_expr(&self, term: &str, depth: usize) -> Ce {
+ if depth > MAX_DEPTH {
+ return Ce::Unreadable;
+ }
+ if self.is_data_range(term) {
+ return Ce::DataRange;
+ }
+ if let Some(i) = iri_of(term) {
+ if owl_is(i, "Thing") {
+ return Ce::Thing;
+ }
+ if owl_is(i, "Nothing") {
+ return Ce::Nothing;
+ }
+ return Ce::Named(i.to_string());
+ }
+ if !is_bnode(term) {
+ return Ce::Unreadable;
+ }
+ for (pred, wrap) in [
+ ("intersectionOf", true),
+ ("unionOf", false),
+ ] {
+ if let Some(head) = self.owl_object(term, pred) {
+ let Some(items) = self.list(head) else { return Ce::Unreadable };
+ let v: Vec<Ce> = items.iter().map(|t| self.class_expr(t, depth + 1)).collect();
+ return if wrap { Ce::And(v) } else { Ce::Or(v) };
+ }
+ }
+ if let Some(c) = self.owl_object(term, "complementOf") {
+ return Ce::Not(Box::new(self.class_expr(c, depth + 1)));
+ }
+ if let Some(head) = self.owl_object(term, "oneOf") {
+ return match self.list(head) {
+ Some(items) => Ce::OneOf(items.len()),
+ None => Ce::Unreadable,
+ };
+ }
+ // A restriction. `owl:onProperties` is the n-ary data form and is not
+ // read here, so it falls through to Unreadable and is included.
+ let Some(on_property) = self.owl_object(term, "onProperty") else {
+ return Ce::Unreadable;
+ };
+ let p = self.property_expr(on_property);
+ if let Some(f) = self.owl_object(term, "someValuesFrom") {
+ return Ce::Exists(p, Box::new(self.class_expr(f, depth + 1)));
+ }
+ if let Some(f) = self.owl_object(term, "allValuesFrom") {
+ return Ce::Forall(p, Box::new(self.class_expr(f, depth + 1)));
+ }
+ if self.owl_object(term, "hasValue").is_some() {
+ return Ce::HasValue(p);
+ }
+ if self.owl_object(term, "hasSelf").is_some() {
+ return Ce::HasSelf(p);
+ }
+ let qualifier = self
+ .owl_object(term, "onClass")
+ .or_else(|| self.owl_object(term, "onDataRange"))
+ .map(|f| self.class_expr(f, depth + 1))
+ .unwrap_or(Ce::Thing);
+ let card = |local: &'static str| -> Option<u32> {
+ let raw = self.owl_object(term, local)?;
+ raw.strip_prefix('"')?.split('"').next()?.parse::<u32>().ok()
+ };
+ for (unqualified, qualified, build) in [
+ ("minCardinality", "minQualifiedCardinality", 0u8),
+ ("maxCardinality", "maxQualifiedCardinality", 1),
+ ("cardinality", "qualifiedCardinality", 2),
+ ] {
+ let found = card(unqualified)
+ .map(|n| (n, Ce::Thing))
+ .or_else(|| card(qualified).map(|n| (n, qualifier.clone())));
+ if let Some((n, f)) = found {
+ return match build {
+ 0 => Ce::Min(n, p, Box::new(f)),
+ 1 => Ce::Max(p, Box::new(f)),
+ _ => Ce::Exact(n, p, Box::new(f)),
+ };
+ }
+ }
+ Ce::Unreadable
+ }
+
+ /// Every triple the axiom rooted at `root_index` spells: the root, plus the
+ /// transitive blank-node structure it reaches.
+ fn axiom_triples(&self, root_index: usize) -> Vec<Spelled> {
+ let mut out: BTreeSet<Spelled> = BTreeSet::new();
+ let root = &self.triples[root_index];
+ out.insert(root.clone());
+ let mut seen: HashSet<String> = HashSet::new();
+ let mut stack: Vec<String> = [&root.0, &root.2]
+ .into_iter()
+ .filter(|t| is_bnode(t))
+ .cloned()
+ .collect();
+ while let Some(b) = stack.pop() {
+ if !seen.insert(b.clone()) {
+ continue;
+ }
+ for i in self.rows(&b) {
+ let t = &self.triples[*i];
+ out.insert(t.clone());
+ if is_bnode(&t.2) {
+ stack.push(t.2.clone());
+ }
+ }
+ }
+ out.into_iter().collect()
+ }
+}
+
+/// The non-logical names a set of triples mentions.
+fn signature_of(triples: &[Spelled]) -> BTreeSet<String> {
+ let mut out = BTreeSet::new();
+ for (s, p, o) in triples {
+ for t in [s, p, o] {
+ if let Some(i) = iri_of(t)
+ && !is_builtin(i)
+ {
+ out.insert(i.to_string());
+ }
+ }
+ }
+ out
+}
+
+fn render(t: &Spelled) -> String {
+ format!("{} {} {}", t.0, t.1, t.2)
+}
+
+/// Read the store as a list of axioms.
+fn axioms_of(ix: &Index) -> Vec<Axiom> {
+ let mut out = Vec::new();
+ for i in 0..ix.triples.len() {
+ let (s, p, o) = &ix.triples[i];
+ // A blank node some other triple points at is part of the axiom that
+ // points at it, not an axiom of its own.
+ if is_bnode(s) && ix.object_terms.contains(s) {
+ continue;
+ }
+ let Some(pi) = iri_of(p) else { continue };
+ let form = if is_bnode(s) {
+ bnode_rooted_form(ix, s, pi, o, i)
+ } else {
+ let mut f = iri_rooted_form(ix, pi, o);
+ if let Some(f) = f.as_mut() {
+ finish_subject(ix, f, s);
+ }
+ f
+ };
+ let Some(form) = form else { continue };
+ let triples = ix.axiom_triples(i);
+ let signature = signature_of(&triples);
+ out.push(Axiom { triples, form, signature, root: render(&ix.triples[i]) });
+ }
+ out
+}
+
+/// A blank-node-rooted axiom: `owl:AllDisjointClasses` and friends.
+///
+/// Exactly ONE triple of the structure becomes the axiom — the `rdf:type` one —
+/// so the structure is not read once per triple. A structure with no
+/// `rdf:type` at all is rooted at its first triple and reported unclassified,
+/// which includes it.
+fn bnode_rooted_form(ix: &Index, s: &str, pi: &str, o: &str, row: usize) -> Option<Form> {
+ if !rdf_is(pi, "type") {
+ if ix.has_type(s, |_| true) {
+ return None;
+ }
+ if ix.rows(s).first() != Some(&row) {
+ return None;
+ }
+ return Some(Form::Unclassified(format!("orphan blank-node structure on <{pi}>")));
+ }
+ let oi = iri_of(o).unwrap_or("");
+ let members = || ix.owl_object(s, "members").and_then(|h| ix.list(h));
+ if owl_is(oi, "AllDisjointClasses") {
+ return Some(match members() {
+ Some(v) => Form::DisjointClasses(v.iter().map(|t| ix.class_expr(t, 0)).collect()),
+ None => {
+ Form::Unclassified("owl:AllDisjointClasses with an unreadable member list".into())
+ }
+ });
+ }
+ if owl_is(oi, "AllDisjointProperties") {
+ return Some(match members() {
+ Some(v) => Form::DisjointProperties(v.iter().map(|t| ix.property_expr(t)).collect()),
+ None => {
+ Form::Unclassified("owl:AllDisjointProperties with an unreadable member list".into())
+ }
+ });
+ }
+ if owl_is(oi, "AllDifferent") {
+ return Some(Form::IndividualIdentity("different_individuals"));
+ }
+ if owl_is(oi, "NegativePropertyAssertion") {
+ return Some(match ix.owl_object(s, "assertionProperty") {
+ Some(p) => Form::NegativePropertyAssertion(ix.property_expr(p)),
+ None => Form::Unclassified(
+ "owl:NegativePropertyAssertion with no owl:assertionProperty".into(),
+ ),
+ });
+ }
+ if owl_is(oi, "Axiom") {
+ // Axiom reification annotates an axiom that is also asserted in its own
+ // right, so it carries no consequence of its own.
+ return Some(Form::Annotation);
+ }
+ Some(Form::Unclassified(format!("blank-node-rooted structure of type <{oi}>")))
+}
+
+fn iri_rooted_form(ix: &Index, pi: &str, o: &str) -> Option<Form> {
+ let ce = |t: &str| ix.class_expr(t, 0);
+ let pe = |t: &str| ix.property_expr(t);
+ if rdfs_is(pi, "subClassOf") {
+ return Some(Form::SubClassOf(Ce::Unreadable, ce(o)));
+ }
+ if owl_is(pi, "equivalentClass") {
+ return Some(Form::EquivalentClasses(vec![Ce::Unreadable, ce(o)]));
+ }
+ if owl_is(pi, "disjointWith") {
+ return Some(Form::DisjointClasses(vec![Ce::Unreadable, ce(o)]));
+ }
+ if owl_is(pi, "disjointUnionOf") {
+ return Some(match ix.list(o) {
+ Some(v) => Form::DisjointUnion(Ce::Unreadable, v.iter().map(|x| ce(x)).collect()),
+ None => Form::Unclassified("owl:disjointUnionOf with an unreadable list".into()),
+ });
+ }
+ if rdfs_is(pi, "subPropertyOf") {
+ return Some(Form::SubPropertyOf(Pe::Unreadable, pe(o)));
+ }
+ if owl_is(pi, "propertyChainAxiom") {
+ return Some(match ix.list(o) {
+ Some(v) => Form::PropertyChain(v.iter().map(|x| pe(x)).collect(), Pe::Unreadable),
+ None => Form::Unclassified("owl:propertyChainAxiom with an unreadable list".into()),
+ });
+ }
+ if owl_is(pi, "equivalentProperty") {
+ return Some(Form::EquivalentProperties(vec![Pe::Unreadable, pe(o)]));
+ }
+ if owl_is(pi, "propertyDisjointWith") {
+ return Some(Form::DisjointProperties(vec![Pe::Unreadable, pe(o)]));
+ }
+ if rdfs_is(pi, "domain") {
+ return Some(Form::Domain(Pe::Unreadable, ce(o)));
+ }
+ if rdfs_is(pi, "range") {
+ return Some(Form::Range(Pe::Unreadable, ce(o)));
+ }
+ if owl_is(pi, "inverseOf") {
+ return Some(Form::InverseProperties(Pe::Unreadable, pe(o)));
+ }
+ if owl_is(pi, "hasKey") {
+ return Some(Form::HasKey(Ce::Unreadable));
+ }
+ if owl_is(pi, "sameAs") {
+ return Some(Form::IndividualIdentity("same_individual"));
+ }
+ if owl_is(pi, "differentFrom") {
+ return Some(Form::IndividualIdentity("different_individuals"));
+ }
+ if rdf_is(pi, "type") {
+ return Some(type_form(ix, o));
+ }
+ if ANNOTATION_PREDICATES.contains(&pi) && !ix.loaded_annotation_predicates.contains(pi) {
+ return Some(Form::Annotation);
+ }
+ // Anything left in the RDF, RDFS, OWL or XSD namespaces is OWL vocabulary
+ // this file does not classify. It is NOT read as a property assertion,
+ // because an unrecognised `owl:` predicate could carry logical force, and
+ // reading it as an assertion would make it `⊤`-local and drop it.
+ if is_builtin(pi) {
+ return Some(Form::Unclassified(format!("unclassified built-in predicate <{pi}>")));
+ }
+ Some(Form::PropertyAssertion(Pe::Named(pi.to_string())))
+}
+
+/// `X rdf:type Y`: a declaration, a property characteristic, or a class
+/// assertion.
+fn type_form(ix: &Index, o: &str) -> Form {
+ let Some(oi) = iri_of(o) else {
+ return Form::ClassAssertion(ix.class_expr(o, 0));
+ };
+ if DECLARATION_TYPES.contains(&oi) {
+ // The declared term is the subject, filled in by `finish_subject`.
+ return Form::Declaration(String::new());
+ }
+ for (local, k) in [
+ ("TransitiveProperty", Characteristic::Transitive),
+ ("SymmetricProperty", Characteristic::Symmetric),
+ ("AsymmetricProperty", Characteristic::Asymmetric),
+ ("ReflexiveProperty", Characteristic::Reflexive),
+ ("IrreflexiveProperty", Characteristic::Irreflexive),
+ ("FunctionalProperty", Characteristic::Functional),
+ ("InverseFunctionalProperty", Characteristic::InverseFunctional),
+ ] {
+ if owl_is(oi, local) {
+ return Form::Characteristic(k, Pe::Unreadable);
+ }
+ }
+ // `owl:Restriction` and the other structural types reached at a ROOT mean a
+ // blank node nothing points at, or an IRI used as one: not a shape this
+ // file reads, so it is included rather than guessed at.
+ if oi.starts_with(OWL) && !owl_is(oi, "Thing") && !owl_is(oi, "Nothing") {
+ return Form::Unclassified(format!("rdf:type <{oi}> at an axiom root"));
+ }
+ Form::ClassAssertion(ix.class_expr(o, 0))
+}
+
+/// Fill in the subject side of a form parsed from the object side only.
+/// Splitting it this way keeps ONE place where the subject is read.
+fn finish_subject(ix: &Index, form: &mut Form, subject: &str) {
+ match form {
+ Form::SubClassOf(c, _) => *c = ix.class_expr(subject, 0),
+ Form::EquivalentClasses(v) | Form::DisjointClasses(v) => v[0] = ix.class_expr(subject, 0),
+ Form::DisjointUnion(c, _) | Form::HasKey(c) => *c = ix.class_expr(subject, 0),
+ Form::SubPropertyOf(p, _) => *p = ix.property_expr(subject),
+ Form::PropertyChain(_, q) => *q = ix.property_expr(subject),
+ Form::EquivalentProperties(v) | Form::DisjointProperties(v) => {
+ v[0] = ix.property_expr(subject)
+ }
+ Form::Domain(p, _) | Form::Range(p, _) => *p = ix.property_expr(subject),
+ Form::InverseProperties(p, _) => *p = ix.property_expr(subject),
+ Form::Characteristic(_, p) => *p = ix.property_expr(subject),
+ Form::Declaration(name) => *name = iri_of(subject).unwrap_or_default().to_string(),
+ _ => {}
+ }
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Extraction
+// ───────────────────────────────────────────────────────────────────────────
+
+/// Which module to extract.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Locality {
+ Bottom,
+ Top,
+ /// The iterated `⊥⊤*`: alternate the two until the set stops shrinking.
+ /// Never larger than either, and usually smaller than both.
+ Star,
+}
+
+impl Locality {
+ pub fn parse(s: &str) -> anyhow::Result<Locality> {
+ match s {
+ "bottom" | "⊥" => Ok(Locality::Bottom),
+ "top" | "⊤" => Ok(Locality::Top),
+ "star" | "bottom-top-star" | "⊥⊤*" => Ok(Locality::Star),
+ other => anyhow::bail!(
+ "unknown locality {other:?}: pass \"bottom\", \"top\" or \"star\" (the iterated ⊥⊤*)"
+ ),
+ }
+ }
+ pub fn name(self) -> &'static str {
+ match self {
+ Locality::Bottom => "bottom",
+ Locality::Top => "top",
+ Locality::Star => "star",
+ }
+ }
+ pub fn symbol(self) -> &'static str {
+ match self {
+ Locality::Bottom => "⊥",
+ Locality::Top => "⊤",
+ Locality::Star => "⊥⊤*",
+ }
+ }
+}
+
+/// One extraction pass, run to a fixpoint.
+///
+/// The fixpoint is not an optimisation, it is the SOUNDNESS CONDITION. The
+/// working signature grows with every axiom taken, and an axiom that looked
+/// local against `Σ` stops being local once a name it mentions has been pulled
+/// in. Stopping after one sweep would drop `a p₁ b` from a module that kept
+/// `p₁ ⊑ p₂`, and so lose `a p₂ b` over a signature containing `p₂`, `a` and
+/// `b`. `the_top_pass_iterates_rather_than_sweeping_once` pins the case.
+/// An axiom's locality depends only on which of the names IT MENTIONS are in
+/// the signature, so it can only stop being local when one of those names is
+/// added. That is what makes the index below correct and the naive rescan
+/// unnecessary: re-sweeping every axiom after every addition is quadratic, and
+/// an ontology of a hundred thousand axioms is not a hypothetical.
+fn extract_once(axioms: &[Axiom], over: &[usize], sigma: &Sig, side: Side) -> Vec<usize> {
+ let candidates: HashSet<usize> = over.iter().copied().collect();
+ let mut by_symbol: HashMap<&str, Vec<usize>> = HashMap::new();
+ for &i in over {
+ for s in &axioms[i].signature {
+ by_symbol.entry(s.as_str()).or_default().push(i);
+ }
+ }
+ let mut work = sigma.clone();
+ let mut taken: HashSet<usize> = HashSet::new();
+ // Everything is tested once; after that, only what a newly admitted name
+ // could have changed.
+ let mut queue: Vec<usize> = over.to_vec();
+ while let Some(i) = queue.pop() {
+ if !candidates.contains(&i) || taken.contains(&i) || is_local(&axioms[i], &work, side) {
+ continue;
+ }
+ taken.insert(i);
+ for s in &axioms[i].signature {
+ if work.insert(s.clone())
+ && let Some(v) = by_symbol.get(s.as_str())
+ {
+ queue.extend(v.iter().copied());
+ }
+ }
+ }
+ let mut out: Vec<usize> = taken.into_iter().collect();
+ out.sort_unstable();
+ out
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Options and report
+// ───────────────────────────────────────────────────────────────────────────
+
+#[derive(Clone, Debug)]
+pub struct ModuleOptions {
+ /// The IRIs the module must cover.
+ pub signature: Vec<String>,
+ pub locality: Locality,
+ /// Re-attach `rdfs:label`, `rdfs:comment` and the other annotation
+ /// assertions for terms the module keeps. They are NOT part of the logical
+ /// module and are counted separately, so the reported module size stays the
+ /// logical one.
+ pub include_annotations: bool,
+ /// Rows rendered per list. Totals are always exact.
+ pub max_rows: usize,
+}
+
+impl Default for ModuleOptions {
+ fn default() -> Self {
+ ModuleOptions {
+ signature: Vec::new(),
+ locality: Locality::Star,
+ include_annotations: false,
+ max_rows: 200,
+ }
+ }
+}
+
+/// An axiom taken into the module because this file could not classify it.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct UnclassifiedAxiom {
+ pub root_triple: String,
+ pub why: String,
+ pub triples: usize,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ModuleReport {
+ pub format: &'static str,
+ /// One sentence the reader cannot miss, first after `format`.
+ pub headline: String,
+ pub locality: &'static str,
+ pub locality_symbol: &'static str,
+
+ /// What the module guarantees, and whose theorem it is.
+ pub guarantee: &'static str,
+ /// The word that is NOT used, spelled out so it cannot be inferred.
+ pub guarantee_is_not_machine_checked: &'static str,
+ /// Axiom kinds whose locality was decided by a test written for that kind.
+ pub guarantee_covers: Vec<&'static str>,
+ /// Axiom kinds taken into the module WITHOUT a locality test, because no
+ /// replacement could make them tautologies or because they could not be
+ /// classified. Including is the safe direction; the counts are here so that
+ /// a small module and an unreadable one cannot render the same.
+ pub included_conservatively: BTreeMap<String, usize>,
+ pub unclassified_axioms: Vec<UnclassifiedAxiom>,
+ pub unclassified_total: usize,
+
+ pub signature_requested: Vec<String>,
+ /// Names in `signature_requested` that occur nowhere in the ontology. A
+ /// module over a misspelled IRI is empty and correct, which is the most
+ /// expensive way to learn about a typo.
+ pub signature_not_in_ontology: Vec<String>,
+ /// `Σ ∪ sig(M)`: everything the module's guarantee actually ranges over.
+ pub signature_closure: Vec<String>,
+ pub signature_closure_size: usize,
+
+ pub ontology_axioms: usize,
+ pub module_axioms: usize,
+ pub ontology_triples: usize,
+ pub module_triples: usize,
+ /// `module_triples / ontology_triples`, for reading only. It is NOT a
+ /// quality score: a module is not better for being smaller, it is correct
+ /// or it is not, and the size is what the signature costs.
+ pub module_fraction: f64,
+ pub axioms_by_kind: BTreeMap<String, usize>,
+ pub annotation_triples_added: usize,
+ /// The predicates this run treated as carrying no logical content, so a
+ /// reader can see exactly what "annotation" meant here. An annotation
+ /// predicate the ontology gave a domain, a range, a superproperty or an
+ /// equivalent is NOT in this list: it was read as a property assertion
+ /// instead, because the rule table will read it as one.
+ pub annotation_predicates_treated_as_vacuous: Vec<String>,
+ /// `⊥⊤` rounds. One for a plain `⊥` or `⊤` extraction.
+ pub rounds: usize,
+
+ pub module_ttl: String,
+ pub seconds: f64,
+}
+
+pub const GUARANTEE: &str =
+ "every axiom over the requested signature that the whole ontology entails, the module entails, \
+ and nothing else: M ⊨ α iff O ⊨ α for every α over Σ. That is the locality theorem of Cuenca \
+ Grau, Horrocks, Kazakov and Sattler (JAIR 31, 2008, 'Modular Reuse of Ontologies: Theory and \
+ Practice'), which holds for OWL 2 DL and therefore for every profile inside it. It is a \
+ COVERAGE guarantee and not a MINIMALITY one: a locality module is the smallest set the \
+ syntactic test can justify, not the smallest set that would do.";
+
+pub const NOT_MACHINE_CHECKED: &str =
+ "the locality theorem is CITED, not checked: nothing under lean/ is about syntactic locality, \
+ so this report names a paper and never names a Lean theorem. What can be checked here is the \
+ consequence rather than the theorem, and that is what verify_out_dir does — it reasons the \
+ whole ontology and the module to a fixpoint under one rule table and reports every conclusion \
+ over the signature the module does not reach, which must be none.";
+
+/// Axiom kinds with a locality test written for them.
+pub const CLASSIFIED_KINDS: &[&str] = &[
+ "sub_class_of",
+ "equivalent_classes",
+ "disjoint_classes",
+ "disjoint_union",
+ "sub_property_of",
+ "property_chain",
+ "equivalent_properties",
+ "disjoint_properties",
+ "property_domain",
+ "property_range",
+ "inverse_properties",
+ "transitive_property",
+ "symmetric_property",
+ "asymmetric_property",
+ "reflexive_property",
+ "irreflexive_property",
+ "functional_property",
+ "inverse_functional_property",
+ "has_key",
+ "class_assertion",
+ "property_assertion",
+ "negative_property_assertion",
+ "declaration",
+ "annotation",
+];
+
+/// Axiom kinds that are never local, so they are always in the module.
+pub const ALWAYS_INCLUDED_KINDS: &[&str] =
+ &["same_individual", "different_individuals", "unclassified"];
+
+// ───────────────────────────────────────────────────────────────────────────
+// The entry point
+// ───────────────────────────────────────────────────────────────────────────
+
+pub fn extract_module(
+ store: &Arc<GraphStore>,
+ opts: &ModuleOptions,
+) -> anyhow::Result<ModuleReport> {
+ let started = std::time::Instant::now();
+ if opts.signature.is_empty() {
+ anyhow::bail!(
+ "the signature is empty. The module over the empty signature is the set of axioms no \
+ replacement can turn into a tautology, which is a real answer and never the one \
+ anybody wanted: pass the IRIs the module has to cover"
+ );
+ }
+ let ix = Index::build(store)?;
+ let axioms = axioms_of(&ix);
+
+ let sigma: Sig = opts.signature.iter().cloned().collect();
+ let present: BTreeSet<String> = signature_of(&ix.triples);
+ let signature_not_in_ontology: Vec<String> =
+ sigma.iter().filter(|s| !present.contains(*s)).cloned().collect();
+
+ let all: Vec<usize> = (0..axioms.len()).collect();
+ let (module, rounds) = match opts.locality {
+ Locality::Bottom => (extract_once(&axioms, &all, &sigma, Side::Bottom), 1),
+ Locality::Top => (extract_once(&axioms, &all, &sigma, Side::Top), 1),
+ Locality::Star => {
+ let mut current = all;
+ let mut rounds = 0usize;
+ loop {
+ rounds += 1;
+ let b = extract_once(&axioms, &current, &sigma, Side::Bottom);
+ let t = extract_once(&axioms, &b, &sigma, Side::Top);
+ // Each pass only ever removes, so the length strictly decreases
+ // until the fixpoint and this terminates.
+ let done = t.len() == current.len();
+ current = t;
+ if done {
+ break;
+ }
+ }
+ (current, rounds)
+ }
+ };
+
+ let mut module_triples: BTreeSet<Spelled> = BTreeSet::new();
+ let mut by_kind: BTreeMap<String, usize> = BTreeMap::new();
+ let mut conservative: BTreeMap<String, usize> = BTreeMap::new();
+ let mut unclassified: Vec<UnclassifiedAxiom> = Vec::new();
+ let mut unclassified_total = 0usize;
+ let mut closure: BTreeSet<String> = sigma.clone();
+ for &i in &module {
+ let a = &axioms[i];
+ module_triples.extend(a.triples.iter().cloned());
+ closure.extend(a.signature.iter().cloned());
+ let kind = a.form.kind();
+ *by_kind.entry(kind.to_string()).or_default() += 1;
+ if ALWAYS_INCLUDED_KINDS.contains(&kind) {
+ *conservative.entry(kind.to_string()).or_default() += 1;
+ }
+ if let Form::Unclassified(why) = &a.form {
+ unclassified_total += 1;
+ if unclassified.len() < opts.max_rows {
+ unclassified.push(UnclassifiedAxiom {
+ root_triple: a.root.clone(),
+ why: why.clone(),
+ triples: a.triples.len(),
+ });
+ }
+ }
+ }
+
+ let mut annotation_triples_added = 0usize;
+ if opts.include_annotations {
+ for a in &axioms {
+ if !matches!(a.form, Form::Annotation) {
+ continue;
+ }
+ let kept = a
+ .triples
+ .first()
+ .and_then(|t| iri_of(&t.0))
+ .is_some_and(|s| closure.contains(s));
+ if kept {
+ for t in &a.triples {
+ if module_triples.insert(t.clone()) {
+ annotation_triples_added += 1;
+ }
+ }
+ }
+ }
+ }
+
+ let module_ttl: String = module_triples.iter().map(|t| format!("{} .\n", render(t))).collect();
+ let ontology_triples = ix.triples.len();
+ let module_fraction = if ontology_triples == 0 {
+ 0.0
+ } else {
+ module_triples.len() as f64 / ontology_triples as f64
+ };
+ let headline = format!(
+ "the {} module over {} requested name(s) is {} of {} axioms and {} of {} triples. {} \
+ axiom(s) were taken in WITHOUT a locality test because they could not be classified. {}",
+ opts.locality.symbol(),
+ opts.signature.len(),
+ module.len(),
+ axioms.len(),
+ module_triples.len(),
+ ontology_triples,
+ unclassified_total,
+ GUARANTEE,
+ );
+
+ Ok(ModuleReport {
+ format: "oo-locality-module/1",
+ headline,
+ locality: opts.locality.name(),
+ locality_symbol: opts.locality.symbol(),
+ guarantee: GUARANTEE,
+ guarantee_is_not_machine_checked: NOT_MACHINE_CHECKED,
+ guarantee_covers: CLASSIFIED_KINDS.to_vec(),
+ included_conservatively: conservative,
+ unclassified_axioms: unclassified,
+ unclassified_total,
+ signature_requested: opts.signature.clone(),
+ signature_not_in_ontology,
+ signature_closure_size: closure.len(),
+ signature_closure: closure.into_iter().collect(),
+ ontology_axioms: axioms.len(),
+ module_axioms: module.len(),
+ ontology_triples,
+ module_triples: module_triples.len(),
+ module_fraction,
+ axioms_by_kind: by_kind,
+ annotation_triples_added,
+ annotation_predicates_treated_as_vacuous: ANNOTATION_PREDICATES
+ .iter()
+ .filter(|p| !ix.loaded_annotation_predicates.contains(**p))
+ .map(|p| p.to_string())
+ .collect(),
+ rounds,
+ module_ttl,
+ seconds: started.elapsed().as_secs_f64(),
+ })
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Exercising the guarantee instead of asserting it
+// ───────────────────────────────────────────────────────────────────────────
+
+/// What the closure diff said about a module, filtered to the signature the
+/// module is supposed to cover.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ModuleVerification {
+ pub format: &'static str,
+ pub headline: String,
+ pub profile: String,
+ /// The one number that matters. A locality module may not lose ANY of
+ /// these, so a non-zero value is a defect in the extractor rather than a
+ /// property of the ontology.
+ pub lost_over_signature_total: usize,
+ pub lost_over_signature: Vec<crate::closure_diff::LostEntailment>,
+ /// Triples over the signature whose predicate is one of
+ /// `annotation_predicates_treated_as_vacuous`. They ARE gone from the
+ /// module and they are NOT entailment losses: the extractor drops them
+ /// deliberately, and it only calls a predicate vacuous after checking that
+ /// the ontology gives it no domain, range, superproperty or equivalent, so
+ /// no rule in the table can read one as a premise. Counted separately
+ /// rather than filtered out, because a silent filter is how a real loss
+ /// would eventually hide here.
+ pub lost_over_signature_annotation_only: usize,
+ pub annotation_losses_are_not_entailment_losses: &'static str,
+ /// Conclusions the module does not reach whose terms are NOT all in the
+ /// signature closure. Expected and unremarkable: that is what a module is
+ /// for.
+ pub lost_outside_signature_total: usize,
+ /// The BLIND SPOT, counted rather than left to be discovered. A subset of
+ /// `lost_outside_signature_total`, and one that could not have landed
+ /// anywhere else: a conclusion carrying a blank node or a Skolem IRI has no
+ /// term whose name means the same thing on both sides, so the signature
+ /// question cannot be ASKED of it, let alone answered. A large number here
+ /// means a `lost_over_signature_total: 0` covers less of the ontology than
+ /// it looks.
+ pub not_decided_blank_node_bearing: usize,
+ pub blind_spot_means: &'static str,
+ /// Conclusions the diff did not look at, because it renders at most
+ /// `max_rows` of them. Non-zero means this verification is a SAMPLE and
+ /// `lost_over_signature_total: 0` does not mean "nothing was lost".
+ pub not_examined: usize,
+ /// The engine's own soundness gate, run for free by the closure diff.
+ pub engine_soundness_violations: usize,
+ pub source_certificate: crate::closure_diff::CertificateVerdict,
+ pub means: &'static str,
+ pub seconds: f64,
+}
+
+pub const ANNOTATION_LOSSES_MEAN: &str =
+ "an rdfs:label or rdfs:comment the module drops is not a lost entailment: no rule in the table \
+ reads one as a premise, which is checked rather than assumed — a predicate the ontology gives \
+ a domain, a range, a superproperty or an equivalent is NOT counted here and is kept as a \
+ property assertion instead. Pass include_annotations to carry them into the module for \
+ reading; the logical module is the same either way.";
+
+pub const BLIND_SPOT_MEANS: &str =
+ "the module is serialised with the source store's own blank node labels, and the closure diff \
+ skolemises the source before comparing, so a conclusion carrying a blank node or a Skolem IRI \
+ has no name that means the same thing on both sides and is NOT decided against the signature. \
+ That is the same complexity decision 0007 documents and declines to close: deciding subgraph \
+ containment up to blank-node renaming is simple entailment, NP-complete in general. \
+ Skolemising the store before extracting the module empties this bucket, and until something \
+ does, the number is here so the coverage of a clean result can be read.";
+
+pub const VERIFICATION_MEANS: &str =
+ "this is the CONSEQUENCE of the locality theorem, measured; it is not the theorem. It reasons \
+ the whole ontology and the module to a fixpoint under one rule table and subtracts, so it can \
+ only ever speak about that rule table: a clean run says the module lost nothing this engine \
+ could derive over the signature, and says nothing about entailments the engine cannot reach. \
+ A non-zero lost_over_signature_total is a defect in the extractor.";
+
+/// Run the closure diff between the whole ontology and the module, and report
+/// the part the module's guarantee is about.
+///
+/// This is deliberately the same machinery `onto_closure_diff` runs. A second
+/// implementation of "what did this subset lose" would be a second place for
+/// the answer to be wrong.
+pub fn verify_module(
+ store: &Arc<GraphStore>,
+ module: &ModuleReport,
+ opts: &crate::closure_diff::DiffOptions,
+ scan_rows: usize,
+) -> anyhow::Result<ModuleVerification> {
+ let started = std::time::Instant::now();
+ let module_ttl = module.module_ttl.as_str();
+ let sig: BTreeSet<&str> = module.signature_closure.iter().map(String::as_str).collect();
+ let vacuous: BTreeSet<&str> =
+ module.annotation_predicates_treated_as_vacuous.iter().map(String::as_str).collect();
+ // The diff renders `max_rows` of the difference and counts the rest, but
+ // the signature partition has to see EVERY row: a verification computed
+ // from the first two hundred conclusions is a sample, and a clean sample
+ // is not a clean result. `scan_rows` bounds it so a pathological graph
+ // cannot exhaust memory, and `not_examined` says when the bound bit.
+ let scan = crate::closure_diff::DiffOptions { max_rows: scan_rows, ..opts.clone() };
+ let report = crate::closure_diff::closure_diff(store, module_ttl, &scan)?;
+ let over_signature = |t: &Spelled| -> bool {
+ [&t.0, &t.1, &t.2].into_iter().all(|term| match iri_of(term) {
+ Some(i) => is_builtin(i) || sig.contains(i),
+ // A literal is a value, not a name, so it never takes a triple out
+ // of the signature. A blank node has no name at all and cannot be
+ // decided, so it does.
+ None => is_literal(term),
+ })
+ };
+ let over: Vec<&crate::closure_diff::LostEntailment> =
+ report.entailments_lost.iter().filter(|l| over_signature(&l.triple)).collect();
+ let annotation_only = over
+ .iter()
+ .filter(|l| iri_of(&l.triple.1).is_some_and(|p| vacuous.contains(p)))
+ .count();
+ let lost: Vec<crate::closure_diff::LostEntailment> = over
+ .iter()
+ .filter(|l| !iri_of(&l.triple.1).is_some_and(|p| vacuous.contains(p)))
+ .map(|l| (*l).clone())
+ .collect();
+ let unnameable = |t: &Spelled| -> bool {
+ [&t.0, &t.1, &t.2].into_iter().any(|term| {
+ is_bnode(term)
+ || iri_of(term).is_some_and(|i| i.starts_with(SKOLEM_PREFIX))
+ })
+ };
+ let blind = report.entailments_lost.iter().filter(|l| unnameable(&l.triple)).count();
+ let scanned = report.entailments_lost.len();
+ let lost_over = lost.len();
+ let headline = format!(
+ "{lost_over} conclusion(s) over the signature closure are reachable from the whole \
+ ontology and not from the module, out of {scanned} examined of {} lost in total, plus \
+ {annotation_only} annotation triple(s) the module drops by design and {blind} carrying a \
+ blank node or a Skolem IRI, which cannot be decided against the signature at all. A \
+ locality module may not lose any of the first kind.",
+ report.lost_total
+ );
+ Ok(ModuleVerification {
+ format: "oo-module-verification/1",
+ headline,
+ profile: report.profile.clone(),
+ lost_over_signature_total: lost_over,
+ lost_over_signature: lost.into_iter().take(opts.max_rows).collect(),
+ lost_over_signature_annotation_only: annotation_only,
+ annotation_losses_are_not_entailment_losses: ANNOTATION_LOSSES_MEAN,
+ lost_outside_signature_total: scanned - lost_over - annotation_only,
+ not_decided_blank_node_bearing: blind,
+ blind_spot_means: BLIND_SPOT_MEANS,
+ not_examined: report.lost_total.saturating_sub(scanned),
+ engine_soundness_violations: report.monotonicity_violations.len(),
+ source_certificate: report.source_certificate.clone(),
+ means: VERIFICATION_MEANS,
+ seconds: started.elapsed().as_secs_f64(),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn loaded(ttl: &str) -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_turtle(ttl, None).unwrap();
+ g
+ }
+
+ const PREFIXES: &str = "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n\
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\
+ @prefix ex: <http://ex.org/> .\n";
+
+ fn chain() -> Arc<GraphStore> {
+ loaded(&format!(
+ "{PREFIXES}
+ ex:Cat rdfs:subClassOf ex:Mammal .
+ ex:Mammal rdfs:subClassOf ex:Animal .
+ ex:Animal rdfs:subClassOf ex:LivingThing .
+ ex:Plant rdfs:subClassOf ex:LivingThing ."
+ ))
+ }
+
+ fn opts(sig: &[&str], locality: Locality) -> ModuleOptions {
+ ModuleOptions {
+ signature: sig.iter().map(|s| s.to_string()).collect(),
+ locality,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn a_bottom_module_keeps_the_chain_and_drops_the_sibling() {
+ let r = extract_module(
+ &chain(),
+ &opts(&["http://ex.org/Cat", "http://ex.org/LivingThing"], Locality::Bottom),
+ )
+ .unwrap();
+ assert_eq!(r.module_axioms, 3, "{}", r.module_ttl);
+ assert!(r.module_ttl.contains("Cat"));
+ assert!(r.module_ttl.contains("Animal"));
+ assert!(!r.module_ttl.contains("Plant"), "the sibling is ⊥-local: {}", r.module_ttl);
+ }
+
+ /// The fixpoint IS the soundness condition, and this is the case that shows
+ /// it: the first sweep of the ⊤ pass finds `Cat ⊑ Mammal` and `Mammal ⊑
+ /// Animal` local, and only the signature growth from `Animal ⊑ LivingThing`
+ /// pulls them back in.
+ #[test]
+ fn the_top_pass_iterates_rather_than_sweeping_once() {
+ let r = extract_module(
+ &chain(),
+ &opts(&["http://ex.org/Cat", "http://ex.org/LivingThing"], Locality::Star),
+ )
+ .unwrap();
+ assert_eq!(r.module_axioms, 3, "{}", r.module_ttl);
+ for term in ["Cat", "Mammal", "Animal", "LivingThing"] {
+ assert!(r.module_ttl.contains(term), "{term} missing from {}", r.module_ttl);
+ }
+ }
+
+ /// `⊥⊤*` is strictly smaller than `⊥` here: the `⊥` pass keeps an ABox
+ /// assertion over an external property, and the `⊤` pass removes it.
+ #[test]
+ fn star_is_strictly_smaller_than_bottom_on_an_external_assertion() {
+ let g = loaded(&format!(
+ "{PREFIXES}
+ ex:Cat rdfs:subClassOf ex:LivingThing .
+ ex:tom ex:eats ex:fish ."
+ ));
+ let sig = ["http://ex.org/Cat", "http://ex.org/LivingThing"];
+ let bottom = extract_module(&g, &opts(&sig, Locality::Bottom)).unwrap();
+ let star = extract_module(&g, &opts(&sig, Locality::Star)).unwrap();
+ assert_eq!(bottom.module_axioms, 2, "{}", bottom.module_ttl);
+ assert_eq!(star.module_axioms, 1, "{}", star.module_ttl);
+ assert!(!star.module_ttl.contains("eats"));
+ }
+
+ #[test]
+ fn an_unclassified_builtin_predicate_is_included_not_dropped() {
+ let g = loaded(&format!(
+ "{PREFIXES}
+ ex:Cat rdfs:subClassOf ex:LivingThing .
+ ex:Cat owl:members ex:Nonsense ."
+ ));
+ let r = extract_module(
+ &g,
+ &opts(&["http://ex.org/Cat", "http://ex.org/LivingThing"], Locality::Star),
+ )
+ .unwrap();
+ assert_eq!(r.unclassified_total, 1, "{:?}", r.axioms_by_kind);
+ assert!(r.module_ttl.contains("members"), "{}", r.module_ttl);
+ }
+
+ #[test]
+ fn same_as_is_never_local() {
+ let g = loaded(&format!("{PREFIXES}\nex:a owl:sameAs ex:b ."));
+ let r = extract_module(&g, &opts(&["http://ex.org/Unrelated"], Locality::Star)).unwrap();
+ assert_eq!(r.module_axioms, 1);
+ assert_eq!(r.included_conservatively.get("same_individual"), Some(&1));
+ }
+
+ #[test]
+ fn a_datatype_filler_is_not_treated_as_an_external_class_name() {
+ let g = loaded(&format!(
+ "{PREFIXES}
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ ex:Person rdfs:subClassOf
+ [ a owl:Restriction ; owl:onProperty ex:age ; owl:someValuesFrom xsd:integer ] ."
+ ));
+ // `xsd:integer` is not a class name, so `∃age.xsd:integer` is not
+ // ⊥-equivalent and the axiom is not ⊥-local over {Person}.
+ let r = extract_module(&g, &opts(&["http://ex.org/Person"], Locality::Bottom)).unwrap();
+ assert_eq!(r.module_axioms, 1, "{}", r.module_ttl);
+ assert!(r.module_ttl.contains("someValuesFrom"));
+ }
+
+ #[test]
+ fn an_empty_signature_is_an_error_not_an_empty_module() {
+ let e = extract_module(&chain(), &opts(&[], Locality::Star)).unwrap_err();
+ assert!(e.to_string().contains("signature is empty"), "{e}");
+ }
+
+ #[test]
+ fn a_signature_name_absent_from_the_ontology_is_named() {
+ let r = extract_module(&chain(), &opts(&["http://ex.org/Typo"], Locality::Star)).unwrap();
+ assert_eq!(r.signature_not_in_ontology, vec!["http://ex.org/Typo".to_string()]);
+ }
+
+ #[test]
+ fn a_declaration_survives_for_a_term_in_the_signature() {
+ let g = loaded(&format!("{PREFIXES}\nex:Cat a owl:Class .\nex:Dog a owl:Class ."));
+ let r = extract_module(&g, &opts(&["http://ex.org/Cat"], Locality::Star)).unwrap();
+ assert_eq!(r.module_axioms, 1, "{}", r.module_ttl);
+ assert!(r.module_ttl.contains("Cat"));
+ assert!(!r.module_ttl.contains("Dog"));
+ }
+
+ /// An annotation property the ontology has given a domain is not an
+ /// annotation property any more, and its assertions carry consequences.
+ #[test]
+ fn a_loaded_annotation_predicate_stops_being_vacuous() {
+ let g = loaded(&format!(
+ "{PREFIXES}
+ rdfs:label rdfs:domain ex:Named .
+ ex:thing rdfs:label \"x\" ."
+ ));
+ let r = extract_module(&g, &opts(&["http://ex.org/Named"], Locality::Bottom)).unwrap();
+ assert!(
+ r.module_ttl.contains("label"),
+ "a label assertion under a declared domain is a property assertion: {}",
+ r.module_ttl
+ );
+ }
+
+ #[test]
+ fn locality_names_round_trip() {
+ for (word, l) in
+ [("bottom", Locality::Bottom), ("top", Locality::Top), ("star", Locality::Star)]
+ {
+ assert_eq!(Locality::parse(word).unwrap(), l);
+ assert_eq!(l.name(), word);
+ }
+ assert!(Locality::parse("sideways").is_err());
+ }
+}
diff --git a/src/plan.rs b/src/plan.rs
index 13b7bd58..adbf6683 100644
--- a/src/plan.rs
+++ b/src/plan.rs
@@ -102,6 +102,58 @@ impl Planner {
/// Compute a diff plan between current store and proposed new Turtle.
pub fn plan(&self, new_turtle: &str) -> anyhow::Result<String> {
+ self.plan_checked(new_turtle, None)
+ }
+
+ /// [`Planner::plan`], optionally answering the semantic question as well as
+ /// the syntactic one.
+ ///
+ /// Everything else a plan reports is about SHAPE: which classes appear,
+ /// which disappear, how many triples move. None of it can tell you that
+ /// adding one `rdfs:domain` silently reclassified nine hundred existing
+ /// individuals, because that change adds no class and removes nothing. The
+ /// conservativity block is the only part of a plan that is about MEANING,
+ /// and it is opt-in because it reasons both graphs to a fixpoint, which is
+ /// seconds rather than milliseconds on a real store.
+ ///
+ /// It is never fatal. A plan whose conservativity check could not run says
+ /// so in `conservativity.skipped` and still returns the plan, because a
+ /// diagnostic that can block a plan is a diagnostic people turn off.
+ pub fn plan_checked(
+ &self,
+ new_turtle: &str,
+ conservativity: Option<crate::conservativity::ConservativityOptions>,
+ ) -> anyhow::Result<String> {
+ let mut result: serde_json::Value = serde_json::from_str(&self.plan_inner(new_turtle)?)?;
+ result["conservativity"] = match conservativity {
+ None => serde_json::json!({
+ "ran": false,
+ "skipped": "not requested. Pass check_conservativity=true to ask whether this \
+ change alters any consequence over the names the store already uses, \
+ under the rule table named in profile. It reasons both graphs to a \
+ fixpoint, so it is not free.",
+ }),
+ Some(opts) => {
+ match crate::conservativity::conservativity_check(&self.graph, new_turtle, &opts) {
+ Ok(r) => {
+ let mut v = serde_json::to_value(&r)?;
+ v["ran"] = serde_json::Value::Bool(true);
+ v
+ }
+ Err(e) => serde_json::json!({
+ "ran": false,
+ "skipped": format!(
+ "the conservativity check could not run, so this plan says nothing \
+ about what the change means: {e}"
+ ),
+ }),
+ }
+ }
+ };
+ Ok(result.to_string())
+ }
+
+ fn plan_inner(&self, new_turtle: &str) -> anyhow::Result<String> {
let current_classes = self.extract_classes_from_store(&self.graph);
let current_properties = self.extract_properties_from_store(&self.graph);
diff --git a/src/projection_entailment.rs b/src/projection_entailment.rs
index 9afede15..d418f1fc 100644
--- a/src/projection_entailment.rs
+++ b/src/projection_entailment.rs
@@ -121,12 +121,29 @@ fn has_blank(t: &Spelled) -> bool {
/// that makes a re-parsed slice comparable, because the slice then carries real
/// IRIs and nothing has to be matched.
pub fn skolemise(g: &Arc<GraphStore>) -> anyhow::Result<(Arc<GraphStore>, BTreeMap<String, String>)> {
+ skolemise_with_prefix(g, SKOLEM_PREFIX)
+}
+
+/// [`skolemise`] under a caller-chosen prefix.
+///
+/// Two graphs skolemised SEPARATELY under the same prefix can collide: the map
+/// is `_:label ↦ prefix + label`, and two unrelated graphs both containing
+/// `_:b0` would then agree on an IRI that names two different things. Any
+/// caller that skolemises one graph and later merges another into it has to
+/// keep the two apart, and a distinct prefix is the only thing that does it.
+/// `_` is not a legal character-run separator in an N-Triples blank node label
+/// and `/` cannot appear in one at all, so a prefix ending in `/base/` cannot
+/// be produced by the default prefix over any label.
+pub fn skolemise_with_prefix(
+ g: &Arc<GraphStore>,
+ prefix: &str,
+) -> anyhow::Result<(Arc<GraphStore>, BTreeMap<String, String>)> {
let mut map: BTreeMap<String, String> = BTreeMap::new();
let mut nt = String::new();
for (s, p, o) in g.all_triples()? {
let mut one = |term: &str| -> String {
if let Some(label) = term.strip_prefix("_:") {
- let iri = format!("<{SKOLEM_PREFIX}{label}>");
+ let iri = format!("<{prefix}{label}>");
map.insert(iri.clone(), term.to_string());
iri
} else {
diff --git a/src/server.rs b/src/server.rs
index 06005f73..e9e344c8 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1530,7 +1530,7 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_segment_retrieve", description = "Retrieve a TBox-slice neighbourhood of seed IRIs for grounding LLM reasoning (#34, SEMANTiCS 2025 GrOWL-RAG). Walks `rdfs:subClassOf` / `subPropertyOf` / `domain` / `range` + `owl:equivalentClass` / `equivalentProperty` / `disjointWith` / `inverseOf` to `hops` depth (default 2). Returns the slice as Turtle plus IRI/triple counts and any frontier IRIs hit at the hop budget. Pairs with `graph_projection_lossy_check`: this retrieves, that audits. Pass `include_abox=true` to also pull instance triples for each seed.")]
+ #[tool(name = "onto_segment_retrieve", description = "Retrieve a TBox-slice neighbourhood of seed IRIs for grounding LLM reasoning (#34, SEMANTiCS 2025 GrOWL-RAG). Walks `rdfs:subClassOf` / `subPropertyOf` / `domain` / `range` + `owl:equivalentClass` / `equivalentProperty` / `disjointWith` / `inverseOf` to `hops` depth (default 2). Returns the slice as Turtle plus IRI/triple counts and any frontier IRIs hit at the hop budget. Pairs with `graph_projection_lossy_check`: this retrieves, that audits. Pass `include_abox=true` to also pull instance triples for each seed. A NEIGHBOURHOOD IS NOT A MODULE: the hop budget is a heuristic, so what this drops has to be measured afterwards by onto_closure_diff. When the question is 'give me the part of the ontology that matters for these IRIs' and losing an entailment over them is not acceptable, use onto_module_extract instead, which carries a coverage theorem rather than a loss report.")]
async fn onto_segment_retrieve(&self, Parameters(input): Parameters<OntoSegmentRetrieveInput>) -> String {
let hops = input.hops.unwrap_or(2);
let include_abox = input.include_abox.unwrap_or(false);
@@ -1619,7 +1619,7 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_closure_diff", description = "Which CONCLUSIONS a projection preserves, with no goals supplied. Reasons the source and the slice to a fixpoint under the same rule table and reports closure(source) minus closure(projection), partitioned by whether every term of the lost conclusion occurs in the projection: lost_in_projection_vocabulary is the headline, because a conclusion over terms the slice never mentions cannot ground an answer the slice supports. Each lost row names the rule and the blocking premises the retriever dropped. Three warrant words, never collapsed: checked (a Lean-accepted certificate, OOCert.certificate_sound), asserted_in_source (a lookup, nothing was proved), engine_opinion (no checker looked, or it said no). Also runs the monotonicity gate and reports when the gate did NOT run and why, so an empty violation list can never mean 'we did not look'. Skolemises the source by default so blank-node-bearing triples can be compared at all. The offline form; graph_projection_entailment_check is the per-answer one.")]
+ #[tool(name = "onto_closure_diff", description = "Which CONCLUSIONS a projection preserves, with no goals supplied. Reasons the source and the slice to a fixpoint under the same rule table and reports closure(source) minus closure(projection), partitioned by whether every term of the lost conclusion occurs in the projection: lost_in_projection_vocabulary is the headline, because a conclusion over terms the slice never mentions cannot ground an answer the slice supports. Each lost row names the rule and the blocking premises the retriever dropped. Three warrant words, never collapsed: checked (a Lean-accepted certificate, OOCert.certificate_sound), asserted_in_source (a lookup, nothing was proved), engine_opinion (no checker looked, or it said no). Also runs the monotonicity gate and reports when the gate did NOT run and why, so an empty violation list can never mean 'we did not look'. Skolemises the source by default so blank-node-bearing triples can be compared at all. The offline form; graph_projection_entailment_check is the per-answer one. This MEASURES loss and is the right tool for a slice; a locality module from onto_module_extract has no loss to measure over its signature, and this is what verifies that.")]
async fn onto_closure_diff(&self, Parameters(input): Parameters<OntoClosureDiffInput>) -> String {
use crate::closure_diff as cd;
let opts = cd::DiffOptions {
@@ -1637,6 +1637,85 @@ impl OpenOntologiesServer {
}
}
+ #[tool(name = "onto_module_extract", description = "A MODULE over a signature, not a slice: the smallest subset of the axioms syntactic locality can justify, such that every entailment of the WHOLE ontology over those IRIs is still an entailment of the subset. Where onto_segment_retrieve retrieves a neighbourhood and onto_closure_diff then MEASURES what it lost, this cannot lose anything over the signature, and the difference is a theorem rather than a metric: Cuenca Grau, Horrocks, Kazakov and Sattler, JAIR 31 (2008), for ⊥-locality, ⊤-locality and the iterated ⊥⊤*. THAT THEOREM IS CITED, NOT MACHINE-CHECKED: nothing under lean/ is about locality, so this names a paper and never names a Lean theorem — pass verify_out_dir to have the consequence measured instead, which reasons the ontology and the module to a fixpoint and reports every conclusion over the signature the module does not reach (which must be none). THE GUARANTEE COVERS these axiom types, each with a locality test written for it: SubClassOf, EquivalentClasses, DisjointClasses, DisjointUnion, SubPropertyOf, property chains, EquivalentProperties, DisjointProperties, domain, range, InverseProperties, the seven property characteristics (transitive, symmetric, asymmetric, reflexive, irreflexive, functional, inverse-functional), HasKey, class assertions, property assertions, negative property assertions, declarations and annotations, over class expressions built from intersection, union, complement, oneOf, someValuesFrom, allValuesFrom, hasValue, hasSelf and the six cardinality forms. INCLUDED CONSERVATIVELY, with no locality test, because no replacement can make them tautologies: owl:sameAs, owl:differentFrom, owl:AllDifferent, every unrecognised predicate in the RDF/RDFS/OWL/XSD namespaces, every blank-node structure whose shape is not one of the above, and every malformed rdf:List. Those are COUNTED AND NAMED in the report, so a module that is small and a module that was unreadable cannot look the same. Datatypes are never treated as class names, because replacing xsd:integer by ⊥ would make ∃hasAge.xsd:integer look local and drop the axiom. TWO PLACES WHERE OWL 2 AND THIS ENGINE'S RULE TABLE DISAGREE, both resolved towards the rule table: a declaration (X rdf:type owl:Class) is logically vacuous in OWL 2 and is a PREMISE of OWL 2 RL's scm-cls, and X rdf:type owl:Thing is a tautology in OWL 2 that the rule table does not regenerate, so both are kept whenever the term is in the signature. Annotation assertions (rdfs:label, rdfs:comment and the rest) are NOT in the logical module; the vacuity is checked rather than assumed, so an annotation predicate the ontology gives a domain, range, superproperty or equivalent is kept as a property assertion instead, and annotation_predicates_treated_as_vacuous lists what was dropped. Pass include_annotations to carry the labels along for reading; the logical module is the same either way.")]
+ async fn onto_module_extract(&self, Parameters(input): Parameters<OntoModuleExtractInput>) -> String {
+ use crate::module_extract as me;
+ let locality = match me::Locality::parse(input.locality.as_deref().unwrap_or("star")) {
+ Ok(l) => l,
+ Err(e) => return Self::err_json(e),
+ };
+ let opts = me::ModuleOptions {
+ signature: input.signature,
+ locality,
+ include_annotations: input.include_annotations.unwrap_or(false),
+ max_rows: input.max_rows.unwrap_or(200),
+ };
+ let report = match me::extract_module(&self.graph, &opts) {
+ Ok(r) => r,
+ Err(e) => return Self::err_json(e),
+ };
+ let mut body = match serde_json::to_value(&report) {
+ Ok(v) => v,
+ Err(e) => return Self::err_json(format!("serialization: {}", e)),
+ };
+ // A module that was never verified and a module that verified clean
+ // must not render the same, so the absence is a field.
+ body["verification"] = match input.verify_out_dir {
+ None => serde_json::json!({
+ "ran": false,
+ "skipped": "not requested. Pass verify_out_dir to reason the whole ontology and \
+ the module to a fixpoint and report every conclusion over the \
+ signature the module does not reach, which must be none.",
+ }),
+ Some(dir) => {
+ let diff = crate::closure_diff::DiffOptions {
+ profile: input.verify_profile.unwrap_or_else(|| "owl-rl-ext".to_string()),
+ out: std::path::PathBuf::from(dir),
+ max_rows: opts.max_rows,
+ ..Default::default()
+ };
+ match me::verify_module(
+ &self.graph,
+ &report,
+ &diff,
+ input.verify_scan_rows.unwrap_or(200_000),
+ ) {
+ Ok(v) => {
+ let mut v = serde_json::to_value(&v).unwrap_or_default();
+ v["ran"] = serde_json::Value::Bool(true);
+ v
+ }
+ Err(e) => serde_json::json!({
+ "ran": false,
+ "skipped": format!("the verification could not run: {e}"),
+ }),
+ }
+ }
+ };
+ body.to_string()
+ }
+
+ #[tool(name = "onto_conservative_check", description = "Does adding these axioms change anything the ontology ALREADY said? Reasons base and base+extension to a fixpoint under one rule table and reports closure(base ∪ extension) minus closure(base), restricted to triples every name of which the base already used. Each row names the rule that produced it and the premises the base did not have, so the change can be judged on the derivation rather than on a verdict word. A NON-CONSERVATIVE EXTENSION IS A FINDING, NOT AN ERROR: changing what the ontology says about existing terms is often the intended change, and the point is that it should be intended rather than discovered later. BE CLEAR ABOUT THE FRAGMENT. The verdict field is conservativity_verdict with five words (conservative_under_rule_table, not_conservative_under_rule_table, undecided_scan_truncated, undecided_not_an_extension, undecided_engine_soundness_violation) and the boolean beside it is conservative_under_rule_table, null whenever the answer is undecided rather than false, because a reader takes false for a finding. The monotonicity gate runs on every call and its violation gets its OWN word: the base is a subset of the extended graph by construction and the rule table is monotone, so a conclusion the base reaches and the extension does not is an engine soundness bug, and folding it into not_conservative would send it to the ontology's author instead of the engine's. There is deliberately no field called `conservative`. What is computed is conservativity WITH RESPECT TO THE HORN RULE TABLE this engine evaluates, which derives only positive ground triples. It is NOT deductive conservativity in a description logic (ExpTime-complete for EL, 2ExpTime-complete for ALC, UNDECIDABLE for ALCQIO) and NOT model conservativity (undecidable already for EL). The asymmetry is the point: a new consequence reported here IS a real change to what this engine derives over the old names, while finding none establishes only that this rule table derives nothing new. onto_plan takes check_conservativity=true to run the same check as part of a plan, which is where it belongs.")]
+ async fn onto_conservative_check(&self, Parameters(input): Parameters<OntoConservativeCheckInput>) -> String {
+ use crate::conservativity as cx;
+ let mode = match cx::ExtensionMode::parse(input.mode.as_deref().unwrap_or("delta")) {
+ Ok(m) => m,
+ Err(e) => return Self::err_json(e),
+ };
+ let opts = cx::ConservativityOptions {
+ mode,
+ profile: input.profile.unwrap_or_else(|| "owl-rl".to_string()),
+ out: std::path::PathBuf::from(&input.out_dir),
+ scan_rows: input.scan_rows.unwrap_or(200_000),
+ max_rows: input.max_rows.unwrap_or(100),
+ };
+ match cx::conservativity_check(&self.graph, &input.extension_ttl, &opts) {
+ Ok(r) => serde_json::to_string(&r)
+ .unwrap_or_else(|e| Self::err_json(format!("serialization: {}", e))),
+ Err(e) => Self::err_json(e),
+ }
+ }
+
#[tool(name = "onto_certify_action", description = "CIVeX-style causal certificate for a proposed state-changing ontology action. Returns a verdict (EXECUTE / REJECT / EXPERIMENT / ABSTAIN) plus an auditable certificate documenting the assumptions, structural-dependency identification proof, utility point estimate + one-sided lower confidence bound, provenance hash, and risk bound. Use as a pre-flight gate for onto_apply / onto_save / onto_push / onto_ingest. Scaffold port of arXiv:2605.09168 — structural-dependency proxy in place of full do-calculus identifiability; documented honestly.")]
async fn onto_certify_action(&self, Parameters(input): Parameters<OntoCertifyActionInput>) -> String {
let frame = crate::civex::ActionFrame {
@@ -2053,14 +2132,38 @@ impl OpenOntologiesServer {
// ── v2: Lifecycle tools ─────────────────────────────────────────────────
- #[tool(name = "onto_plan", description = "Terraform-style plan: diff current store against proposed Turtle. Shows added/removed classes/properties, blast radius, risk score, and locked IRI violations.")]
+ #[tool(name = "onto_plan", description = "Terraform-style plan: diff current store against proposed Turtle. Shows added/removed classes/properties, blast radius, risk score, and locked IRI violations. All of that is about SHAPE. Pass check_conservativity=true for the one part that is about MEANING: whether the change alters any consequence over the names the store already uses, under the rule table in conservativity_profile. That is the check a shape diff cannot do — adding one 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. It reasons both graphs to a fixpoint, so it is opt-in; when it is off the plan says so under `conservativity` rather than staying silent. Read the honesty note in onto_conservative_check before acting on the verdict: it is conservativity under a Horn rule table, not in a description logic.")]
pub async fn onto_plan(&self, Parameters(input): Parameters<OntoPlanInput>) -> String {
let planner = crate::plan::Planner::with_owner(
self.db.clone(),
self.graph.clone(),
&self.session_id,
);
- match planner.plan(&input.new_turtle) {
+ // `onto_plan` receives the WHOLE proposed graph, so the mode is fixed
+ // here rather than exposed: reading a replacement as a delta would
+ // report a change that deletes half the ontology as an extension.
+ let conservativity = input.check_conservativity.unwrap_or(false).then(|| {
+ crate::conservativity::ConservativityOptions {
+ mode: crate::conservativity::ExtensionMode::Replacement,
+ profile: input.conservativity_profile.unwrap_or_else(|| "owl-rl".to_string()),
+ out: input
+ .conservativity_out_dir
+ .map(std::path::PathBuf::from)
+ .unwrap_or_else(|| {
+ // Per CALL, not per process. Two plans running at once
+ // in one server would otherwise write their two
+ // certificates into the same directory and each read
+ // the other's.
+ std::env::temp_dir().join(format!(
+ "oo-plan-conservativity-{}-{:016x}",
+ std::process::id(),
+ crate::lineage::rand_id()
+ ))
+ }),
+ ..Default::default()
+ }
+ });
+ match planner.plan_checked(&input.new_turtle, conservativity) {
Ok(result) => {
self.lineage().record(&self.session_id, "P", "plan", "computed");
result
@@ -3005,6 +3108,6 @@ impl OpenOntologiesServer {
impl ServerHandler for OpenOntologiesServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(ServerCapabilities::builder().enable_tools().enable_prompts().build())
- .with_instructions("Open Ontologies: AI-native ontology engine, an RDF/OWL/SPARQL MCP server with 114 tools and 6 workflow prompts for ontology engineering, validation, comparison, alignment, data ingestion, and exploration. All 112 tools are advertised in a default build; 8 of them require an optional Cargo feature (embeddings, plugins, postgres or duckdb) and return an error without it.")
+ .with_instructions("Open Ontologies: AI-native ontology engine, an RDF/OWL/SPARQL MCP server with 116 tools and 6 workflow prompts for ontology engineering, validation, comparison, alignment, data ingestion, and exploration. All 116 tools are advertised in a default build; 8 of them require an optional Cargo feature (embeddings, plugins, postgres or duckdb) and return an error without it.")
}
}
diff --git a/tests/conservativity_test.rs b/tests/conservativity_test.rs
new file mode 100644
index 00000000..c21b1956
--- /dev/null
+++ b/tests/conservativity_test.rs
@@ -0,0 +1,336 @@
+//! Adding an axiom either changes what the ontology already said, or it does
+//! not, and the difference is invisible to every other number a plan reports.
+//!
+//! The pair that matters is `adding_a_domain_reclassifies_existing_individuals`
+//! and `adding_a_disconnected_hierarchy_changes_nothing_over_the_old_names`.
+//! They start from the SAME base and differ by two triples, the plan's shape
+//! diff cannot tell them apart (both add a class or a triple and remove
+//! nothing), and one of them silently retypes existing data.
+
+use open_ontologies::conservativity as cx;
+use open_ontologies::graph::GraphStore;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+const BASE: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://ex.org/> .
+
+ex:Person a owl:Class .
+ex:hasParent a owl:ObjectProperty .
+ex:Alice ex:hasParent ex:Bob .
+"#;
+
+const EX: &str = "http://ex.org/";
+const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
+
+fn loaded(ttl: &str) -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_turtle(ttl, None).unwrap_or_else(|e| panic!("fixture must parse: {e}\n{ttl}"));
+ g
+}
+
+fn scratch(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("oo-cx-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+fn opts(name: &str, mode: cx::ExtensionMode) -> cx::ConservativityOptions {
+ cx::ConservativityOptions { mode, out: scratch(name), ..Default::default() }
+}
+
+fn check(name: &str, extension: &str, mode: cx::ExtensionMode) -> cx::ConservativityReport {
+ cx::conservativity_check(&loaded(BASE), extension, &opts(name, mode))
+ .expect("the check must run")
+}
+
+fn rendered(r: &cx::ConservativityReport) -> Vec<String> {
+ r.new_consequences_over_old_signature
+ .iter()
+ .map(|c| format!("{} {} {}", c.triple.0, c.triple.1, c.triple.2))
+ .collect()
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// It changed something
+// ───────────────────────────────────────────────────────────────────────────
+
+/// One `rdfs:domain` triple. It adds no class, removes nothing, and retypes
+/// every existing subject of `ex:hasParent`. A shape diff sees a single
+/// addition; this sees the reclassification.
+#[test]
+fn adding_a_domain_reclassifies_existing_individuals() {
+ let r = check(
+ "domain",
+ "@prefix ex: <http://ex.org/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \
+ ex:hasParent rdfs:domain ex:Person .",
+ cx::ExtensionMode::Delta,
+ );
+ assert_eq!(r.conservativity_verdict, cx::NOT_CONSERVATIVE, "{}", r.headline);
+ assert_eq!(r.conservative_under_rule_table, Some(false));
+ assert_eq!(r.exit_code, 1, "a finding is exit 1, not an error");
+
+ let want = format!("<{EX}Alice> <{RDF_TYPE}> <{EX}Person>");
+ assert!(
+ rendered(&r).contains(&want),
+ "the reclassification must be named, not summarised: {:#?}",
+ rendered(&r)
+ );
+
+ // The row has to carry the derivation, or the user is being asked to
+ // trust a verdict word.
+ let row = r
+ .new_consequences_over_old_signature
+ .iter()
+ .find(|c| format!("{} {} {}", c.triple.0, c.triple.1, c.triple.2) == want)
+ .unwrap();
+ assert_eq!(row.rule.as_deref(), Some("rdfs2"), "the rule that produced it: {row:?}");
+ assert!(row.over_old_signature);
+ assert!(
+ row.premises_the_base_lacked
+ .iter()
+ .any(|p| p.1.contains("domain")),
+ "the premise the base lacked is the domain axiom itself: {:#?}",
+ row.premises_the_base_lacked
+ );
+}
+
+/// A second, structurally different way to change the old vocabulary: a
+/// subclass edge between two classes that both already existed.
+#[test]
+fn adding_a_subclass_edge_between_existing_classes_is_a_finding() {
+ let base = format!("{BASE}\n@prefix ex2: <http://ex.org/> . ex2:Agent a <http://www.w3.org/2002/07/owl#Class> .");
+ let r = cx::conservativity_check(
+ &loaded(&base),
+ "@prefix ex: <http://ex.org/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \
+ ex:Person rdfs:subClassOf ex:Agent .",
+ &opts("subclass", cx::ExtensionMode::Delta),
+ )
+ .unwrap();
+ assert_eq!(r.conservativity_verdict, cx::NOT_CONSERVATIVE, "{}", r.headline);
+ let want = format!(
+ "<{EX}Person> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <{EX}Agent>"
+ );
+ assert!(rendered(&r).contains(&want), "{:#?}", rendered(&r));
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// It changed nothing over the old names
+// ───────────────────────────────────────────────────────────────────────────
+
+/// The control. Two triples, both over names the base never used. The extension
+/// adds plenty of NEW consequences, which is what adding a class does; none of
+/// them is over the old signature, which is the whole question.
+#[test]
+fn adding_a_disconnected_hierarchy_changes_nothing_over_the_old_names() {
+ let r = check(
+ "disconnected",
+ "@prefix ex: <http://ex.org/> . @prefix owl: <http://www.w3.org/2002/07/owl#> . \
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \
+ ex:Robot a owl:Class . ex:Android rdfs:subClassOf ex:Robot .",
+ cx::ExtensionMode::Delta,
+ );
+ assert_eq!(r.conservativity_verdict, cx::CONSERVATIVE, "{}\n{:#?}", r.headline, rendered(&r));
+ assert_eq!(r.conservative_under_rule_table, Some(true));
+ assert_eq!(r.new_consequences_over_old_signature_total, 0);
+ assert_eq!(r.exit_code, 0);
+ // A clean verdict over an extension that derived nothing at all would be
+ // vacuous, so the control has to have moved the closure.
+ assert!(
+ r.new_consequences_total > 0,
+ "the extension must add SOME consequence, or 'none over the old signature' says nothing"
+ );
+ assert_eq!(
+ r.signature_added_total, 2,
+ "two new names: {:?}",
+ r.signature_added
+ );
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// The honesty of the verdict
+// ───────────────────────────────────────────────────────────────────────────
+
+/// The field name is the whole point of the feature. A reader who sees
+/// `conservative: true` will believe something nobody can compute.
+#[test]
+fn the_payload_never_carries_a_bare_conservative_flag() {
+ let r = check(
+ "wording",
+ "@prefix ex: <http://ex.org/> . @prefix owl: <http://www.w3.org/2002/07/owl#> . \
+ ex:Robot a owl:Class .",
+ cx::ExtensionMode::Delta,
+ );
+ let json = serde_json::to_string(&r).unwrap();
+ assert!(
+ !json.contains("\"conservative\""),
+ "no field may be called `conservative`, because conservativity in a description logic is \
+ not what was computed"
+ );
+ assert!(json.contains("\"conservative_under_rule_table\""));
+ assert!(json.contains("\"conservativity_verdict\""));
+ // The fragment has to travel in the payload, not only in the docs, because
+ // the docs are not what a dashboard renders.
+ for phrase in ["UNDECIDABLE for ALCQIO", "undecidable already for EL", "rule_table"] {
+ assert!(json.contains(phrase), "the payload must carry {phrase:?}");
+ }
+ assert!(json.contains("FINDING, not a failure"));
+}
+
+/// A change that REMOVES is not an extension, and the question does not apply
+/// to it. Reporting it as conservative would be the dangerous answer, and
+/// reporting it as non-conservative would be a false alarm, so it is neither.
+#[test]
+fn a_replacement_that_drops_a_base_triple_is_undecided_not_conservative() {
+ let r = check(
+ "removal",
+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://ex.org/> . \
+ ex:Person a owl:Class . ex:hasParent a owl:ObjectProperty .",
+ cx::ExtensionMode::Replacement,
+ );
+ assert_eq!(r.conservativity_verdict, cx::UNDECIDED_NOT_AN_EXTENSION, "{}", r.headline);
+ assert_eq!(r.conservative_under_rule_table, None, "undecided is null, never false");
+ assert!(!r.is_an_extension);
+ assert_eq!(r.base_triples_the_proposal_drops, 1, "{:?}", r.dropped_examples);
+ assert_eq!(r.exit_code, 2);
+ assert!(r.dropped_examples.iter().any(|d| d.contains("Alice")));
+}
+
+/// The same turtle, read the other way round. A delta says nothing about the
+/// triples it does not mention, so the mode is asked for rather than guessed.
+#[test]
+fn the_same_turtle_read_as_a_delta_is_not_a_removal() {
+ let ttl = "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://ex.org/> . \
+ ex:Person a owl:Class . ex:hasParent a owl:ObjectProperty .";
+ let as_delta = check("mode-delta", ttl, cx::ExtensionMode::Delta);
+ let as_replacement = check("mode-replacement", ttl, cx::ExtensionMode::Replacement);
+ assert!(as_delta.is_an_extension);
+ assert_eq!(as_delta.base_triples_the_proposal_drops, 0);
+ assert_eq!(as_delta.conservativity_verdict, cx::CONSERVATIVE);
+ assert!(!as_replacement.is_an_extension);
+ assert_ne!(as_delta.conservativity_verdict, as_replacement.conservativity_verdict);
+}
+
+#[test]
+fn an_unknown_mode_is_refused_by_name() {
+ let e = cx::ExtensionMode::parse("maybe").unwrap_err().to_string();
+ assert!(e.contains("delta"), "{e}");
+ assert!(e.contains("replacement"), "{e}");
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// The engine's own gate, riding along
+// ───────────────────────────────────────────────────────────────────────────
+
+/// The base is a subset of the extended graph by construction and the rule
+/// table is monotone, so nothing the base derives may be missing from the
+/// extension's closure. That gate must be ARMED, not merely empty: an empty
+/// violation list under a disarmed gate means "we did not look".
+#[test]
+fn the_monotonicity_gate_is_armed_and_finds_nothing() {
+ let r = check(
+ "monotonicity",
+ "@prefix ex: <http://ex.org/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \
+ ex:hasParent rdfs:domain ex:Person .",
+ cx::ExtensionMode::Delta,
+ );
+ assert!(r.engine_soundness_violations.is_empty(), "{:?}", r.engine_soundness_violations);
+ assert!(
+ r.engine_soundness_gate_skipped.is_none(),
+ "the gate must actually run, or the empty list proves nothing: {:?}",
+ r.engine_soundness_gate_skipped
+ );
+}
+
+/// Blank nodes on both sides used to be the reason the gate could not run.
+/// Skolemising the base under its OWN prefix before the extension is merged in
+/// is what keeps them apart: the same label on both sides must not become the
+/// same IRI.
+#[test]
+fn blank_nodes_in_the_base_do_not_disarm_the_gate() {
+ let base = "@prefix owl: <http://www.w3.org/2002/07/owl#> . \
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \
+ @prefix ex: <http://ex.org/> . \
+ ex:Cheesy rdfs:subClassOf \
+ [ a owl:Restriction ; owl:onProperty ex:hasTopping ; \
+ owl:someValuesFrom ex:Cheese ] .";
+ let r = cx::conservativity_check(
+ &loaded(base),
+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . \
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \
+ @prefix ex: <http://ex.org/> . \
+ ex:Deep rdfs:subClassOf \
+ [ a owl:Restriction ; owl:onProperty ex:hasBase ; owl:someValuesFrom ex:Thin ] .",
+ &opts("blanks", cx::ExtensionMode::Delta),
+ )
+ .unwrap();
+ assert!(
+ r.engine_soundness_gate_skipped.is_none(),
+ "blank nodes on both sides must not disarm the gate: {:?}",
+ r.engine_soundness_gate_skipped
+ );
+ assert!(r.engine_soundness_violations.is_empty());
+ assert_eq!(r.conservativity_verdict, cx::CONSERVATIVE, "{}", r.headline);
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Where the feature actually lives
+// ───────────────────────────────────────────────────────────────────────────
+
+/// `onto_plan` is the home. A plan that did not run the check must SAY it did
+/// not run it, because a missing block and a clean block read the same to a
+/// dashboard.
+#[test]
+fn a_plan_reports_conservativity_or_reports_that_it_did_not_look() {
+ use open_ontologies::plan::Planner;
+ use open_ontologies::state::StateDb;
+
+ let dir = scratch("plan");
+ let db = StateDb::open(&dir.join("state.db")).expect("state db");
+ let graph = loaded(BASE);
+ let planner = Planner::new(db, graph);
+
+ let proposal = format!(
+ "{BASE}\n@prefix ex2: <http://ex.org/> . \
+ @prefix rdfs2: <http://www.w3.org/2000/01/rdf-schema#> . \
+ ex2:hasParent rdfs2:domain ex2:Person ."
+ );
+
+ let silent: serde_json::Value =
+ serde_json::from_str(&planner.plan(&proposal).unwrap()).unwrap();
+ assert_eq!(silent["conservativity"]["ran"], false);
+ assert!(
+ silent["conservativity"]["skipped"].as_str().unwrap().contains("not requested"),
+ "a plan that did not look must say so: {}",
+ silent["conservativity"]
+ );
+
+ let checked: serde_json::Value = serde_json::from_str(
+ &planner
+ .plan_checked(
+ &proposal,
+ Some(cx::ConservativityOptions {
+ mode: cx::ExtensionMode::Replacement,
+ out: scratch("plan-cx"),
+ ..Default::default()
+ }),
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(checked["conservativity"]["ran"], true);
+ assert_eq!(
+ checked["conservativity"]["conservativity_verdict"],
+ cx::NOT_CONSERVATIVE,
+ "{}",
+ checked["conservativity"]["headline"]
+ );
+ // The shape diff sees nothing wrong, which is the entire reason the
+ // semantic block had to be added.
+ assert_eq!(checked["risk_score"], "low");
+ assert_eq!(checked["removed_classes"].as_array().unwrap().len(), 0);
+ assert_eq!(checked["added_classes"].as_array().unwrap().len(), 0);
+}
diff --git a/tests/module_extract_test.rs b/tests/module_extract_test.rs
new file mode 100644
index 00000000..0e2a7521
--- /dev/null
+++ b/tests/module_extract_test.rs
@@ -0,0 +1,421 @@
+//! A module is not a smaller slice, it is a slice with a theorem.
+//!
+//! The tests that matter here are the ones that would pass for a heuristic too,
+//! and the one that would not. `a_naive_signature_slice_drops_an_entailment_the
+//! _module_keeps` is the second kind: it builds the slice a sensible retriever
+//! produces, shows it is BIGGER than the module, and shows it has lost a
+//! conclusion the module still reaches. Without that test, "we extract modules"
+//! and "we extract neighbourhoods and call them modules" look identical from
+//! the outside.
+
+use open_ontologies::closure_diff::DiffOptions;
+use open_ontologies::graph::GraphStore;
+use open_ontologies::module_extract as me;
+use open_ontologies::reason::{InferenceTarget, Reasoner};
+use std::collections::HashSet;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+type Triple = (String, String, String);
+
+fn loaded(ttl: &str) -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_turtle(ttl, None)
+ .unwrap_or_else(|e| panic!("fixture must parse: {e}\n{ttl}"));
+ g
+}
+
+/// Everything the profile derives from `ttl`, as N-Triples-spelled triples.
+fn closure_of(ttl: &str, profile: &str) -> HashSet<Triple> {
+ let g = loaded(ttl);
+ Reasoner::run_full(&g, profile, true, InferenceTarget::DefaultGraph, None)
+ .expect("the reasoner must run");
+ g.all_triples().expect("triples").into_iter().collect()
+}
+
+fn t(s: &str, p: &str, o: &str) -> Triple {
+ (format!("<{s}>"), format!("<{p}>"), format!("<{o}>"))
+}
+
+const EX: &str = "http://ex.org/";
+const SUBCLASS: &str = "http://www.w3.org/2000/01/rdf-schema#subClassOf";
+
+fn ex(local: &str) -> String {
+ format!("{EX}{local}")
+}
+
+/// The namespace `benchmark/reference/pizza-reference.owl` actually declares.
+/// Its `xml:base` is the raw.githubusercontent URL the file was fetched from,
+/// not the co-ode.org IRI the ontology is usually cited by, and a signature
+/// spelled the usual way selects nothing at all.
+const PIZZA: &str =
+ "https://raw.githubusercontent.com/owlcs/pizza-ontology/refs/heads/master/pizza.owl#";
+
+fn pizza(local: &str) -> String {
+ format!("{PIZZA}{local}")
+}
+
+/// A four-link chain with two dead branches hanging off its top, one instance
+/// and one unrelated ABox edge. Every number below is hand-computed from it.
+const ONTOLOGY: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://ex.org/> .
+
+ex:Cat rdfs:subClassOf ex:Mammal .
+ex:Mammal rdfs:subClassOf ex:Animal .
+ex:Animal rdfs:subClassOf ex:LivingThing .
+ex:Plant rdfs:subClassOf ex:LivingThing .
+ex:Fungus rdfs:subClassOf ex:LivingThing .
+ex:tom a ex:Cat .
+ex:tom ex:eats ex:fish .
+"#;
+
+/// `{Cat, LivingThing}`.
+fn signature() -> Vec<String> {
+ vec![ex("Cat"), ex("LivingThing")]
+}
+
+fn extract(locality: me::Locality) -> me::ModuleReport {
+ me::extract_module(
+ &loaded(ONTOLOGY),
+ &me::ModuleOptions { signature: signature(), locality, ..Default::default() },
+ )
+ .expect("extraction must succeed")
+}
+
+/// The slice a sensible retriever produces: every triple that MENTIONS a term
+/// of the signature. It is the honest baseline, not a straw man, and it is the
+/// shape `onto_segment_retrieve` produces at one hop.
+fn naive_signature_slice() -> String {
+ let g = loaded(ONTOLOGY);
+ let wanted: HashSet<String> = signature().into_iter().map(|s| format!("<{s}>")).collect();
+ g.all_triples()
+ .unwrap()
+ .into_iter()
+ .filter(|(s, _, o)| wanted.contains(s) || wanted.contains(o))
+ .map(|(s, p, o)| format!("{s} {p} {o} .\n"))
+ .collect()
+}
+
+fn scratch(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("oo-module-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// The module is strictly smaller and still says everything
+// ───────────────────────────────────────────────────────────────────────────
+
+/// Hand-computed. Over `{Cat, LivingThing}`:
+///
+/// - the `⊥` pass keeps the three chain links (each has a non-`⊥` left-hand
+/// side once the previous link has grown the signature), `tom a Cat` and
+/// `tom eats fish`, and drops the `Plant` and `Fungus` branches, whose
+/// left-hand sides are external and therefore `⊥`;
+/// - the `⊤` pass over that set keeps `Animal ⊑ LivingThing` on the first
+/// sweep, then `Mammal ⊑ Animal`, then `Cat ⊑ Mammal` as the signature grows,
+/// keeps `tom a Cat` because `Cat` is in `Σ`, and drops `tom eats fish`
+/// because `eats` is external and the universal property makes the assertion
+/// a tautology;
+/// - a second `⊥⊤` round changes nothing, so the fixpoint is 4 of 7.
+#[test]
+fn the_star_module_is_strictly_smaller_than_the_ontology() {
+ let r = extract(me::Locality::Star);
+ assert_eq!(r.ontology_axioms, 7, "the fixture is seven axioms");
+ assert_eq!(r.module_axioms, 4, "hand-computed ⊥⊤* module:\n{}", r.module_ttl);
+ assert!(r.module_axioms < r.ontology_axioms);
+ assert_eq!(r.rounds, 2, "one round to shrink, one to prove it stopped");
+ assert!(!r.module_ttl.contains("Plant"), "{}", r.module_ttl);
+ assert!(!r.module_ttl.contains("Fungus"), "{}", r.module_ttl);
+ assert!(!r.module_ttl.contains("eats"), "{}", r.module_ttl);
+}
+
+/// The point of the smaller set: the conclusion over the signature survives it.
+#[test]
+fn the_module_still_entails_the_goal_over_the_signature() {
+ let r = extract(me::Locality::Star);
+ let goal = t(&ex("Cat"), SUBCLASS, &ex("LivingThing"));
+ assert!(
+ closure_of(ONTOLOGY, "owl-rl").contains(&goal),
+ "the fixture must entail the goal, or the test proves nothing"
+ );
+ assert!(
+ closure_of(&r.module_ttl, "owl-rl").contains(&goal),
+ "the module lost a conclusion over its own signature:\n{}",
+ r.module_ttl
+ );
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// The negative: a heuristic slice loses what the module keeps
+// ───────────────────────────────────────────────────────────────────────────
+
+/// This is the test that separates a module from a neighbourhood.
+///
+/// The naive slice keeps every triple MENTIONING a signature term. That is five
+/// triples against the module's four, so it is not losing because it is smaller
+/// or because it was built carelessly. It loses because `Mammal ⊑ Animal`
+/// mentions neither `Cat` nor `LivingThing`, and the chain runs through it. The
+/// module keeps it for exactly the reason the locality test exists: after
+/// `Cat ⊑ Mammal` is taken, `Mammal` is in the working signature and the next
+/// link stops being local.
+#[test]
+fn a_naive_signature_slice_drops_an_entailment_the_module_keeps() {
+ let naive = naive_signature_slice();
+ let module = extract(me::Locality::Star);
+ let goal = t(&ex("Cat"), SUBCLASS, &ex("LivingThing"));
+
+ let naive_triples = naive.lines().count();
+ assert_eq!(naive_triples, 5, "the naive slice is:\n{naive}");
+ assert!(
+ naive_triples > module.module_triples,
+ "the naive slice must be BIGGER than the module, or the comparison is about size: \
+ naive {naive_triples}, module {}",
+ module.module_triples
+ );
+
+ assert!(
+ !closure_of(&naive, "owl-rl").contains(&goal),
+ "the naive slice was supposed to lose the goal; if it stopped losing it the fixture \
+ changed and this test no longer demonstrates anything:\n{naive}"
+ );
+ assert!(
+ closure_of(&module.module_ttl, "owl-rl").contains(&goal),
+ "the module must keep it:\n{}",
+ module.module_ttl
+ );
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Exercising the guarantee rather than asserting it
+// ───────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn the_closure_diff_finds_nothing_lost_over_the_signature() {
+ let store = loaded(ONTOLOGY);
+ let r = extract(me::Locality::Star);
+ let opts = DiffOptions { out: scratch("verify"), ..Default::default() };
+ let v = me::verify_module(&store, &r, &opts, 200_000)
+ .expect("verification must run");
+ assert_eq!(
+ v.lost_over_signature_total, 0,
+ "a locality module may not lose a conclusion over its own signature closure:\n{:#?}",
+ v.lost_over_signature
+ );
+ assert_eq!(v.not_examined, 0, "the whole difference was examined");
+ assert_eq!(v.engine_soundness_violations, 0);
+ assert!(
+ v.lost_outside_signature_total > 0,
+ "the module must lose something OUTSIDE the signature, or it is the whole ontology and \
+ the clean result is vacuous"
+ );
+}
+
+/// The same thing at a size nobody hand-computes, on a file this repository
+/// ships. A clean result over seven triples is cheap; a clean result over the
+/// pizza ontology is the one worth reporting.
+#[test]
+fn the_guarantee_holds_on_the_pizza_ontology() {
+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("benchmark")
+ .join("reference")
+ .join("pizza-reference.owl");
+ let store = Arc::new(GraphStore::new());
+ store.load_file(path.to_str().unwrap()).expect("the shipped pizza ontology must load");
+
+ let signature = vec![pizza("Veneziana"), pizza("Food")];
+ let r = me::extract_module(
+ &store,
+ &me::ModuleOptions {
+ signature: signature.clone(),
+ locality: me::Locality::Star,
+ ..Default::default()
+ },
+ )
+ .expect("extraction must succeed");
+
+ assert!(r.signature_not_in_ontology.is_empty(), "{:?}", r.signature_not_in_ontology);
+ assert!(
+ r.module_triples < r.ontology_triples,
+ "the module must be a proper subset: {} of {}",
+ r.module_triples,
+ r.ontology_triples
+ );
+ // Whatever it could not classify is IN the module, and the report says how
+ // much. Printed rather than asserted to a number, which would pin a
+ // property of the file rather than of this code.
+ eprintln!(
+ "pizza: {} of {} axioms, {} of {} triples, {} unclassified, kinds {:?}",
+ r.module_axioms,
+ r.ontology_axioms,
+ r.module_triples,
+ r.ontology_triples,
+ r.unclassified_total,
+ r.axioms_by_kind
+ );
+
+ let opts = DiffOptions { out: scratch("pizza"), ..Default::default() };
+ let v = me::verify_module(&store, &r, &opts, 200_000)
+ .expect("verification must run");
+ assert_eq!(
+ v.lost_over_signature_total, 0,
+ "{}\nfirst rows: {:#?}",
+ v.headline,
+ v.lost_over_signature.iter().take(5).collect::<Vec<_>>()
+ );
+ assert_eq!(v.not_examined, 0, "the whole difference was examined: {}", v.headline);
+ // The annotation partition has to be doing real work here, or a future
+ // change that widened it into a blanket filter would go unnoticed: it
+ // would make every module verify clean.
+ assert!(
+ v.lost_over_signature_annotation_only > 0,
+ "pizza carries multilingual rdfs:labels the logical module drops, and they must be \
+ COUNTED rather than silently filtered: {}",
+ v.headline
+ );
+ eprintln!("pizza verification: {}", v.headline);
+ // The blind spot is real on this file, because the module carries the
+ // store's own blank node labels and the diff skolemises the source. It is
+ // COUNTED, so the coverage of the clean result above can be read rather
+ // than assumed.
+ assert!(
+ v.not_decided_blank_node_bearing > 0,
+ "pizza is full of blank-node restrictions, so the blind spot must be non-zero and \
+ reported: {}",
+ v.headline
+ );
+ assert!(
+ v.not_decided_blank_node_bearing <= v.lost_outside_signature_total,
+ "the blind spot is a subset of the outside-signature count, not a fourth bucket"
+ );
+
+ // The conclusion the decision-0007 record names as the one a 99%-coverage
+ // slice silently loses. It is over the module's signature closure, so the
+ // module may not lose it.
+ let goal = t(&pizza("Veneziana"), SUBCLASS, &pizza("Food"));
+ assert!(
+ closure_of(&r.module_ttl, "owl-rl").contains(&goal),
+ "the module must still put Veneziana under Food"
+ );
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Conservative where it cannot classify
+// ───────────────────────────────────────────────────────────────────────────
+
+/// An axiom type this file does not classify must be INCLUDED, never dropped,
+/// and must be named in the report so the module's size can be read honestly.
+///
+/// `owl:hasSelf` is classified, so the unreadable case has to be a shape that
+/// genuinely is not: a blank-node structure whose type is an OWL term with no
+/// axiom reading here. Dropping it would be the silent failure, because the
+/// module still parses and the count still looks small.
+#[test]
+fn an_unclassifiable_axiom_is_included_and_named() {
+ let ttl = format!(
+ "{ONTOLOGY}
+ @prefix owl2: <http://www.w3.org/2002/07/owl#> .
+ [] a owl2:SomeFutureAxiomKind ; owl2:members ( ex:Cat ex:Plant ) .
+ ex:Cat owl2:someUnknownPredicate ex:Fungus ."
+ );
+ let r = me::extract_module(
+ &loaded(&ttl),
+ &me::ModuleOptions {
+ signature: signature(),
+ locality: me::Locality::Star,
+ ..Default::default()
+ },
+ )
+ .expect("extraction must succeed");
+
+ assert_eq!(
+ r.unclassified_total, 2,
+ "both unreadable shapes must survive into the module, and be counted: {:#?}",
+ r.unclassified_axioms
+ );
+ assert_eq!(r.included_conservatively.get("unclassified"), Some(&2));
+ assert!(
+ r.module_ttl.contains("SomeFutureAxiomKind"),
+ "a blank-node structure of an unknown OWL type must be kept:\n{}",
+ r.module_ttl
+ );
+ assert!(
+ r.module_ttl.contains("someUnknownPredicate"),
+ "an unrecognised owl: predicate must NOT be read as a droppable property assertion:\n{}",
+ r.module_ttl
+ );
+ for u in &r.unclassified_axioms {
+ assert!(!u.why.is_empty(), "every conservative inclusion says why: {u:?}");
+ }
+}
+
+/// The dual of the test above, and the one that stops the conservative rule
+/// from being vacuous: an unrecognised predicate in a USER namespace IS read as
+/// a property assertion, and is `⊤`-local, so it does not survive. If every
+/// unknown predicate were kept, the module would be the ontology and the
+/// guarantee would be free.
+#[test]
+fn an_unrecognised_user_predicate_is_a_property_assertion_and_can_be_dropped() {
+ let r = extract(me::Locality::Star);
+ assert!(!r.module_ttl.contains("eats"), "{}", r.module_ttl);
+ assert_eq!(r.axioms_by_kind.get("unclassified"), None);
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// The report may not overstate what stands behind it
+// ───────────────────────────────────────────────────────────────────────────
+
+/// The house rule from decision 0002: a word with a machine-checked theorem
+/// behind it and a word without one may never render the same. Locality has no
+/// Lean theorem in this repository, so the serialised report must not name one.
+#[test]
+fn the_module_report_never_names_a_lean_theorem() {
+ let r = extract(me::Locality::Star);
+ let json = serde_json::to_string(&r).unwrap();
+ for forbidden in ["OOCert.", "OwlLean.", "Fol.", "machine-checked theorem"] {
+ assert!(
+ !json.contains(forbidden),
+ "the module report claimed {forbidden:?}, and no theorem in lean/ is about syntactic \
+ locality"
+ );
+ }
+ assert!(json.contains("CITED, not checked"), "the absence has to be stated, not inferred");
+ assert!(json.contains("JAIR 31"), "the theorem that IS relied on must be named");
+}
+
+#[test]
+fn every_axiom_kind_the_extractor_produces_is_declared_in_one_of_the_two_lists() {
+ // A kind that is in neither list is a guarantee nobody wrote down. The
+ // report's `axioms_by_kind` is the measurement; the two constants are the
+ // claim.
+ let ttl = format!(
+ "{ONTOLOGY}
+ @prefix owl2: <http://www.w3.org/2002/07/owl#> .
+ ex:hasParent a owl2:TransitiveProperty ; rdfs:domain ex:Cat ; rdfs:range ex:Cat .
+ ex:hasChild owl2:inverseOf ex:hasParent .
+ ex:a owl2:sameAs ex:b .
+ ex:Cat owl2:disjointWith ex:Plant .
+ [] a owl2:SomeFutureAxiomKind ; owl2:members ( ex:Cat ) ."
+ );
+ let r = me::extract_module(
+ &loaded(&ttl),
+ &me::ModuleOptions {
+ signature: vec![ex("Cat"), ex("LivingThing"), ex("hasParent"), ex("a")],
+ locality: me::Locality::Bottom,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ assert!(!r.axioms_by_kind.is_empty());
+ for kind in r.axioms_by_kind.keys() {
+ assert!(
+ me::CLASSIFIED_KINDS.contains(&kind.as_str())
+ || me::ALWAYS_INCLUDED_KINDS.contains(&kind.as_str()),
+ "{kind:?} is produced by the extractor and declared in neither CLASSIFIED_KINDS nor \
+ ALWAYS_INCLUDED_KINDS, so the tool description does not cover it"
+ );
+ }
+}
diff --git a/tests/plan_mcp_test.rs b/tests/plan_mcp_test.rs
index e0cfbd41..954ec78c 100644
--- a/tests/plan_mcp_test.rs
+++ b/tests/plan_mcp_test.rs
@@ -27,6 +27,19 @@ const PROPOSED: &str = r#"
ex:Organizacion a owl:Class .
"#;
+/// Every field of `OntoPlanInput` except the turtle. Spelled once so adding an
+/// option to the tool does not mean editing every call site, and spelled
+/// EXPLICITLY rather than through `Default`, so a new option has to be given a
+/// value here and cannot arrive switched on by accident.
+fn plan_defaults() -> OntoPlanInput {
+ OntoPlanInput {
+ new_turtle: String::new(),
+ check_conservativity: None,
+ conservativity_profile: None,
+ conservativity_out_dir: None,
+ }
+}
+
fn server() -> (tempfile::TempDir, OpenOntologiesServer, Arc<GraphStore>) {
let tmp = tempfile::tempdir().unwrap();
let db = StateDb::open(&tmp.path().join("state.db")).unwrap();
@@ -44,6 +57,7 @@ async fn onto_apply_sees_the_plan_onto_plan_computed() {
&server
.onto_plan(Parameters(OntoPlanInput {
new_turtle: PROPOSED.to_string(),
+ ..plan_defaults()
}))
.await,
)
@@ -74,6 +88,7 @@ async fn onto_apply_accepts_an_explicit_plan_id() {
&server
.onto_plan(Parameters(OntoPlanInput {
new_turtle: PROPOSED.to_string(),
+ ..plan_defaults()
}))
.await,
)