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.

Counting-clash rules, assumed-disjointness WARN tier, v1.1.0

FABIOTESS58837bd68bff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index abada283..a499e412 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,31 @@
# Changelog
+## 1.1.0 — 2026-07-27
+
+### Added
+- `claimcheck` module: compiled per-claim ontology-consistency verification.
+ Token-bitset engine (0.3 µs median per claim, 11M claims/s batched), sound
+ two-hop disjointness join with witness extraction, three-valued verdicts
+ (`Rejected` / `Undetermined` / `Consistent`), reasoner-backed residual tier
+ (`ResidualOracle`) with verdict learn-back, closed-world vocabulary checks,
+ and an assumed-disjointness WARN tier for zero-disjointness ontologies.
+ Correctness audited against HermiT: 0 disagreements over 78,884 exhaustive
+ class pairs (13 ontologies) and 793 adversarial structural claims.
+- Offline compile tooling (`benchmark/reasoner/`): `CompileOntology` with six
+ sound disjointness-propagation rules (restriction, functional, union,
+ data-value, counting, dueling-universal idioms), `DisjointnessMatrix`,
+ `ClaimConsistency`, `PairOracle`, `VetDisjointness`, `StripDisjointness`.
+
+### Changed
+- OWL-DL reasoner: satisfiability is now three-valued — resource exhaustion
+ reports `Unknown` instead of unsatisfiability; per-test (10s) and global
+ classification (180s) wall-clock budgets; pairwise blocking; output gains
+ `complete`, `undetermined_classes`, `subsumption_sweep_cut_short`, and
+ `abox.undecided`.
+- RDF loading content-sniffs `.owl` files, so Turtle published under `.owl`
+ parses correctly.
+
+
All notable changes to Open Ontologies are documented here.
## [Unreleased]
diff --git a/Cargo.lock b/Cargo.lock
index 660dcf7f..9fd3586e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2729,7 +2729,7 @@ dependencies = [
[[package]]
name = "open-ontologies"
-version = "1.0.0"
+version = "1.1.0"
dependencies = [
"anyhow",
"arrow 54.3.1",
diff --git a/Cargo.toml b/Cargo.toml
index 1559824e..23474f50 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "open-ontologies"
-version = "1.0.0"
+version = "1.1.0"
edition = "2024"
description = "AI-native ontology engine — standalone MCP server"
license = "MIT"
diff --git a/benchmark/layer3-prototype/holdout_disjointness.py b/benchmark/layer3-prototype/holdout_disjointness.py
new file mode 100644
index 00000000..d1f5974e
--- /dev/null
+++ b/benchmark/layer3-prototype/holdout_disjointness.py
@@ -0,0 +1,162 @@
+"""Holdout evaluation of the assumed-disjointness WARN tier.
+
+The dominant real-world gap: most large ontologies declare NO disjointness, so
+the entailed contradiction tier is empty and verification value collapses onto
+vocabulary checks. The WARN tier reconstructs a candidate surface:
+
+ proposer suggests class pairs that "should" be disjoint
+ vetter (VetDisjointness + HermiT) filters to admissible assumptions
+ WARN tier surfaces conflicts with those assumptions, never rejects on them
+
+This harness measures how good that reconstruction is, honestly:
+
+ 1. strip ALL disjointness from an ontology that has it
+ 2. propose pairs (built-in: sibling heuristic — classes sharing a direct
+ parent; or --proposals file from an LLM, the MCP-native slot)
+ 3. vet against the STRIPPED ontology
+ 4. score the admissible set's two-hop closure against the ORIGINAL
+ ontology's exhaustive incompatibility matrix:
+ recall fraction of truly-incompatible pairs the WARN tier covers
+ precision fraction of WARN-tier flags that are truly incompatible
+
+Precision is the number that matters: a WARN tier that cries wolf is worse
+than none.
+
+Usage: holdout_disjointness.py <ontology.owl> <matrix.csv> [--proposals f.json]
+"""
+from __future__ import annotations
+
+import csv
+import itertools
+import json
+import subprocess
+import sys
+from collections import defaultdict
+from pathlib import Path
+
+REASONER_DIR = Path(__file__).resolve().parent.parent / "reasoner"
+JAVA = "/opt/homebrew/opt/openjdk@17/bin/java"
+CP = f".:{REASONER_DIR}/lib/*"
+
+
+def run_tool(cls: str, *args: str, stdin: str | None = None, timeout: int = 900):
+ p = subprocess.run([JAVA, "-cp", CP, cls, *args], cwd=REASONER_DIR,
+ input=stdin, capture_output=True, text=True, timeout=timeout)
+ return [json.loads(l) for l in p.stdout.splitlines() if l.startswith("{")]
+
+
+def direct_parents(supers: dict[str, set[str]]) -> dict[str, set[str]]:
+ """Direct (minimal) parents from the reflexive-transitive closure."""
+ out: dict[str, set[str]] = {}
+ for c, sups in supers.items():
+ strict = {s for s in sups if s != c}
+ out[c] = {p for p in strict
+ if not any(p in supers.get(q, set()) and q != p for q in strict - {p})}
+ return out
+
+
+def sibling_proposals(supers: dict[str, set[str]]) -> list[tuple[str, str]]:
+ """Classes sharing a direct parent, excluding comparable pairs.
+
+ The 'strong disjointness assumption' from the ontology-learning
+ literature: siblings are usually intended to be disjoint even when nobody
+ wrote the axiom.
+ """
+ dp = direct_parents(supers)
+ by_parent: dict[str, list[str]] = defaultdict(list)
+ for c, parents in dp.items():
+ for p in parents:
+ by_parent[p].append(c)
+ seen, out = set(), []
+ for group in by_parent.values():
+ for a, b in itertools.combinations(sorted(group), 2):
+ if b in supers.get(a, set()) or a in supers.get(b, set()):
+ continue # comparable — vetting would reject anyway
+ key = (a, b)
+ if key not in seen:
+ seen.add(key)
+ out.append(key)
+ return out
+
+
+def main() -> None:
+ ont = Path(sys.argv[1]).resolve()
+ matrix = Path(sys.argv[2]).resolve()
+ proposals_file = None
+ if "--proposals" in sys.argv:
+ proposals_file = sys.argv[sys.argv.index("--proposals") + 1]
+
+ stripped = Path("/tmp") / (ont.stem + "_stripped.owl")
+ removed = run_tool("StripDisjointness", str(ont), str(stripped))[0]["removed"]
+ print(f"stripped {removed} disjointness axioms -> {stripped.name}")
+
+ compiled = run_tool("CompileOntology", str(stripped), "/tmp/holdout_compiled.json")[0]
+ print(f"stripped compile: {compiled}")
+ data = json.load(open("/tmp/holdout_compiled.json"))
+ supers: dict[str, set[str]] = {}
+ for sub, sup in data["subsumptions"]:
+ supers.setdefault(sub, set()).add(sup)
+
+ if proposals_file:
+ proposals = [tuple(p) for p in json.load(open(proposals_file))]
+ source = f"LLM proposals ({proposals_file})"
+ else:
+ proposals = sibling_proposals(supers)
+ source = "sibling heuristic"
+ print(f"proposer [{source}]: {len(proposals)} candidate pairs")
+
+ stdin = "\n".join(f"{a}\t{b}" for a, b in proposals)
+ verdicts = run_tool("VetDisjointness", str(stripped), stdin=stdin)
+ by_verdict: dict[str, int] = defaultdict(int)
+ admissible = []
+ for v in verdicts:
+ by_verdict[v["verdict"]] += 1
+ if v["verdict"] == "admissible":
+ admissible.append((v["a"], v["b"]))
+ print(f"vetting: {dict(by_verdict)}")
+
+ # WARN-tier closure: two-hop over the stripped hierarchy + admissible set.
+ assumed = set()
+ for a, b in admissible:
+ assumed.add((a, b))
+ assumed.add((b, a))
+
+ def warn(a: str, b: str) -> bool:
+ return any((x, y) in assumed
+ for x in supers.get(a, {a}) for y in supers.get(b, {b}))
+
+ truth = set()
+ with open(matrix) as f:
+ rd = csv.reader(f)
+ next(rd, None)
+ for a, b in rd:
+ truth.add((a, b))
+
+ classes = sorted(supers)
+ tp = fp = fn = 0
+ fp_examples = []
+ for a, b in itertools.combinations(classes, 2):
+ w = warn(a, b)
+ t = (a, b) in truth
+ if w and t:
+ tp += 1
+ elif w and not t:
+ fp += 1
+ if len(fp_examples) < 5:
+ fp_examples.append((a.rsplit("#", 1)[-1], b.rsplit("#", 1)[-1]))
+ elif t and not w:
+ fn += 1
+
+ print(f"\n=== WARN-tier reconstruction vs original ground truth ===")
+ print(f" truly incompatible pairs : {tp + fn:,}")
+ print(f" covered by WARN tier : {tp:,} (recall {100*tp/(tp+fn):.1f}%)"
+ if tp + fn else " (no ground truth)")
+ if tp + fp:
+ print(f" WARN flags raised : {tp + fp:,} (precision {100*tp/(tp+fp):.1f}%)")
+ print(f" false warnings : {fp:,}")
+ for e in fp_examples:
+ print(f" false warn: {e[0]} + {e[1]}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmark/reasoner/CompileOntology.java b/benchmark/reasoner/CompileOntology.java
index d5265bda..2fa6587a 100644
--- a/benchmark/reasoner/CompileOntology.java
+++ b/benchmark/reasoner/CompileOntology.java
@@ -129,6 +129,11 @@ public class CompileOntology {
Map<String, List<String[]>> ex = new HashMap<>(); // class -> [prop, filler...]
Map<String, List<String[]>> all = new HashMap<>(); // class -> [prop, filler...]
Map<String, List<String[]>> unions = new HashMap<>(); // class -> union operands
+ // Cardinality records. minRec: [prop, n, filler] — at least n R-successors
+ // in filler ("*" = unqualified/Thing). maxRec: [prop, m, filler] — at
+ // most m R-successors in filler.
+ Map<String, List<String[]>> minRec = new HashMap<>();
+ Map<String, List<String[]>> maxRec = new HashMap<>();
Map<String, List<String[]>> hv = new HashMap<>(); // class -> [dataProp, datatype, lexical]
Map<String, Set<String>> dmax1 = new HashMap<>(); // class -> dataProps with card <= 1
for (OWLAxiom ax : ont.getAxioms()) {
@@ -153,16 +158,70 @@ public class CompileOntology {
if (e instanceof OWLObjectSomeValuesFrom sv
&& !sv.getProperty().isAnonymous()
&& !sv.getFiller().isAnonymous()) {
- ex.computeIfAbsent(named.getIRI().toString(), x -> new ArrayList<>())
- .add(new String[]{sv.getProperty().getNamedProperty().getIRI().toString(),
- sv.getFiller().asOWLClass().getIRI().toString()});
+ String cn = named.getIRI().toString();
+ String pr = sv.getProperty().getNamedProperty().getIRI().toString();
+ String fl = sv.getFiller().asOWLClass().getIRI().toString();
+ ex.computeIfAbsent(cn, x -> new ArrayList<>()).add(new String[]{pr, fl});
+ minRec.computeIfAbsent(cn, x -> new ArrayList<>())
+ .add(new String[]{pr, "1", fl});
} else if (e instanceof OWLObjectMinCardinality mc
&& mc.getCardinality() >= 1
- && !mc.getProperty().isAnonymous()
- && !mc.getFiller().isAnonymous()) {
- ex.computeIfAbsent(named.getIRI().toString(), x -> new ArrayList<>())
- .add(new String[]{mc.getProperty().getNamedProperty().getIRI().toString(),
- mc.getFiller().asOWLClass().getIRI().toString()});
+ && !mc.getProperty().isAnonymous()) {
+ String cn = named.getIRI().toString();
+ String pr = mc.getProperty().getNamedProperty().getIRI().toString();
+ String fl = mc.getFiller().isAnonymous() ? "*"
+ : mc.getFiller().asOWLClass().getIRI().toString();
+ if (!mc.getFiller().isAnonymous())
+ ex.computeIfAbsent(cn, x -> new ArrayList<>()).add(new String[]{pr, fl});
+ if (fl.equals("*") || !mc.getFiller().isAnonymous())
+ minRec.computeIfAbsent(cn, x -> new ArrayList<>())
+ .add(new String[]{pr, String.valueOf(mc.getCardinality()), fl});
+ } else if (e instanceof OWLObjectExactCardinality ec
+ && !ec.getProperty().isAnonymous()
+ && (ec.getFiller().isAnonymous() ? ec.getFiller().isOWLThing() || true : true)) {
+ // Exact n = (min n) ⊓ (max n). Record both sides when the
+ // filler is named or unqualified; skip complex fillers.
+ if (ec.getFiller().isAnonymous() && !ec.getFiller().isOWLThing()) {
+ // complex filler — outside the envelope
+ } else {
+ String cn = named.getIRI().toString();
+ String pr = ec.getProperty().getNamedProperty().getIRI().toString();
+ String fl = ec.getFiller().isOWLThing() ? "*"
+ : ec.getFiller().asOWLClass().getIRI().toString();
+ String n = String.valueOf(ec.getCardinality());
+ if (ec.getCardinality() >= 1) {
+ minRec.computeIfAbsent(cn, x -> new ArrayList<>())
+ .add(new String[]{pr, n, fl});
+ if (!fl.equals("*"))
+ ex.computeIfAbsent(cn, x -> new ArrayList<>())
+ .add(new String[]{pr, fl});
+ }
+ maxRec.computeIfAbsent(cn, x -> new ArrayList<>())
+ .add(new String[]{pr, n, fl});
+ }
+ } else if (e instanceof OWLObjectMaxCardinality xc
+ && !xc.getProperty().isAnonymous()
+ && (!xc.getFiller().isAnonymous() || xc.getFiller().isOWLThing())) {
+ String cn = named.getIRI().toString();
+ String pr = xc.getProperty().getNamedProperty().getIRI().toString();
+ String fl = xc.getFiller().isOWLThing() ? "*"
+ : xc.getFiller().asOWLClass().getIRI().toString();
+ maxRec.computeIfAbsent(cn, x -> new ArrayList<>())
+ .add(new String[]{pr, String.valueOf(xc.getCardinality()), fl});
+ } else if (e instanceof OWLDataExactCardinality dxc
+ && dxc.getCardinality() == 1
+ && dxc.getProperty() instanceof OWLDataProperty dxp
+ && dxc.getFiller() instanceof OWLDataOneOf oneOf
+ && oneOf.getValues().size() == 1) {
+ // ExactCardinality(1, p, DataOneOf(v)) pins exactly one
+ // p-value equal to v — a hasValue in cardinality syntax.
+ OWLLiteral lit = oneOf.getValues().iterator().next();
+ hv.computeIfAbsent(named.getIRI().toString(), x -> new ArrayList<>())
+ .add(new String[]{dxp.getIRI().toString(),
+ lit.getDatatype().getIRI().toString(),
+ lit.getLiteral()});
+ dmax1.computeIfAbsent(named.getIRI().toString(), x -> new HashSet<>())
+ .add(dxp.getIRI().toString());
} else if (e instanceof OWLObjectUnionOf uo2) {
// B ⊑ (D1 ⊔ … ⊔ Dn). Only usable when EVERY operand is
// named: deriving from a subset of the operands would
@@ -223,6 +282,8 @@ public class CompileOntology {
Map<String, List<String[]>> unionInh = new HashMap<>();
Map<String, List<String[]>> hvInh = new HashMap<>();
Map<String, Set<String>> dmax1Inh = new HashMap<>();
+ Map<String, List<String[]>> minInh = new HashMap<>();
+ Map<String, List<String[]>> maxInh = new HashMap<>();
for (String c : anc.keySet()) {
for (String a : anc.get(c)) {
if (ex.containsKey(a))
@@ -235,6 +296,10 @@ public class CompileOntology {
hvInh.computeIfAbsent(c, x -> new ArrayList<>()).addAll(hv.get(a));
if (dmax1.containsKey(a))
dmax1Inh.computeIfAbsent(c, x -> new HashSet<>()).addAll(dmax1.get(a));
+ if (minRec.containsKey(a))
+ minInh.computeIfAbsent(c, x -> new ArrayList<>()).addAll(minRec.get(a));
+ if (maxRec.containsKey(a))
+ maxInh.computeIfAbsent(c, x -> new ArrayList<>()).addAll(maxRec.get(a));
}
}
@@ -304,6 +369,35 @@ public class CompileOntology {
}
}
+ // R4: counting clash. A ⊑ ≤m R.C, B ⊑ ≥n R.D with n > m and D ⊑* C
+ // (or C unqualified): the A⊓B individual would need at least n
+ // R-successors inside a region capped at m. Functional object
+ // properties act as an unqualified ≤1.
+ List<String> maxClasses = new ArrayList<>(maxInh.keySet());
+ List<String> minClasses = new ArrayList<>(minInh.keySet());
+ for (String a : maxClasses) {
+ for (String[] mx : maxInh.get(a)) {
+ int m2 = Integer.parseInt(mx[1]);
+ for (String b : minClasses) {
+ if (a.equals(b) || disjStar.test(a, b)) continue;
+ for (String[] mn : minInh.get(b)) {
+ if (!mn[0].equals(mx[0])) continue;
+ int n2 = Integer.parseInt(mn[1]);
+ if (n2 <= m2) continue;
+ boolean fillerOk = mx[2].equals("*")
+ || (!mn[2].equals("*")
+ && anc.getOrDefault(mn[2], java.util.Collections.singleton(mn[2]))
+ .contains(mx[2]));
+ if (fillerOk) {
+ disjSet.add(a + "|" + b); disjSet.add(b + "|" + a);
+ derived.add("[" + q(a) + "," + q(b) + "]");
+ break;
+ }
+ }
+ }
+ }
+ }
+
int rounds = 0;
boolean changed = true;
while (changed && rounds++ < 20) {
@@ -343,6 +437,39 @@ public class CompileOntology {
}
}
}
+ // R5: A ⊑ ∀R.(C…), B ⊑ ∀R.(D…) with every Ci disjoint from every
+ // Dj, and A or B (via ancestors) forces at least one R-successor.
+ // That successor would have to be in both fillers, which are
+ // incompatible. Without the ≥1, an individual with no R-successors
+ // satisfies both universals, so no derivation.
+ for (String a : allInh.keySet()) {
+ for (String[] ra : allInh.get(a)) {
+ for (String b : allInh.keySet()) {
+ if (a.equals(b) || disjStar.test(a, b)) continue;
+ boolean forced = false;
+ for (String[] mn : minInh.getOrDefault(a, java.util.Collections.emptyList()))
+ if (mn[0].equals(ra[0])) { forced = true; break; }
+ if (!forced)
+ for (String[] mn : minInh.getOrDefault(b, java.util.Collections.emptyList()))
+ if (mn[0].equals(ra[0])) { forced = true; break; }
+ if (!forced) continue;
+ for (String[] rb : allInh.get(b)) {
+ if (!rb[0].equals(ra[0])) continue;
+ boolean allDisj = true;
+ outer5:
+ for (int i = 1; i < ra.length; i++)
+ for (int j = 1; j < rb.length; j++)
+ if (!disjStar.test(ra[i], rb[j])) { allDisj = false; break outer5; }
+ if (allDisj) {
+ disjSet.add(a + "|" + b); disjSet.add(b + "|" + a);
+ derived.add("[" + q(a) + "," + q(b) + "]");
+ changed = true;
+ break;
+ }
+ }
+ }
+ }
+ }
// RU: B is subsumed by a union of named classes, and A is
// disjoint from EVERY operand ⟹ disj(A, B). An A⊓B individual
// must fall in some operand, each of which excludes A. Runs
diff --git a/benchmark/reasoner/StripDisjointness.java b/benchmark/reasoner/StripDisjointness.java
new file mode 100644
index 00000000..8b03bc03
--- /dev/null
+++ b/benchmark/reasoner/StripDisjointness.java
@@ -0,0 +1,38 @@
+/*
+ * Remove every disjointness axiom from an ontology.
+ *
+ * Produces the held-out variant for evaluating assumed-disjointness recovery:
+ * strip the axioms, let a proposer + vetter reconstruct a candidate surface,
+ * then score it against the ORIGINAL ontology's exhaustive incompatibility
+ * matrix. Also mirrors the dominant real-world case, since most large
+ * ontologies declare no disjointness at all.
+ *
+ * Usage: java StripDisjointness <in.owl> <out.owl>
+ */
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.semanticweb.owlapi.apibinding.OWLManager;
+import org.semanticweb.owlapi.formats.FunctionalSyntaxDocumentFormat;
+import org.semanticweb.owlapi.model.*;
+
+public class StripDisjointness {
+ public static void main(String[] args) throws Exception {
+ OWLOntologyManager m = OWLManager.createOWLOntologyManager();
+ OWLOntology ont = m.loadOntologyFromOntologyDocument(new File(args[0]));
+
+ List<OWLAxiom> drop = new ArrayList<>();
+ for (OWLAxiom ax : ont.getAxioms()) {
+ if (ax instanceof OWLDisjointClassesAxiom
+ || ax instanceof OWLDisjointUnionAxiom) {
+ drop.add(ax);
+ }
+ }
+ m.removeAxioms(ont, new java.util.HashSet<>(drop));
+ m.saveOntology(ont, new FunctionalSyntaxDocumentFormat(),
+ IRI.create(new File(args[1]).toURI()));
+ System.out.println("{\"removed\":" + drop.size() + "}");
+ }
+}
diff --git a/benchmark/reasoner/VetDisjointness.java b/benchmark/reasoner/VetDisjointness.java
new file mode 100644
index 00000000..b10cc803
--- /dev/null
+++ b/benchmark/reasoner/VetDisjointness.java
@@ -0,0 +1,88 @@
+/*
+ * Vet PROPOSED disjointness axioms against an ontology.
+ *
+ * The MCP-native split for enriching a zero-disjointness ontology: a proposer
+ * (an LLM over MCP, or a structural heuristic) suggests class pairs that
+ * "should" be disjoint; this tool gives each proposal one of three verdicts:
+ *
+ * entailed A ⊓ B is already unsatisfiable — the pair belongs in the
+ * HARD tier; no assumption needed.
+ * inadmissible assuming disjoint(A,B) would break the ontology: A and B
+ * are subsumption-comparable (the subclass would become
+ * empty), or they share a satisfiable named subclass.
+ * admissible consistent to assume. Suitable for the WARN tier ONLY —
+ * admissible means "does not contradict the ontology", never
+ * "true".
+ *
+ * Protocol: stdin lines "<iriA>\t<iriB>", one JSON verdict per line.
+ *
+ * Usage: java VetDisjointness <ontology>
+ */
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.InputStreamReader;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.semanticweb.owlapi.apibinding.OWLManager;
+import org.semanticweb.owlapi.model.*;
+import org.semanticweb.owlapi.reasoner.OWLReasoner;
+import org.semanticweb.HermiT.ReasonerFactory;
+
+public class VetDisjointness {
+ public static void main(String[] args) throws Exception {
+ OWLOntologyManager m = OWLManager.createOWLOntologyManager();
+ OWLOntology ont = m.loadOntologyFromOntologyDocument(new File(args[0]));
+ OWLDataFactory df = m.getOWLDataFactory();
+ OWLReasoner r = new ReasonerFactory().createReasoner(ont);
+ r.isConsistent();
+
+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ String line;
+ while ((line = in.readLine()) != null) {
+ line = line.trim();
+ if (line.isEmpty()) continue;
+ String[] p = line.split("\t");
+ if (p.length < 2) continue;
+ OWLClass a = df.getOWLClass(IRI.create(p[0]));
+ OWLClass b = df.getOWLClass(IRI.create(p[1]));
+
+ String verdict;
+ long t0 = System.nanoTime();
+ try {
+ OWLClassExpression both = df.getOWLObjectIntersectionOf(a, b);
+ if (!r.isSatisfiable(both)) {
+ verdict = "entailed";
+ } else if (r.getSuperClasses(a, false).containsEntity(b)
+ || r.getSuperClasses(b, false).containsEntity(a)
+ || r.getEquivalentClasses(a).contains(b)) {
+ // Comparable classes: disjoint(A,B) with A ⊑ B forces
+ // A ⊑ ⊥.
+ verdict = "inadmissible";
+ } else {
+ // A satisfiable named class under both would become
+ // unsatisfiable under the assumption.
+ Set<OWLClass> subA = new HashSet<>(r.getSubClasses(a, false).getFlattened());
+ boolean shared = false;
+ for (OWLClass c : r.getSubClasses(b, false).getFlattened()) {
+ if (c.isOWLNothing()) continue;
+ if (subA.contains(c) && r.isSatisfiable(c)) {
+ shared = true;
+ break;
+ }
+ }
+ verdict = shared ? "inadmissible" : "admissible";
+ }
+ } catch (Exception e) {
+ verdict = "error";
+ }
+ double ms = (System.nanoTime() - t0) / 1e6;
+ System.out.println("{\"a\":\"" + p[0] + "\",\"b\":\"" + p[1]
+ + "\",\"verdict\":\"" + verdict + "\",\"ms\":"
+ + String.format("%.2f", ms) + "}");
+ System.out.flush();
+ }
+ r.dispose();
+ }
+}
diff --git a/docs/layer3-compiled-reasoning.md b/docs/layer3-compiled-reasoning.md
index 8010961f..9db95122 100644
--- a/docs/layer3-compiled-reasoning.md
+++ b/docs/layer3-compiled-reasoning.md
@@ -199,3 +199,53 @@ python benchmark/layer3-prototype/verify_join_soundness.py <corpus_dir> 250
# Rust bench (loads compiled.json)
cargo test --release --test claimcheck_pizza_bench -- --nocapture
```
+
+## Counting rules R4/R5 and the assumed-disjointness WARN tier (2026-07-27)
+
+Two further sound compile rules close the counting idiom (found by reading a
+92.1%-coverage ontology's failing axioms — dueling `ExactCardinality` and
+`allValuesFrom` restrictions):
+
+```
+R4 A ⊑ ≤m R.C, B ⊑ ≥n R.D, n > m, D ⊑* C (or C unqualified) ⟹ disj(A,B)
+R5 A ⊑ ∀R.(C…), B ⊑ ∀R.(D…), every Ci disjoint every Dj,
+ and A or B forces ≥1 R-successor ⟹ disj(A,B)
+```
+
+plus `DataExactCardinality(1, p, DataOneOf(v))` recognised as a pinned value
+for RD. Effect on the 12-ontology exhaustive audit: tier-2 residual fell from
+501 to **23 pairs of 78,884** (aggregate recall 99.83%), still **0 unsound**;
+the diagnosed ontology went 96.1% → 99.9%. Pizza and ore_ont_10230 hold at
+100%.
+
+### The WARN tier: vetted assumptions for zero-disjointness ontologies
+
+Most large real ontologies declare no disjointness, leaving the entailed
+contradiction tier empty. The WARN tier reconstructs a candidate surface under
+an explicit assumption semantics:
+
+- a proposer suggests pairs (built-in structural sibling heuristic, or an LLM
+ over MCP — the server never embeds one);
+- `VetDisjointness` (HermiT) gives each proposal a three-way verdict:
+ *entailed* (belongs in the hard tier), *inadmissible* (would break the
+ ontology), *admissible* (consistent to assume);
+- admissible pairs load via `load_assumed_disjoint` into their own token
+ bitsets and fire **warnings, never rejections** — `disjointness_assumed`,
+ witness named, explicitly labelled not-entailed. Verdicts are untouched;
+ the pair still routes to the residual.
+
+Holdout evaluation (`holdout_disjointness.py`): strip ALL disjointness, let
+the sibling heuristic + vetting reconstruct it, score the WARN closure
+against the original exhaustive matrix:
+
+| Ontology | axioms stripped | recall | precision |
+| --- | --- | --- | --- |
+| pizza.owl | 14 | 82.2% | 91.4% |
+| ore_ont_11064 | 54 | 44.3% | 92.1% |
+
+Precision is stable ~91–92%; recall depends on how much of the true surface
+is sibling-shaped. Measured precision is a **lower bound**: many "false"
+warnings (American + IceCream) are false only against entailed truth — they
+are exactly the intended-but-never-encoded disjointness the tier exists to
+surface. LLM proposals are the open slot for pushing recall past the
+structural heuristic.
diff --git a/src/claimcheck.rs b/src/claimcheck.rs
index 08972782..c002ced6 100644
--- a/src/claimcheck.rs
+++ b/src/claimcheck.rs
@@ -103,6 +103,12 @@ pub enum Verdict {
pub struct CheckResult {
pub verdict: Verdict,
pub violations: Vec<Violation>,
+ /// Assumption-based findings. A warning means an ASSUMED (not entailed)
+ /// disjointness axiom fired: the claim conflicts with vetted domain
+ /// knowledge that the ontology itself does not assert. Warnings never
+ /// change the verdict.
+ #[serde(default)]
+ pub warnings: Vec<Violation>,
/// Class pairs the join could not settle. A caller wanting `Consistent`
/// must discharge these with a reasoner.
pub residual_pairs: Vec<(String, String)>,
@@ -153,6 +159,9 @@ fn bits_first_common(a: &Bits, b: &Bits) -> Option<usize> {
struct RawData {
subsumptions: Vec<(String, String)>,
disjoint: Vec<(String, String)>,
+ /// Disjointness ASSUMED (e.g. LLM-proposed, reasoner-vetted), not entailed.
+ /// Drives warnings, never rejections.
+ assumed_disjoint: Vec<(String, String)>,
declared_classes: HashSet<String>,
declared_props: HashSet<String>,
functional: HashSet<String>,
@@ -162,6 +171,7 @@ impl RawData {
fn is_empty(&self) -> bool {
self.subsumptions.is_empty()
&& self.disjoint.is_empty()
+ && self.assumed_disjoint.is_empty()
&& self.declared_classes.is_empty()
&& self.declared_props.is_empty()
&& self.functional.is_empty()
@@ -170,17 +180,60 @@ impl RawData {
/// The immutable query structure. Built once per load generation; shared
/// across threads via `Arc`, so batch checking needs no locks on the hot path.
+/// Token bitsets for one set of disjointness axioms.
+struct TokenSet {
+ pair_left: Vec<u32>,
+ pair_right: Vec<u32>,
+ l_tokens: Vec<Bits>,
+ r_tokens: Vec<Bits>,
+}
+
+impl TokenSet {
+ fn build(pairs: &[(String, String)], ids: &HashMap<String, u32>,
+ descendants: &[Vec<u32>], n: usize) -> Self {
+ let m = pairs.len();
+ let mut pair_left = Vec::with_capacity(m);
+ let mut pair_right = Vec::with_capacity(m);
+ let mut l_tokens: Vec<Bits> = (0..n).map(|_| bits_new(m)).collect();
+ let mut r_tokens: Vec<Bits> = (0..n).map(|_| bits_new(m)).collect();
+ for (k, (x, y)) in pairs.iter().enumerate() {
+ let (xi, yi) = (ids[x.as_str()], ids[y.as_str()]);
+ pair_left.push(xi);
+ pair_right.push(yi);
+ for &c in &descendants[xi as usize] {
+ bits_set(&mut l_tokens[c as usize], k);
+ }
+ for &c in &descendants[yi as usize] {
+ bits_set(&mut r_tokens[c as usize], k);
+ }
+ }
+ Self { pair_left, pair_right, l_tokens, r_tokens }
+ }
+
+ /// Two-hop join over this token set. Returns the witnessing axiom.
+ fn incompatible<'a>(&'a self, names: &'a [String], ai: usize, bi: usize)
+ -> Option<(&'a str, &'a str)> {
+ if let Some(k) = bits_first_common(&self.l_tokens[ai], &self.r_tokens[bi]) {
+ return Some((names[self.pair_left[k] as usize].as_str(),
+ names[self.pair_right[k] as usize].as_str()));
+ }
+ if let Some(k) = bits_first_common(&self.r_tokens[ai], &self.l_tokens[bi]) {
+ return Some((names[self.pair_right[k] as usize].as_str(),
+ names[self.pair_left[k] as usize].as_str()));
+ }
+ None
+ }
+}
+
struct Index {
/// IRI → interned id, for classes only.
ids: HashMap<String, u32>,
/// id → IRI, for witness reporting.
names: Vec<String>,
- /// Disjointness axioms as interned pairs; index = token.
- pair_left: Vec<u32>,
- pair_right: Vec<u32>,
- /// Per class id: tokens whose left / right side subsumes this class.
- l_tokens: Vec<Bits>,
- r_tokens: Vec<Bits>,
+ /// Entailed disjointness (asserted + soundly derived). Drives rejections.
+ hard: TokenSet,
+ /// Assumed disjointness (proposed + vetted, not entailed). Drives warnings.
+ assumed: TokenSet,
}
impl Index {
@@ -197,7 +250,12 @@ impl Index {
names.push(s.to_string());
i
};
- for (a, b) in raw.subsumptions.iter().chain(raw.disjoint.iter()) {
+ for (a, b) in raw
+ .subsumptions
+ .iter()
+ .chain(raw.disjoint.iter())
+ .chain(raw.assumed_disjoint.iter())
+ {
intern(a, &mut ids, &mut names);
intern(b, &mut ids, &mut names);
}
@@ -221,48 +279,25 @@ impl Index {
}
}
- // Tokenise disjointness and stamp the bitsets down both hierarchies.
- let m = raw.disjoint.len();
- let mut pair_left = Vec::with_capacity(m);
- let mut pair_right = Vec::with_capacity(m);
- let mut l_tokens: Vec<Bits> = (0..n).map(|_| bits_new(m)).collect();
- let mut r_tokens: Vec<Bits> = (0..n).map(|_| bits_new(m)).collect();
- for (k, (x, y)) in raw.disjoint.iter().enumerate() {
- let (xi, yi) = (ids[x.as_str()], ids[y.as_str()]);
- pair_left.push(xi);
- pair_right.push(yi);
- for &c in &descendants[xi as usize] {
- bits_set(&mut l_tokens[c as usize], k);
- }
- for &c in &descendants[yi as usize] {
- bits_set(&mut r_tokens[c as usize], k);
- }
- }
+ // Tokenise both axiom sets and stamp bitsets down the hierarchies.
+ let hard = TokenSet::build(&raw.disjoint, &ids, &descendants, n);
+ let assumed = TokenSet::build(&raw.assumed_disjoint, &ids, &descendants, n);
- Self { ids, names, pair_left, pair_right, l_tokens, r_tokens }
+ Self { ids, names, hard, assumed }
}
- /// The two-hop join as two bitset intersections. Returns the witnessing
- /// disjointness axiom `(left, right)` when incompatible.
- ///
- /// Symmetric by construction: both orientations are tested, so callers
- /// never need to try both argument orders.
+ /// The entailed two-hop join. `Some` means PROVEN incompatible; drives
+ /// rejections. Symmetric by construction: both orientations are tested.
fn incompatible(&self, a: &str, b: &str) -> Option<(&str, &str)> {
let (&ai, &bi) = (self.ids.get(a)?, self.ids.get(b)?);
- let (ai, bi) = (ai as usize, bi as usize);
- if let Some(k) = bits_first_common(&self.l_tokens[ai], &self.r_tokens[bi]) {
- return Some((
- self.names[self.pair_left[k] as usize].as_str(),
- self.names[self.pair_right[k] as usize].as_str(),
- ));
- }
- if let Some(k) = bits_first_common(&self.r_tokens[ai], &self.l_tokens[bi]) {
- return Some((
- self.names[self.pair_right[k] as usize].as_str(),
- self.names[self.pair_left[k] as usize].as_str(),
- ));
- }
- None
+ self.hard.incompatible(&self.names, ai as usize, bi as usize)
+ }
+
+ /// The assumed two-hop join. `Some` means the pair conflicts with a
+ /// VETTED ASSUMPTION, not an entailment; drives warnings only.
+ fn assumed_incompatible(&self, a: &str, b: &str) -> Option<(&str, &str)> {
+ let (&ai, &bi) = (self.ids.get(a)?, self.ids.get(b)?);
+ self.assumed.incompatible(&self.names, ai as usize, bi as usize)
}
}
@@ -334,6 +369,17 @@ impl CompiledOntology {
Ok(pairs.len())
}
+ /// Load ASSUMED disjointness: pairs proposed (e.g. by an LLM) and vetted
+ /// by a reasoner as admissible — consistent with the ontology but not
+ /// entailed by it. These drive warnings, never rejections; a deployment
+ /// on a zero-disjointness ontology gets its verification value from
+ /// vocabulary checks plus this tier.
+ pub fn load_assumed_disjoint(&self, pairs: &[(String, String)]) -> Result<usize> {
+ self.raw.write().unwrap().assumed_disjoint.extend_from_slice(pairs);
+ self.invalidate();
+ Ok(pairs.len())
+ }
+
pub fn load_declared_classes(&self, iris: &[String]) -> Result<usize> {
self.raw.write().unwrap().declared_classes.extend(iris.iter().cloned());
self.invalidate();
@@ -364,6 +410,7 @@ impl CompiledOntology {
return Ok(CheckResult {
verdict: Verdict::Undetermined,
violations: Vec::new(),
+ warnings: Vec::new(),
residual_pairs: Vec::new(),
elapsed_us: 0,
});
@@ -381,6 +428,7 @@ impl CompiledOntology {
fn check_inner(raw: &RawData, ix: &Index, claim: &Claim) -> CheckResult {
let start = std::time::Instant::now();
let mut violations = Vec::new();
+ let mut warnings = Vec::new();
let mut residual = Vec::new();
// 1. Closed-world vocabulary. Open-world OWL structurally cannot flag
@@ -421,7 +469,18 @@ impl CompiledOntology {
),
});
} else {
- // NOT proven compatible. The join is incomplete.
+ // Not PROVEN incompatible. Probe the assumption tier:
+ // a hit is domain knowledge worth surfacing, but it is
+ // not proof, so the verdict is untouched and the pair
+ // still goes to the residual.
+ if let Some((wa, wb)) = ix.assumed_incompatible(a, b) {
+ warnings.push(Violation {
+ check: "disjointness_assumed".into(),
+ detail: format!(
+ "{subj} being both {a} and {b} conflicts with the ASSUMED disjointness of {wa} and {wb} (vetted assumption, not entailed by the ontology)"
+ ),
+ });
+ }
residual.push((a.to_string(), b.to_string()));
}
}
@@ -460,6 +519,7 @@ impl CompiledOntology {
CheckResult {
verdict,
violations,
+ warnings,
residual_pairs: residual,
elapsed_us: start.elapsed().as_micros(),
}
@@ -476,6 +536,7 @@ impl CompiledOntology {
.map(|_| CheckResult {
verdict: Verdict::Undetermined,
violations: Vec::new(),
+ warnings: Vec::new(),
residual_pairs: Vec::new(),
elapsed_us: 0,
})
@@ -880,6 +941,76 @@ mod tests {
assert_eq!(c.check(&claim).unwrap().verdict, Verdict::Rejected);
}
+
+ // ── assumed-disjointness WARN tier ──────────────────────────────────
+
+ #[test]
+ fn assumed_disjointness_warns_but_never_rejects() {
+ let c = fixture();
+ // Vetted assumption: Margherita and CheeseyPizza "should" be disjoint
+ // (deliberately false in reality — assumptions are not entailments,
+ // and the machinery must treat them accordingly).
+ c.load_assumed_disjoint(&[(iri("Margherita"), iri("CheeseyPizza"))]).unwrap();
+ let claim = Claim {
+ types: vec![("x".into(), iri("Margherita")), ("x".into(), iri("CheeseyPizza"))],
+ ..Default::default()
+ };
+ let r = c.check(&claim).unwrap();
+ assert_eq!(r.verdict, Verdict::Undetermined, "assumption must not reject: {r:?}");
+ assert_eq!(r.warnings.len(), 1, "{r:?}");
+ assert_eq!(r.warnings[0].check, "disjointness_assumed");
+ assert!(r.warnings[0].detail.contains("not entailed"));
+ // The pair still needs tier 2: nothing was proven.
+ assert_eq!(r.residual_pairs.len(), 1);
+ }
+
+ #[test]
+ fn assumed_tier_climbs_the_hierarchy() {
+ let c = fixture();
+ // Assumption at superclass level must warn for subclasses.
+ c.load_assumed_disjoint(&[(iri("NamedPizza"), iri("CheeseyPizza"))]).unwrap();
+ let claim = Claim {
+ // Margherita ⊑ NamedPizza (inferred), so the assumption applies.
+ types: vec![("x".into(), iri("Margherita")), ("x".into(), iri("CheeseyPizza"))],
+ ..Default::default()
+ };
+ let r = c.check(&claim).unwrap();
+ assert_eq!(r.warnings.len(), 1, "{r:?}");
+ assert!(r.warnings[0].detail.contains("NamedPizza"), "witness must name the assumed axiom: {r:?}");
+ }
+
+ #[test]
+ fn hard_rejection_takes_precedence_over_assumed() {
+ let c = fixture();
+ c.load_assumed_disjoint(&[(iri("Margherita"), iri("MeatyPizza"))]).unwrap();
+ let claim = Claim {
+ types: vec![("x".into(), iri("Margherita")), ("x".into(), iri("MeatyPizza"))],
+ ..Default::default()
+ };
+ let r = c.check(&claim).unwrap();
+ // Entailed disjointness fires as a rejection; no duplicate warning.
+ assert_eq!(r.verdict, Verdict::Rejected);
+ assert!(r.warnings.is_empty(), "{r:?}");
+ }
+
+ #[test]
+ fn oracle_confirmed_consistency_keeps_the_warning() {
+ let c = fixture();
+ c.load_assumed_disjoint(&[(iri("Margherita"), iri("CheeseyPizza"))]).unwrap();
+ let o = oracle(vec![], vec![]);
+ let claim = Claim {
+ types: vec![("x".into(), iri("Margherita")), ("x".into(), iri("CheeseyPizza"))],
+ ..Default::default()
+ };
+ let r = c.check_with_oracle(&claim, &o).unwrap();
+ // The reasoner proves no ENTAILED contradiction, so the claim is
+ // Consistent — but the extra-logical assumption still stands and the
+ // warning must survive, because "not entailed inconsistent" does not
+ // refute vetted domain knowledge the ontology never encoded.
+ assert_eq!(r.verdict, Verdict::Consistent, "{r:?}");
+ assert_eq!(r.warnings.len(), 1, "{r:?}");
+ }
+
// ── batch / parallelism ─────────────────────────────────────────────
#[test]