Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
Reason in pure Python and let the same verified checker say what it was worth
FABIOTESS47142adafa60
diff --git a/python/README.md b/python/README.mdindex ba2261f4..fde87707 100644--- a/python/README.md+++ b/python/README.md@@ -1,6 +1,6 @@# Open Ontologies Lite (Python bridge)-A lightweight, pip-installable Python bridge to the same [Oxigraph](https://github.com/oxigraph/oxigraph) RDF/OWL engine that powers [Open Ontologies](https://github.com/fabio-rovai/open-ontologies). **No Rust toolchain, no compilation, no multi-gigabyte build directory** — `pyoxigraph` ships the engine as a prebuilt wheel, so everything here is pure-Python glue installed from PyPI.+A lightweight, pip-installable Python bridge to the same [Oxigraph](https://github.com/oxigraph/oxigraph) RDF/OWL engine that powers [Open Ontologies](https://github.com/fabio-rovai/open-ontologies). **No Rust toolchain, no compilation, no multi-gigabyte build directory**. `pyoxigraph` ships the engine as a prebuilt wheel, so everything here is pure-Python glue installed from PyPI.It exposes the core ontology lifecycle as both a Python library and an MCP server.@@ -54,9 +54,9 @@ structural comparison, no model. Also exposed as the `onto_kgcl_diff` MCP tool.engine.load_rows(df, base_iri="http://x.org/", class_iri="http://x.org/Thing", id_column="id")```-`load_rows` duck-types against the common export methods — `to_pylist()`+`load_rows` duck-types against the common export methods (`to_pylist()`(fenic DataFrame, pyarrow Table), `to_dicts()` (polars), `to_dict("records")`-(pandas) — or takes a plain list of dicts. Values become typed literals+(pandas)), or takes a plain list of dicts. Values become typed literals(int/float/bool → XSD), `None` is skipped, and the output is deterministic.The primary consumer is [fenic](https://github.com/typedef-ai/fenic): itssemantic operators do the LLM extraction, this bridge just loads and lets@@ -118,6 +118,66 @@ Register it with any MCP client (e.g. Claude):| `onto_lint` | Missing labels, domains, ranges || `onto_shacl` | SHACL conformance: violations with focus node, path, value, severity and constraint, plus `focus_nodes` and `unmatched_shapes` (needs the `[shacl]` extra) || `onto_vocab_check` | Closed-world check: which terms in the data are not declared in the loaded ontology |+| `onto_reason` | Forward-chain a Horn rule table over the store and write a certificate the Lean checker verifies |++### Certified reasoning++The reasoner here is pure Python over pyoxigraph and adds no dependency at all.+It is also **untrusted**, in exactly the way the Rust engine is untrusted: what+carries the warrant is not the engine but the certificate, and the certificate is+checked by a small verified checker written in core Lean 4, no Mathlib, whose+soundness is a machine-checked theorem with the axiom footprint pinned to+`[propext, Classical.choice, Quot.sound]`.++```python+from open_ontologies_lite import OntologyEngine++engine = OntologyEngine()+engine.load(open("ontology.ttl").read())+report = engine.reason_horn("out/cert")++report["derived_triples"] # 859+report["check"]["verdict"] # 'entailed'+report["check"]["theorem"] # 'OOCert.entails_of_builtin_horn'+```++Three files land in `out/cert`: the rule table that ran, every triple the run+started from, and one line per derived triple carrying the rule index, the+binding and the premises. `oo-horn check` reads those three and pronounces.++**Two verdicts, and they never share a word.** A certificate over the built-in+table earns `entailed`: every conclusion is true in every model of the asserted+graph. A certificate over any other table, the built-ins plus one extra rule+included, earns `entailed_under_supplied_rules`: every conclusion is true in+every model that *also satisfies your rules*, which are assumed and never+checked. A rule reading "every supplier is compliant" produces certificates that+check green for ever. Only the Lean checker decides which of the two a run+earned; nothing in this package contains either word as an executable string,+and a test scans the abstract syntax tree to keep it that way.++**The checker is optional and external.** Build it with `cd lean && lake build`+in a checkout of the [Rust repository](https://github.com/fabio-rovai/open-ontologies),+or set `OO_HORN`. Without it the package still reasons and still writes the+certificate, and the report says so in its own words:++```python+report["check"]["status"] # 'unchecked_no_checker'+report["check"]["checked"] # False+report["check"]["verdict"] # None+report["check"]["warning"] # 'the certificate was written and NOT checked: ...+ # Nothing here has been proved; these are the+ # claims of an untrusted engine'+```++Nothing is materialised into the store. A conclusion drawn under a supplied rule+table holds only in models that satisfy that table, so writing it back in beside+the assertions is how one run's output becomes the next run's axiom. Only the+default graph is asserted, for the same reason.++Because this engine and the Rust one are independent implementations of one+specification, running both over a corpus and checking both certificates gives a+three-way differential. `tests/test_horn_differential.py` does exactly that, and+reports disagreement rather than adjudicating it.### Closed-world checkingdiff --git a/python/examples/certified_reasoning.py b/python/examples/certified_reasoning.pynew file mode 100644index 00000000..ae6668d2--- /dev/null+++ b/python/examples/certified_reasoning.py@@ -0,0 +1,123 @@+#!/usr/bin/env python3+"""Reason over an ontology, then have a verified checker say what that was worth.++Run it:++ python examples/certified_reasoning.py++It works with no Lean checker installed, which is the point: it writes the+certificate either way and tells you plainly whether anything was proved. To get+a verdict, build the checker once from a checkout of the Rust repository:++ cd lean && lake build++The three things this example is trying to show, in order of importance:++1. The engine states no verdict. It derives triples, writes a certificate and+ reports where it is. `oo-horn` decides what the run earned, and this package+ copies its words rather than forming its own.++2. The built-in table and a table you wrote earn DIFFERENT verdicts, and the+ difference is not a formality. The second run below appends one rule saying+ every supplier is compliant. It is false of the world, the engine fires it+ happily, and the checker accepts the certificate, because the inference really+ does follow FROM THAT RULE. What changes is the verdict word, the theorem+ named, and the digest of the table that was in force. A layer that collapsed+ those two into one word would be a machine for turning an assumption into a+ fact with a proof attached.++3. Nothing is materialised. Look at the store after the run: it is the size it+ was. A conclusion drawn under a supplied rule table holds only in models that+ satisfy that table, so writing it back in beside the assertions is how one+ run's output becomes the next run's axiom.+"""++import json+import tempfile+from pathlib import Path++from open_ontologies_lite import OntologyEngine+from open_ontologies_lite.horn.rules import AtomPat, RulePattern, builtin_rules++TYPE = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"++ONTOLOGY = """+@prefix ex: <http://example.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .++ex:Supplier rdfs:subClassOf ex:Organisation .+ex:Organisation rdfs:subClassOf ex:LegalEntity .+ex:acme a ex:Supplier .+ex:supplies rdfs:domain ex:Supplier ; rdfs:range ex:Part .+ex:acme ex:supplies ex:widget .+ex:partners a owl:SymmetricProperty .+ex:acme ex:partners ex:globex .+"""++# One rule, in the `rules.tsv` shape: a body of triple patterns and a head.+# Every variable in the head must occur in the body, or the engine would have to+# invent a term to bind it to and the table is refused.+EVERY_SUPPLIER_IS_COMPLIANT = RulePattern(+ name="every-supplier-is-compliant",+ body=(AtomPat("?s", TYPE, "<http://example.org/Supplier>"),),+ head=AtomPat("?s", TYPE, "<http://example.org/Compliant>"),+)+++def show(title: str, report: dict) -> None:+ check = report["check"]+ print(f"\n{title}")+ print("-" * len(title))+ print(f" asserted triples {report['asserted_triples']}")+ print(f" derived triples {report['derived_triples']}")+ print(f" fixpoint reached {report['fixpoint_reached']}")+ print(f" materialised {report['materialized']}")+ print(f" certificate {report['certificate']['dir']}")+ print(f" check status {check['status']}")+ print(f" checked {check['checked']}")+ print(f" verdict {check['verdict']}")+ if check.get("theorem"):+ print(f" theorem {check['theorem']}")+ print(f" rule digest {check['rules_digest']}")+ print(f" built-in digest {check['builtin_rules_digest']}")+ print(f" digests agree {check['digests_agree']}")+ print(f" means {check['means']}")+ if check.get("warning"):+ print(f" warning {check['warning']}")+++def main() -> None:+ out = Path(tempfile.mkdtemp(prefix="certified-reasoning-"))++ engine = OntologyEngine()+ engine.load(ONTOLOGY)+ before = engine.stats()["triples"]++ show("Run 1: the built-in table", engine.reason_horn(str(out / "builtin")))++ supplied = list(builtin_rules()) + [EVERY_SUPPLIER_IS_COMPLIANT]+ report = engine.reason_horn(str(out / "supplied"), rules=supplied)+ show("Run 2: the built-in table plus one rule of your own", report)++ compliant = [+ d+ for d in report["sample_derivations"]+ if d.endswith("<http://example.org/Compliant>")+ ]+ print(f"\n the appended rule fired: {compliant}")+ print(+ " that conclusion is true in every model of the graph THAT ALSO SATISFIES\n"+ " your rule, and in no others. The rule was assumed and never checked."+ )++ after = engine.stats()["triples"]+ print(f"\nStore before {before} triples, after {after}. Nothing was materialised.")+ print(f"\nCertificates are in {out}. Check one by hand with:")+ print(" " + report["certificate"]["check_with"])+ print("\nFull report of run 2:")+ print(json.dumps(report, indent=2)[:1200] + "\n ...")+++if __name__ == "__main__":+ main()diff --git a/python/pyproject.toml b/python/pyproject.tomlindex 622e52d7..7a6fea72 100644--- a/python/pyproject.toml+++ b/python/pyproject.toml@@ -24,6 +24,21 @@ classifiers = [# fastapi. Measured against semantica 0.6.6, whose pyproject declares# `fastapi>=0.109.2`: installing 0.4.0 uninstalled it, and every import of# `semantica/explorer` failed afterwards.+#+# The Horn reasoner and the certificate bridge in `open_ontologies_lite/horn/`+# add ZERO runtime dependencies and no extra. The forward chainer is pure Python+# over the pyoxigraph above; the rest is `subprocess`, `json`, `hashlib` and+# `importlib.resources`. There is no pyo3, no maturin and no binding to the Rust+# crate, because the stated value of this package is that it installs without+# compiling anything, and a Rust toolchain requirement would cost exactly the+# audience the Rust engine already cannot reach.+#+# The Lean checker `oo-horn` is an external BINARY, built from `lean/` by+# `lake build`. It is deliberately not packaged and is not a dependency of any+# kind, not even an optional extra: a wheel cannot ship a Lean toolchain, and+# pretending otherwise in the metadata would make `pip install` fail for+# everyone who only wants the reasoner. The package is fully functional without+# it and says loudly, in every report, when a certificate went unchecked.dependencies = ["pyoxigraph>=0.5,<0.6",]diff --git a/python/src/open_ontologies_lite/__init__.py b/python/src/open_ontologies_lite/__init__.pyindex 598174f3..d70840c5 100644--- a/python/src/open_ontologies_lite/__init__.py+++ b/python/src/open_ontologies_lite/__init__.py@@ -4,6 +4,21 @@ Oxigraph RDF/OWL engine. No Rust toolchain, no compilation, prebuilt wheels onlyfrom .dataframe import rows_from_dataframe, rows_to_turtlefrom .engine import OntologyEngine, ValidationResult, resolve_format+from .horn import (+ AssertedGraphError,+ CertificateFieldError,+ CertificateUnreadable,+ CheckerUnavailable,+ HornResult,+ RulePattern,+ RuleTableError,+ builtin_rules,+ check_horn,+ find_checker,+ parse_rules,+ rules_tsv,+ run_horn,+)from .kgcl import ChangeSet, kgcl_difffrom .vocab_check import vocab_check@@ -20,6 +35,28 @@ __all__ = ["__version__",]+# The Horn reasoner and the certificate bridge are UNCONDITIONAL exports, with no+# extra to install: the reasoner is pure Python over the pyoxigraph the package+# already requires, and the bridge is standard library. The Lean checker itself is+# an external binary built by `lake`, deliberately not packaged and not a+# dependency of any kind; `check_horn` reports its absence and never works around+# it. See horn/__init__.py for the verdict vocabulary before using any of this.+__all__ += [+ "run_horn",+ "check_horn",+ "find_checker",+ "builtin_rules",+ "parse_rules",+ "rules_tsv",+ "HornResult",+ "RulePattern",+ "RuleTableError",+ "CheckerUnavailable",+ "CertificateUnreadable",+ "CertificateFieldError",+ "AssertedGraphError",+]+# AlignmentIndex needs the optional [align] extra (hnswlib); export it only when# importable so the base package stays dependency-light.try: # pragma: no coverdiff --git a/python/src/open_ontologies_lite/engine.py b/python/src/open_ontologies_lite/engine.pyindex 938a650b..2711e08e 100644--- a/python/src/open_ontologies_lite/engine.py+++ b/python/src/open_ontologies_lite/engine.py@@ -217,6 +217,94 @@ class OntologyEngine:out.append(val.value)return out+ # ---- certified reasoning ----------------------------------------------+ def reason_horn(+ self,+ certificate_dir: str,+ *,+ rules=None,+ graphs: str | list[str] = "default",+ check: bool = True,+ checker: str | None = None,+ timeout: float = 120.0,+ max_iterations: int | None = None,+ ) -> dict:+ """Derive the closure of a Horn rule table over the loaded store and+ write a certificate the proved-sound Lean checker in `lean/` verifies.++ With `rules=None` this runs the BUILT-IN table, whose bytes are shipped+ with the package and written verbatim. That is the only table that can+ earn the absolute verdict, and `oo-horn` decides whether it did. Pass a+ path or a list of `RulePattern` to run a table you wrote: those rules are+ ASSUMED and never checked, so a certificate over them holds only in+ models of the asserted graph that ALSO satisfy them. A rule saying every+ supplier is compliant produces certificates that check green for ever.++ Nothing is materialised. A conclusion drawn under a supplied rule table+ holds only in models that satisfy that table, so it is not written into+ the store beside the assertions; the certificate is the output of the+ run.++ `check=False` writes the certificate and does not run the checker. The+ returned report then says `not_requested` and carries no verdict, exactly+ as it does when the checker is not installed.+ """+ from .horn.certify import CertificateUnreadable, check_horn+ from .horn.reason import run_horn+ from .horn.rules import RulePattern, parse_rules++ source = None+ if rules is None:+ table = None+ elif isinstance(rules, (str, Path)):+ path = Path(rules)+ table = parse_rules(path.read_text(encoding="utf-8"))+ source = str(path)+ else:+ table = list(rules)+ for r in table:+ if not isinstance(r, RulePattern):+ raise TypeError(+ f"rules must be a path or a sequence of RulePattern, got "+ f"{type(r).__name__}"+ )+ result = run_horn(+ self.store,+ table,+ certificate_dir=certificate_dir,+ graphs=graphs,+ max_iterations=max_iterations,+ rules_source=source,+ )+ report = result.to_dict()+ if not check:+ report["check"] = {+ "status": "not_requested",+ "checked": False,+ "verdict": None,+ "pronounced_by": None,+ "check_with": report["certificate"]["check_with"],+ "warning": (+ "the certificate was written and NOT checked, because check=False. "+ "Nothing here has been proved; these are the claims of an untrusted "+ "engine"+ ),+ }+ return report+ outcome = check_horn(certificate_dir, checker=checker, timeout=timeout)+ report["check"] = outcome+ if outcome["status"] == "unreadable":+ # This method wrote the three files itself, so a checker that cannot+ # read or parse them is an emitter bug and not a data problem. Folding+ # it into the missing-binary branch is how such a bug gets mistaken+ # for an uninstalled checker and never investigated.+ raise CertificateUnreadable(+ f"{outcome['check_with']} could not read the certificate this run had "+ f"just written, which is a defect in this emitter and not a rejection: "+ f"{outcome['error']}"+ )+ return report+def _triple_key(t) -> str:tr = getattr(t, "triple", t)diff --git a/python/src/open_ontologies_lite/horn/__init__.py b/python/src/open_ontologies_lite/horn/__init__.pynew file mode 100644index 00000000..95565610--- /dev/null+++ b/python/src/open_ontologies_lite/horn/__init__.py@@ -0,0 +1,79 @@+"""A pure-Python Horn reasoner whose conclusions carry Lean-checked certificates.++Four modules, split so that "this works with no binary installed" is structural+rather than a promise:++* `terms` the one place a term becomes a certificate field, and the guard that+ makes a forged derivation step impossible to write by accident.+* `rules` the rule table as data. Text and dataclasses, no triple store.+* `reason` the forward chainer and the certificate emitter. Imports pyoxigraph.+* `certify` the bridge to `oo-horn`, the verified checker. Standard library only.++`reason` never imports `certify` and `certify` never imports `reason`, and+`test_the_verdict_words_are_never_written_in_python.py` fails if either ever+does. That is what guarantees the reasoner runs with no checker installed and+that the bridge can be exercised against a certificate this package did not+write. This file imports both, because re-exporting is what it is for, and the+invariant that matters is between the two working modules.++# The verdict vocabulary, which this package never speaks++A certificate over the BUILT-IN rule table can earn `entailed`: every conclusion+is true in every model of the asserted graph. A certificate over ANY other+table, the built-ins plus one extra rule included, earns+`entailed_under_supplied_rules`: every conclusion is true in every model of the+asserted graph THAT ALSO SATISFIES those rules, which are assumed and never+checked. A result the Lean checker has not accepted earns neither and says so.++Only `lean/HMain.lean` decides which of the two a run earned. No module in this+package contains either word as an executable string, and an AST scan in the+test suite enforces it: `verdict` is only ever copied out of the checker's own+report. Read `docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md`+before changing anything here.+"""++from __future__ import annotations++from .certify import (+ CertificateUnreadable,+ CheckerUnavailable,+ check_horn,+ find_checker,+)+from .reason import (+ AssertedGraphError,+ HornResult,+ HornStep,+ run_horn,+)+from .rules import (+ AtomPat,+ RulePattern,+ RuleTableError,+ builtin_rules,+ builtin_rules_bytes,+ parse_rules,+ rules_tsv,+)+from .terms import CertificateFieldError, checked_field, spell++__all__ = [+ "AssertedGraphError",+ "AtomPat",+ "CertificateFieldError",+ "CertificateUnreadable",+ "CheckerUnavailable",+ "HornResult",+ "HornStep",+ "RulePattern",+ "RuleTableError",+ "builtin_rules",+ "builtin_rules_bytes",+ "check_horn",+ "checked_field",+ "find_checker",+ "parse_rules",+ "rules_tsv",+ "run_horn",+ "spell",+]diff --git a/python/src/open_ontologies_lite/horn/certify.py b/python/src/open_ontologies_lite/horn/certify.pynew file mode 100644index 00000000..2f93b7f9--- /dev/null+++ b/python/src/open_ontologies_lite/horn/certify.py@@ -0,0 +1,349 @@+"""The bridge to the verified checker, and the vocabulary of what a run earned.++This module states no verdict of its own. On acceptance it copies the checker's+words out of its stdout verbatim; on anything else it says, in its own words,+that nothing was checked. The two verdicts the checker can print are++* the absolute one, for a certificate over the BUILT-IN table, which+ `OOCert.Builtin.asHorn_sound` discharges against the semantics: every+ conclusion is true in every model of the asserted graph;+* the relativised one, `entailed_under_supplied_rules`, for a certificate over+ ANY other table, including the built-ins plus one extra rule: every conclusion+ is true in every model of the asserted graph THAT ALSO SATISFIES those rules.+ The rules are assumed and never checked, so a rule reading "every supplier is+ compliant" produces certificates that check green for ever.++Which of the two a run earned is decided inside `lean/HMain.lean`, by a full+ordered equality between the table it was handed and the built-in one. Deciding+it a second time here would make Python a second place where the two can be+confused, which is exactly the hazard decision 0003 exists to prevent, so this+module does not compare the tables, does not default the verdict, and does not+contain either verdict word as an executable string. `verdict` is only ever+assigned from the payload, and the rejection JSON has no `verdict` key at all,+so `payload.get("verdict", ...)` is not a hypothetical mistake: it is the+natural way to write that line and it is the exact shape of the laundering+failure.++The checker is an OPTIONAL EXTERNAL BINARY. It is built by `lake` from `lean/`,+it is deliberately not a Python dependency of any kind, not even an extra, and+this package is fully functional without it. What it must never do is report an+unchecked result as checked, so every outcome below carries `checked` and a+`status` word, and four of the six say plainly that nothing was proved.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+from pathlib import Path++#: The theorem `HMain.lean` names when the table it was handed is the built-in+#: one. Used only to notice an impossible disagreement with the digests and say+#: so; it never overrides the checker and never synthesises a verdict.+_BUILTIN_THEOREM = "OOCert.entails_of_builtin_horn"++_INSTALL = (+ "Build it with `cd <repo>/lean && lake build` (it is in defaultTargets, so a bare "+ "`lake build` is enough), or set {env} to the binary"+)++_UNPROVED = (+ "Nothing here has been proved; these are the claims of an untrusted engine"+)+++class CheckerUnavailable(RuntimeError):+ """The verified checker was not found. Reported, never worked around."""++ def __init__(self, binary: str, looked_in: list[str], install_line: str):+ self.binary = binary+ self.looked_in = looked_in+ self.install_line = install_line+ where = (+ f"Looked in {', '.join(looked_in)} and on PATH"+ if looked_in+ else "Looked on PATH, and nowhere else was named: there is no repository "+ "above this package, which is normal for a pip install"+ )+ super().__init__(+ f"{binary}, the verified checker, was not found. {install_line}. {where}"+ )+++class CertificateUnreadable(RuntimeError):+ """The checker could not read a certificate this process had just written.++ Exit 2 is not a rejection. A run that wrote its own three files and is then+ told they cannot be read or parsed has an emitter bug, and folding that into+ the missing-binary branch is how such a bug gets mistaken for an uninstalled+ checker and never investigated.+ """+++def _env_var(name: str) -> str:+ """`oo-horn` -> `OO_HORN`. The repo spells long-form `OPEN_ONTOLOGIES_*` for+ configuration and short `OO_*` for pointing at Lean-side artefacts+ (`OO_FOLMODEL`, `OO_DL_MODEL_DIR`), and this is one of those."""+ return name.upper().replace("-", "_")+++def _repo_candidate(name: str) -> Path | None:+ """`<repo>/lean/.lake/build/bin/<name>`, if this file sits inside a checkout.++ A pip-installed wheel has no repository above it, so finding nothing here is+ normal and must not be an error.+ """+ for parent in Path(__file__).resolve().parents:+ if (parent / "lean" / "lakefile.toml").is_file():+ return parent / "lean" / ".lake" / "build" / "bin" / name+ return None+++def find_checker(name: str = "oo-horn", explicit: str | Path | None = None) -> Path:+ """Locate the checker: explicit, then the environment, then the repository+ build directory, then PATH.++ That order is the Rust precedent (`src/fol_solve.rs:278-306`), and the repo+ probe comes before PATH deliberately: a developer working in the checkout has+ just run `lake build`, the repo binary is the one they mean, and a stale+ `oo-horn` on PATH silently shadowing a freshly built one is a bad half-hour.++ The docstring of the Rust original is the reason this raises rather than+ degrading: "Its absence is reported rather than worked around. A pipeline+ that quietly dropped to an oracle verdict because the checker was not built+ would make every run look like a solver limitation."+ """+ looked: list[str] = []+ env = _env_var(name)+ if explicit is not None:+ # An explicit path does NOT fall through, matching the Rust precedent: a+ # caller who named a binary meant that binary, and quietly running a+ # different one found on PATH would make a report about the wrong+ # checker. The environment variable does fall through, because it is a+ # site-wide default rather than a per-call instruction.+ p = Path(explicit)+ if p.is_file() and os.access(p, os.X_OK):+ return p+ raise CheckerUnavailable(+ name,+ [str(p)],+ f"no executable {name} at {p}, and a path given explicitly is not replaced "+ f"by a search",+ )+ from_env = os.environ.get(env)+ if from_env:+ p = Path(from_env)+ looked.append(f"{env}={from_env}")+ if p.is_file() and os.access(p, os.X_OK):+ return p+ repo = _repo_candidate(name)+ if repo is not None:+ looked.append(str(repo))+ if repo.is_file() and os.access(repo, os.X_OK):+ return repo+ on_path = shutil.which(name)+ if on_path:+ return Path(on_path)+ raise CheckerUnavailable(name, looked, _INSTALL.format(env=env))+++def _check_with(certificate_dir: Path, name: str) -> str:+ return (+ f"{name} check {certificate_dir / 'rules.tsv'} "+ f"{certificate_dir / 'asserted.tsv'} {certificate_dir / 'horn.tsv'}"+ )+++def _unchecked(status: str, certificate_dir: Path, name: str, **extra) -> dict:+ """Every outcome in which the checker did not pronounce. `verdict` is present+ and None rather than absent, so a caller reading `report["check"]["verdict"]`+ cannot get a KeyError and reach for a default."""+ out = {+ "status": status,+ "checked": False,+ "verdict": None,+ "pronounced_by": None,+ "check_with": _check_with(certificate_dir, name),+ "warning": None,+ }+ out.update(extra)+ return out+++def check_horn(+ certificate_dir: str | Path,+ *,+ checker: str | Path | None = None,+ timeout: float = 120.0,+ name: str = "oo-horn",+) -> dict:+ """Run the Lean checker over a certificate directory and report what it said.++ Six outcomes, one `status` word each: `accepted`, `rejected`, `unreadable`,+ `unchecked_no_checker`, `unchecked_timeout`, `unchecked_error`. Only the first+ two have `checked` true, and only the first carries a verdict, copied from the+ checker's stdout and never computed here.++ A read or parse error is NOT a rejection: exit 1 means a step was rejected,+ exit 2 means the checker could not read what it was given. This is a library+ primitive over a directory it did not necessarily write, so it returns that as+ `unreadable` in the package's `ValidationResult(ok=False, error=...)` idiom;+ `OntologyEngine.reason_horn`, which did write the files, raises on it instead.+ """+ certificate_dir = Path(certificate_dir)+ try:+ binary = find_checker(name, checker)+ except CheckerUnavailable as exc:+ return _unchecked(+ "unchecked_no_checker",+ certificate_dir,+ name,+ missing=exc.binary,+ looked_in=exc.looked_in,+ how_to_get_it=exc.install_line,+ warning=(+ f"the certificate was written and NOT checked: {exc}. {_UNPROVED}"+ ),+ )+ argv = [+ str(binary),+ "check",+ str(certificate_dir / "rules.tsv"),+ str(certificate_dir / "asserted.tsv"),+ str(certificate_dir / "horn.tsv"),+ ]+ try:+ # Always a timeout, never shell=True. `oo-horn` writes one JSON line so a+ # pipe cannot fill, but an MCP server that hangs for ever on a missing+ # timeout is a worse bug than the one it avoids.+ proc = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)+ except subprocess.TimeoutExpired:+ return _unchecked(+ "unchecked_timeout",+ certificate_dir,+ name,+ timeout_seconds=timeout,+ error=f"{binary} did not finish within {timeout} seconds",+ warning=f"the certificate was written and NOT checked. {_UNPROVED}",+ )+ except OSError as exc: # a binary that will not execute at all+ return _unchecked(+ "unchecked_error",+ certificate_dir,+ name,+ error=f"cannot run {binary}: {exc}",+ warning=f"the certificate was written and NOT checked. {_UNPROVED}",+ )++ if proc.returncode == 2:+ # Exit 2 writes to STDERR and nothing to stdout. A bridge that captured+ # only stdout would get "" here and a json.loads failure that reads like a+ # checker bug.+ return _unchecked(+ "unreadable",+ certificate_dir,+ name,+ error=proc.stderr.strip() or proc.stdout.strip(),+ means=(+ "a read or parse error is not a rejection: exit 1 means a step was "+ "rejected, exit 2 means the checker could not read what it was given"+ ),+ warning=f"the certificate was written and NOT checked. {_UNPROVED}",+ )++ try:+ payload = json.loads(proc.stdout)+ except (ValueError, TypeError):+ return _unchecked(+ "unchecked_error",+ certificate_dir,+ name,+ error=(+ f"{binary} exited {proc.returncode} and its output is not JSON: "+ f"{proc.stdout.strip()[:400]!r} / {proc.stderr.strip()[:400]!r}"+ ),+ warning=f"the certificate was written and NOT checked. {_UNPROVED}",+ )++ if proc.returncode == 1 and payload.get("ok") is False:+ return {+ "status": "rejected",+ "checked": True,+ "verdict": None,+ "pronounced_by": str(binary),+ "checker_report": payload,+ "means": (+ "the Lean checker rejected at least one step of this certificate. It "+ "establishes nothing"+ ),+ "files": _check_with(certificate_dir, name),+ "check_with": _check_with(certificate_dir, name),+ }++ if proc.returncode != 0 or payload.get("ok") is not True:+ return _unchecked(+ "unchecked_error",+ certificate_dir,+ name,+ error=(+ f"{binary} exited {proc.returncode} with {proc.stdout.strip()[:400]!r}, "+ f"which is neither an acceptance nor a rejection"+ ),+ warning=f"the certificate was written and NOT checked. {_UNPROVED}",+ )++ try:+ # No default, no fallback, no conditional. If a payload the checker called+ # ok is missing one of these, that is an unknown checker and not an+ # acceptance this bridge may summarise.+ verdict = payload["verdict"]+ theorem = payload["theorem"]+ means = payload["means"]+ rules_digest = payload["rules_digest"]+ builtin_digest = payload["builtin_rules_digest"]+ derivations = payload["derivations"]+ except KeyError as exc:+ return _unchecked(+ "unchecked_error",+ certificate_dir,+ name,+ error=(+ f"{binary} accepted the certificate but its report has no {exc} key, so "+ f"this is not a checker this bridge understands"+ ),+ warning=f"the certificate was written and NOT checked. {_UNPROVED}",+ )++ digests_agree = rules_digest == builtin_digest+ out = {+ "status": "accepted",+ "checked": True,+ "verdict": verdict,+ "theorem": theorem,+ "means": means,+ "pronounced_by": str(binary),+ "rules_digest": rules_digest,+ "builtin_rules_digest": builtin_digest,+ "digests_agree": digests_agree,+ "derivations": derivations,+ # An empty horn.tsv is accepted with zero derivations, and the checker is+ # right: vacuously every step in an empty list holds. The report would be+ # what was wrong, so a verdict is never rendered here without the count+ # beside it.+ "vacuous": derivations == 0,+ "check_with": _check_with(certificate_dir, name),+ "checker_report": payload,+ }+ if theorem == _BUILTIN_THEOREM and not digests_agree:+ # Cannot happen: the checker derives both from the same comparison. If it+ # ever does, the anomaly is REPORTED and the checker is still not+ # overridden, because a gate that can only weaken is still a second place+ # where the two warrants are decided.+ out["consistency_warning"] = (+ "the checker named the built-in theorem while reporting a rule digest that "+ "differs from the built-in table's. Do not rely on this report; rerun and "+ "raise it against lean/"+ )+ return outdiff --git a/python/src/open_ontologies_lite/horn/reason.py b/python/src/open_ontologies_lite/horn/reason.pynew file mode 100644index 00000000..52624d82--- /dev/null+++ b/python/src/open_ontologies_lite/horn/reason.py@@ -0,0 +1,641 @@+"""A pure-Python forward chainer that emits a certificate, and states no verdict.++# Why a second untrusted engine is safe++The house rule is that a fast UNTRUSTED engine proposes and a small VERIFIED+checker disposes. The Rust reasoner is untrusted; the certificate carries the+warrant. A second, completely independent reasoner written in Python is+therefore not a new risk: it is untrusted in exactly the same way, its+conclusions carry exactly the same certificates, and the same Lean theorem+checks them. Nothing about the guarantee weakens, because the guarantee never+depended on the engine.++What it buys is a THIRD implementation. Rust engine, Python engine and Lean+checker over one corpus give a differential that can find a defect none of them+would find alone.++# What this module does not decide++It does not print either verdict word and it never will. `oo-horn` decides which+warrant a run earned by comparing the table it was handed against the built-in+one, and a second place where the two could be confused is exactly the hazard+decision 0003 exists to prevent. What this module reports is the table it used,+a hash of it, and where the certificate is.++# The certificate++Three files land in `certificate_dir`:++* `rules.tsv`, the table the run evaluated. The checker is given this rather+ than the user's file, so what it checks and what ran are the same table.+* `asserted.tsv`, every triple the run started from.+* `horn.tsv`, one line per derived triple:+ `ruleIndex TAB bindCount TAB (var TAB term)* TAB cs TAB cp TAB co TAB (ps TAB pp TAB po)*`.++Steps are written in derivation order, and a step's premises are always facts+known before the round that derived it, so every premise is asserted or+concluded by an EARLIER line. That is the ordering `OOCert.checkHornAll`+requires, and it makes a self-citing step structurally impossible rather than+defended against.++Nothing is materialised into the store. A conclusion drawn under a supplied rule+table holds only in models that satisfy that table, and writing it in beside the+assertions is how run N's output becomes run N+1's axiom.+"""++from __future__ import annotations++import hashlib+from dataclasses import dataclass, field+from pathlib import Path+from typing import Iterator, Sequence++import pyoxigraph as ox++from .rules import (+ AtomPat,+ RulePattern,+ RuleTableError,+ builtin_rules,+ builtin_rules_bytes,+ is_var,+ parse_rules,+ rules_tsv,+ vars_of,+)+from .terms import checked_field, spell++INFERRED_GRAPH = "https://open-ontologies.org/graph/inferred"++OWL_INTERSECTION_OF = "<http://www.w3.org/2002/07/owl#intersectionOf>"+OWL_UNION_OF = "<http://www.w3.org/2002/07/owl#unionOf>"+OWL_ONE_OF = "<http://www.w3.org/2002/07/owl#oneOf>"++Fact = tuple[str, str, str]+++class AssertedGraphError(ValueError):+ """The asserted graph would have contained triples a reasoner derived."""+++@dataclass(frozen=True)+class HornStep:+ """One line of `horn.tsv`, before it is spelled out."""++ rule: int # 0-based index into rules.tsv; a rule's identity is its index+ binds: tuple[tuple[str, str], ...] # (BARE variable name, term spelling)+ conclusion: Fact+ premises: tuple[Fact, ...] # the rule body instantiated, IN DECLARED BODY ORDER+++@dataclass+class HornResult:+ """What the run did. No verdict: see the module docstring."""++ certificate_dir: str+ rules_count: int+ rules_source: str+ asserted_graphs: list[str]+ asserted_triples: int+ distinct_asserted_triples: int+ derived_triples: int+ iterations: int+ fixpoint_reached: bool+ skipped_unserialisable: int+ skipped_examples: list[str]+ quoted_triples: int+ by_rule: list[dict]+ sample_derivations: list[str]+ rules_tsv_sha256: str+ not_covered: dict | None = None+ incomplete: str | None = None+ steps: list[HornStep] = field(default_factory=list, repr=False, compare=False)++ def derived(self) -> set[Fact]:+ """The set of triples this run derived. The differential compares SETS."""+ return {st.conclusion for st in self.steps}++ def to_dict(self) -> dict:+ d = Path(self.certificate_dir)+ out: dict = {+ "mode": "horn",+ "engine": "open-ontologies-lite (pure Python)",+ "rules_source": self.rules_source,+ "rules": self.rules_count,+ "asserted_graphs": self.asserted_graphs,+ "asserted_triples": self.asserted_triples,+ "distinct_asserted_triples": self.distinct_asserted_triples,+ "derived_triples": self.derived_triples,+ "iterations": self.iterations,+ "fixpoint_reached": self.fixpoint_reached,+ "skipped_unserialisable": self.skipped_unserialisable,+ "quoted_triples": self.quoted_triples,+ **(+ {+ "quoted_triples_note": (+ "an asserted term is not a single N-Triples term, which under "+ "pyoxigraph 0.5 means an RDF-star quoted triple in object "+ "position. The certificate is still sound, because the checker "+ "treats the term as an opaque name, but asserted.tsv is no "+ "longer re-parsable as N-Triples and no rule can put such a "+ "term in predicate position"+ )+ }+ if self.quoted_triples+ else {}+ ),+ "materialized": False,+ "why_not_materialized": (+ "a conclusion drawn under a supplied rule table holds only in models that "+ "satisfy that table, so it is not written into the store beside the "+ "assertions. The certificate is the output of this run"+ ),+ "conditional_on": (+ f"the rules in {self.rules_source}, which this run ASSUMED and never checked. "+ f"A certificate is only as good as the table it cites: a rule saying every "+ f"supplier is compliant produces steps that check green for ever"+ ),+ "sample_derivations": self.sample_derivations,+ "certificate": {+ "dir": self.certificate_dir,+ "format": "oo-horn/1",+ "rules": self.rules_count,+ "rules_tsv_sha256": self.rules_tsv_sha256,+ "asserted": self.asserted_triples,+ "derivations": self.derived_triples,+ "by_rule": self.by_rule,+ "check_with": (+ f"oo-horn check {d / 'rules.tsv'} {d / 'asserted.tsv'} {d / 'horn.tsv'}"+ ),+ "pronounced_by": (+ "lean/, through `oo-horn check`, which decides what this run earned by "+ "comparing the table against the built-in one. This engine emits the "+ "certificate and states no verdict of its own"+ ),+ },+ }+ if self.skipped_unserialisable:+ out["skipped_examples"] = self.skipped_examples+ out["skipped_reason"] = (+ "the rule head instantiated to a triple no RDF serialiser can write (a "+ "literal in subject position, or a non-IRI in predicate position). Such "+ "conclusions are neither certified nor used as premises, so this run derives "+ "LESS than the table licenses"+ )+ if self.not_covered is not None:+ out["not_covered"] = self.not_covered+ if self.incomplete is not None:+ out["incomplete"] = self.incomplete+ return out+++# ---------------------------------------------------------------------------+# Facts+# ---------------------------------------------------------------------------+++def _graph_label(graph_name) -> str:+ """`str(DefaultGraph())` is the word DEFAULT, not an IRI, so it is renamed+ here to the same token `graphs=` accepts and nothing downstream has to know+ about pyoxigraph's spelling."""+ return "default" if isinstance(graph_name, ox.DefaultGraph) else str(graph_name)+++def _named_graph(name: str):+ """Accept a graph either bare (`http://x/g`) or in its N-Triples spelling+ (`<http://x/g>`), because a user reading `asserted_graphs` out of a previous+ report will paste back the spelled form."""+ if name == "default":+ return ox.DefaultGraph()+ iri = name[1:-1] if name.startswith("<") and name.endswith(">") else name+ return ox.NamedNode(iri)+++def _refuse_inferred(labels: Sequence[str], how: str) -> None:+ if any(lbl == f"<{INFERRED_GRAPH}>" for lbl in labels):+ raise AssertedGraphError(+ f"{how} would put <{INFERRED_GRAPH}> into asserted.tsv. That graph holds what a "+ f"reasoner DERIVED, and the soundness theorem is conditional on the assertions: a "+ f"certificate whose asserted set contains a previous run's conclusions certifies "+ f"entailment from a graph nobody asserted, and the checker cannot detect it "+ f"because it is TOLD what the assertions are. Reason over the graph you asserted, "+ f"or copy those triples into a graph of your own naming so the decision is visible"+ )+++def _facts(store, graphs) -> tuple[list[Fact], list[str]]:+ """Collect the asserted triples, and say which graphs they came from.++ The default is the DEFAULT GRAPH ALONE, which is where `OntologyEngine.load()`+ puts everything, so this package's own users lose nothing by it. The Rust+ engine flattens every named graph here (`src/reason.rs:1449`,+ `graph.all_triples()`), which is the defect above: a store holding a prior+ materialisation turns derived triples into assertions.+ """+ if graphs == "default":+ quads = list(store.quads_for_pattern(None, None, None, ox.DefaultGraph()))+ labels = ["default"]+ elif graphs == "all":+ quads = list(store)+ labels = sorted({_graph_label(q.graph_name) for q in quads})+ _refuse_inferred(labels, "graphs='all'")+ elif isinstance(graphs, str):+ raise ValueError(+ f"graphs={graphs!r} is neither 'default' nor 'all'. Pass a list to name graphs "+ f"explicitly"+ )+ else:+ wanted = list(graphs)+ if not wanted:+ raise ValueError("graphs=[] selects nothing, so there is no graph to reason over")+ labels = sorted({_graph_label(_named_graph(g)) for g in wanted})+ _refuse_inferred(labels, "naming that graph")+ quads = []+ for g in wanted:+ quads.extend(store.quads_for_pattern(None, None, None, _named_graph(g)))+ facts = [+ (+ spell(q.subject, "subject"),+ spell(q.predicate, "predicate"),+ spell(q.object, "object"),+ )+ for q in quads+ ]+ return facts, labels+++def is_atomic_term(term: str) -> bool:+ """True when this spelling is ONE N-Triples term rather than something else.++ An IRI is verified here rather than pattern-guessed: pyoxigraph's `NamedNode`+ refuses a space, a quote and a `>` outright ("Invalid IRI code point"), so an+ IRI that came out of a store is exactly `<`, no space, `>`. Anything else+ beginning with `<` came from somewhere that is not an IRI.++ The case that matters is an RDF-star quoted triple. Measured against+ pyoxigraph 0.5.9 and 0.5.11: a quoted triple is accepted in OBJECT position+ only, `Quad` refuses one in subject or predicate position with a TypeError,+ and its `str()` is `<s> <p> "v"` with RAW SPACES, NOT the `<<( ... )>>`+ spelling. So a `<<`-prefix test alone would check for something these+ versions never produce, and a bare `<`-prefix test would let the+ space-separated spelling through as a predicate.++ Both exclusions are kept, because neither subsumes the other and each is one+ comparison: the space test catches what pyoxigraph 0.5 actually writes, and+ the `<<` test catches the `<<( ... )>>` form other RDF-star tooling uses and+ a future pyoxigraph may adopt.+ """+ if term.startswith("_:") or term.startswith('"'):+ return True+ if term.startswith("<<"):+ return False+ return term.startswith("<") and term.endswith(">") and " " not in term+++def _serialisable(s: str, p: str) -> bool:+ """A rule head can instantiate to a literal in subject position or a non-IRI+ in predicate position. Lean will happily certify such a step, because it+ compares strings and has no RDF well-formedness notion, but no serialiser can+ write the triple. Refusing derives LESS, which is the sound direction.++ A non-atomic term in SUBJECT position is allowed through, because dropping an+ assertion is strictly worse than carrying one the checker treats as an opaque+ name, and an opaque name is still sound: `Interp.ι` maps any term string to a+ domain element. The report counts them, because such an `asserted.tsv` is no+ longer re-parsable as N-Triples.+ """+ return not s.startswith('"') and is_atomic_term(p) and p.startswith("<")+++# ---------------------------------------------------------------------------+# Matching+# ---------------------------------------------------------------------------+++def _join_order(body: Sequence[AtomPat]) -> tuple[int, ...]:+ """Choose the order body atoms are JOINED in.++ THIS IS NOT THE ORDER PREMISES ARE WRITTEN IN. `OOCert.checkHornStep` demands+ `st.premises = r.body.map (inst)`, the DECLARED body order, exactly; a+ certificate with the right triples in the wrong order is rejected. The two+ orders are separate on purpose and the emitter builds premises from+ `rule.body` directly, never from the order they were matched in. Anyone who+ "fixes" the premise list to match the join order will lose every certificate.++ Reordering is sound because the answers to a conjunctive query do not depend+ on join order, and it is worth doing because `rdfs2`, `rdfs3` and `rdfs7` all+ declare `?s ?p ?o` first, an atom with nothing fixed that scans every fact.+ Putting the selective atom first binds `?p` and the scan becomes an index+ lookup. The choice is static, so it is deterministic and the line order of+ `horn.tsv` is stable across runs.+ """+ remaining = list(range(len(body)))+ bound: set[str] = set()+ order: list[int] = []+ while remaining:+ best_i = remaining[0]+ best_score = _selectivity(body[best_i], bound)+ for i in remaining[1:]:+ score = _selectivity(body[i], bound)+ if score > best_score: # strict: ties keep the lower index+ best_i, best_score = i, score+ order.append(best_i)+ remaining.remove(best_i)+ for f in body[best_i].fields():+ if is_var(f):+ bound.add(f[1:])+ return tuple(order)+++def _selectivity(atom: AtomPat, bound: set[str]) -> tuple[int, int]:+ """How constrained this atom is once `bound` is known. Predicate first,+ because the predicate is the only position indexed."""++ def fixed(f: str) -> bool:+ return not is_var(f) or f[1:] in bound++ return (1 if fixed(atom.p) else 0, sum(1 for f in atom.fields() if fixed(f)))+++def _match_body(+ body: Sequence[AtomPat],+ order: Sequence[int],+ all_facts: Sequence[Fact],+ by_pred: dict[str, list[Fact]],+) -> Iterator[dict[str, str]]:+ """Backtracking join. Yields the SHARED environment dict, which the caller+ must read before asking for the next solution; every consumer here builds the+ binding tuple and the conclusion from it immediately."""+ env: dict[str, str] = {}++ def rec(k: int) -> Iterator[dict[str, str]]:+ if k == len(order):+ yield env+ return+ atom = body[order[k]]+ key = env.get(atom.p[1:]) if is_var(atom.p) else atom.p+ candidates = all_facts if key is None else by_pred.get(key, ())+ for fact in candidates:+ newly: list[str] = []+ ok = True+ for pat, value in zip(atom.fields(), fact):+ if is_var(pat):+ name = pat[1:]+ current = env.get(name)+ if current is None:+ env[name] = value+ newly.append(name)+ elif current != value:+ ok = False+ break+ elif pat != value:+ ok = False+ break+ if ok:+ yield from rec(k + 1)+ for name in newly:+ del env[name]++ yield from rec(0)+++def _inst(atom: AtomPat, env: dict[str, str]) -> Fact:+ return tuple(env[f[1:]] if is_var(f) else f for f in atom.fields()) # type: ignore[return-value]+++# ---------------------------------------------------------------------------+# The run+# ---------------------------------------------------------------------------+++def run_horn(+ store,+ rules: Sequence[RulePattern] | None = None,+ *,+ certificate_dir: str | Path,+ graphs: str | Sequence[str] = "default",+ max_iterations: int | None = None,+ rules_source: str | None = None,+) -> HornResult:+ """Derive the closure of a Horn rule table over `store` and write a+ certificate the proved-sound Lean checker in `lean/` verifies.++ `rules=None` means the shipped built-in table, whose bytes are written+ verbatim. That is the only table that can earn the absolute verdict, and only+ the Lean checker decides whether it did.++ `graphs="default"` asserts only the default graph. `"all"` flattens every+ graph the way the Rust engine does, and RAISES if the inferred graph is+ present.++ `max_iterations=None` runs to a genuine fixpoint. No cap is needed for+ termination: `parse_rules` refuses a head variable that does not occur in the+ body, so no rule can mint a term, the Herbrand base over the terms in the+ graph and the table is finite, and `known` grows monotonically. The cap+ exists as an opt-in memory guard, and a run that hits it reports `incomplete`+ because its derived count is then a lower bound and not the closure.+ """+ certificate_dir = Path(certificate_dir)+ if rules is None:+ table = list(builtin_rules())+ rules_bytes = builtin_rules_bytes()+ source = rules_source or "builtin"+ else:+ table = list(rules)+ if not table:+ raise RuleTableError(+ "the rule table holds no rules. An empty table derives nothing, so there is "+ "no certificate to write"+ )+ text = rules_tsv(table)+ # The checker verifies the steps against the FILE, and the run evaluated+ # the table in memory. If the rendering lost or changed anything the two+ # would be different rule sets, and a step would be checked against a+ # rule nobody ran.+ if parse_rules(text) != table:+ raise RuleTableError(+ "the rendered rule table does not parse back to the table that ran, so the "+ "certificate would be checked against different rules. Refusing to write it"+ )+ rules_bytes = text.encode("utf-8")+ source = rules_source or "supplied"+ if b"\r" in rules_bytes:+ raise RuleTableError(+ "the rule table carries a carriage return. HornParse splits on '\\n' alone, so a "+ "CR becomes part of a term"+ )++ facts, graph_labels = _facts(store, graphs)+ known: set[Fact] = set(facts)++ rule_vars = [tuple(vars_of(r.atoms())) for r in table]+ orders = [_join_order(r.body) for r in table]++ steps: list[HornStep] = []+ # A SET, not a counter. A refused conclusion never enters `known`, so every+ # later round matches the same body and re-derives it; a counter would report+ # attempts and grow with the iteration count, which is not what a reader takes+ # "skipped 2" to mean.+ refused: set[Fact] = set()+ skipped_examples: list[str] = []+ iterations = 0+ fixpoint = False++ while max_iterations is None or iterations < max_iterations:+ iterations += 1+ # Sorted so the candidate order, and therefore the order of the lines in+ # horn.tsv, does not depend on set iteration order. Python's string+ # hashing is randomised per process, so without this two runs over one+ # graph produce different bytes.+ all_facts = sorted(known)+ by_pred: dict[str, list[Fact]] = {}+ for f in all_facts:+ by_pred.setdefault(f[1], []).append(f)+ # by_pred is rebuilt INSIDE the loop, every round. Hoisting it is the+ # exact defect the CHANGELOG records against an earlier engine: "only the+ # rdf:type, rdfs:subClassOf and rdfs:subPropertyOf indices were rebuilt+ # each iteration ... a schema triple the reasoner itself derived was+ # never used".+ round_steps: list[HornStep] = []+ pending: set[Fact] = set()+ for ri, rule in enumerate(table):+ for env in _match_body(rule.body, orders[ri], all_facts, by_pred):+ conclusion = _inst(rule.head, env)+ if conclusion in known or conclusion in pending:+ continue+ if not _serialisable(conclusion[0], conclusion[1]):+ if conclusion not in refused:+ refused.add(conclusion)+ if len(skipped_examples) < 3:+ skipped_examples.append(" ".join(conclusion))+ continue+ pending.add(conclusion)+ round_steps.append(+ HornStep(+ rule=ri,+ binds=tuple((v, env[v]) for v in rule_vars[ri]),+ conclusion=conclusion,+ # Declared body order, never the join order.+ premises=tuple(_inst(a, env) for a in rule.body),+ )+ )+ if not round_steps:+ # Tests the ROUND list and not the refusal set: a graph that only+ # produces refusals terminates correctly on round two.+ fixpoint = True+ break+ # `known` is mutated ONLY here, at the end of the round. Body matching ran+ # against `all_facts`, the round's starting set, which is what makes every+ # premise of every step asserted-or-concluded on a strictly earlier line.+ # That is `checkHornAll`'s requirement, and it is why a self-citing step+ # is impossible rather than defended against.+ for st in round_steps:+ known.add(st.conclusion)+ steps.append(st)++ _write_certificate(certificate_dir, rules_bytes, facts, steps)++ by_rule_counts = [0] * len(table)+ for st in steps:+ by_rule_counts[st.rule] += 1+ return HornResult(+ certificate_dir=str(certificate_dir),+ rules_count=len(table),+ rules_source=source,+ asserted_graphs=graph_labels,+ asserted_triples=len(facts),+ distinct_asserted_triples=len(set(facts)),+ derived_triples=len(steps),+ iterations=iterations,+ fixpoint_reached=fixpoint,+ skipped_unserialisable=len(refused),+ skipped_examples=skipped_examples,+ # Asserted terms whose spelling is not one N-Triples term: in practice an+ # RDF-star quoted triple, which pyoxigraph 0.5 accepts in object position+ # and spells with raw spaces. Counted rather than dropped, and named in+ # the report, because the certificate stays sound (the checker treats the+ # term as an opaque name) while `asserted.tsv` stops being re-parsable as+ # N-Triples, and a reader is entitled to know which of those they have.+ quoted_triples=sum(1 for f in facts for t in f if not is_atomic_term(t)),+ by_rule=[+ {"index": i, "name": r.name, "derivations": by_rule_counts[i]}+ for i, r in enumerate(table)+ ],+ sample_derivations=[" ".join(st.conclusion) for st in steps[:10]],+ rules_tsv_sha256=hashlib.sha256(rules_bytes).hexdigest(),+ not_covered=_not_covered(facts),+ incomplete=None+ if fixpoint+ else (+ f"the run stopped at the {max_iterations}-iteration cap with rules still firing. "+ f"Every step in the certificate is still a step the checker can verify, but "+ f"derived_triples is a LOWER BOUND on the closure of this table, not the closure"+ ),+ steps=steps,+ )+++def _not_covered(facts: Sequence[Fact]) -> dict | None:+ """Say out loud where the Horn family stops.++ Silence here is the failure mode: a user diffs a Python derivation count+ against another engine, sees a gap and has no way to know which gap it is.+ """+ n = sum(+ 1 for f in facts if f[1] in (OWL_INTERSECTION_OF, OWL_UNION_OF, OWL_ONE_OF)+ )+ if n == 0:+ return None+ return {+ "rules": ["cls-int1", "cls-int2", "cls-uni", "cls-oo"],+ "constructor_triples_found": n,+ "why": (+ "these four read an RDF list off the graph, so the premise count is the list "+ "length, which is data. A RulePattern has a finite body, so they cannot be "+ "expressed in a Horn table at all. That is the boundary of the Horn family, not "+ "a gap in this engine. Covering them needs the oo-cert/1 format and its "+ "hardcoded arms"+ ),+ }+++def _write_certificate(+ certificate_dir: Path,+ rules_bytes: bytes,+ facts: Sequence[Fact],+ steps: Sequence[HornStep],+) -> None:+ """Write the three files.++ All three go out through `write_bytes` and never `open(path, "w")`: universal+ newline translation on Windows turns every LF into CRLF, `HornParse` splits on+ LF alone, and the resulting CR lands inside the last term of every line. The+ failure mode is "the reasoner found nothing", which reads as a data problem.+ """+ certificate_dir.mkdir(parents=True, exist_ok=True)+ (certificate_dir / "rules.tsv").write_bytes(rules_bytes)++ asserted = "".join(+ "\t".join(checked_field(t, "asserted.tsv term") for t in f) + "\n" for f in facts+ )+ # Store iteration order, unsorted and undeduplicated, mirroring the Rust+ # emitter. pyoxigraph's iteration is deterministic index order, so sorting+ # would buy no determinism and would gratuitously diverge from the reference.+ (certificate_dir / "asserted.tsv").write_bytes(asserted.encode("utf-8"))++ lines = []+ for st in steps:+ fields = [str(st.rule), str(len(st.binds))]+ for var, term in st.binds:+ # BARE, with no '?'. rules.tsv spells `?x`; horn.tsv spells `x`,+ # because `HornParse.patOf` strips the '?' when it parses the rule and+ # `substOf` looks the bare name up. A '?' here is rejected with exit 1+ # and a rejection JSON that names nothing at all.+ fields.append(checked_field(var, "horn.tsv binding variable"))+ fields.append(checked_field(term, "horn.tsv binding term"))+ for triple in (st.conclusion, *st.premises):+ fields.extend(checked_field(t, "horn.tsv triple term") for t in triple)+ lines.append("\t".join(fields))+ (certificate_dir / "horn.tsv").write_bytes(+ "".join(line + "\n" for line in lines).encode("utf-8")+ )diff --git a/python/src/open_ontologies_lite/horn/rules.py b/python/src/open_ontologies_lite/horn/rules.pynew file mode 100644index 00000000..7fcbd471--- /dev/null+++ b/python/src/open_ontologies_lite/horn/rules.py@@ -0,0 +1,217 @@+"""A Horn rule table, read and written as data.++Mirrors `OOCert.HornParse.parseRules` and `OOCert.HornParse.ruleStr` on the Lean+side and `open_ontologies::reason::parse_rules` on the Rust side. The format is++ name TAB bodyLength TAB (s TAB p TAB o)*bodyLength TAB hs TAB hp TAB ho++one rule per line, LF-terminated, where a field beginning with `?` is a variable+and anything else is a term in its N-Triples spelling. N-Triples terms begin with+`<`, `_:` or `"`, so the encoding is unambiguous and needs no escape layer.++This module imports no triple store. It is pure text and dataclasses, which is+what lets the rule table be tested without pyoxigraph and what keeps the+question "is this a well-formed rule?" separate from "what does this graph+entail?".++Two refusals go beyond what the Lean parser rejects, both because this side has+to PRODUCE bindings rather than check them, and both matching the Rust producer:+a head variable that does not occur in the body, and a carriage return.+"""++from __future__ import annotations++from dataclasses import dataclass+from functools import lru_cache+from importlib import resources+from typing import Sequence++from .terms import checked_field+++class RuleTableError(ValueError):+ """A rule table that cannot be parsed, or that a producer must refuse."""+++@dataclass(frozen=True)+class AtomPat:+ """A triple pattern. Each field is in the FILE's own encoding: a leading+ `?` means a variable, anything else is an N-Triples term. Keeping the raw+ spelling means a rule round-trips through `rules.tsv` unchanged, which is+ what `OOCert.HornParse.patOf` and `patStr` do on the Lean side. Predicate+ position may be a variable: `Interp` has one ternary extension, so a+ property is a domain element like any other and the language stays+ first-order."""++ s: str+ p: str+ o: str++ def fields(self) -> tuple[str, str, str]:+ return (self.s, self.p, self.o)+++@dataclass(frozen=True)+class RulePattern:+ """`forall vars. body -> head`, the quantifier left implicit."""++ name: str+ body: tuple[AtomPat, ...]+ head: AtomPat++ def atoms(self) -> tuple[AtomPat, ...]:+ return self.body + (self.head,)+++def is_var(pat: str) -> bool:+ """True when this pattern field is a variable.++ `parse_rules` refuses any constant not starting with `<`, `_:` or `"`, so a+ leading `?` is an exact test rather than a heuristic: no constant that+ survived parsing can begin with one.+ """+ return pat.startswith("?")+++def vars_of(atoms: Sequence[AtomPat]) -> list[str]:+ """Variable names in FIRST-OCCURRENCE order, scanning each atom s, p, o.++ This is the order `src/reason.rs` builds `CRule::vars` in, over+ `RulePattern::atoms()` (body atoms in order, then the head), and it is the+ order the binding list in `horn.tsv` is emitted in. The checker does not care+ about binding order, since `substOf` is a lookup, so this costs nothing and+ buys a diff against the Rust certificate that a human can read.+ """+ out: list[str] = []+ for a in atoms:+ for f in a.fields():+ if is_var(f):+ v = f[1:]+ if v not in out:+ out.append(v)+ return out+++def parse_rules(text: str) -> list[RulePattern]:+ """Parse a rule table. Malformed input names the line and what was wrong."""+ rules: list[RulePattern] = []+ for n, line in enumerate(text.split("\n"), start=1):+ if line == "":+ # `HornParse.parseRules` skips empty lines, so a trailing newline is+ # fine and a blank line in the middle is not an error either.+ continue+ if "\r" in line:+ raise RuleTableError(+ f"rules line {n}: the line contains a carriage return. HornParse splits on "+ f"'\\n' alone, so a CRLF file puts a '\\r' inside the last term of every line "+ f"and silently changes what that term is. Convert the file rather than have "+ f"it stripped here"+ )+ fields = line.split("\t")+ if len(fields) < 2:+ raise RuleTableError(+ f"rules line {n}: expected a name, a body length and then the patterns, got "+ f"{len(fields)} tab-separated field(s)"+ )+ name, count = fields[0], fields[1]+ if not name:+ raise RuleTableError(f"rules line {n}: the rule name is empty")+ checked_field(name, f"rules line {n} rule name")+ if not (count.isascii() and count.isdigit()):+ # `str.isdigit()` is true of '٣' and '²'; `int()` accepts the first+ # and would read a body length the Lean `toNat?` never would.+ raise RuleTableError(+ f"rules line {n}: body length {count!r} is not a decimal number"+ )+ m = int(count)+ rest = fields[2:]+ if len(rest) != 3 * m + 3:+ raise RuleTableError(+ f"rules line {n}: a body of {m} atom(s) plus a head needs {3 * m + 3} "+ f"pattern fields, got {len(rest)}"+ )+ for i, pat in enumerate(rest):+ _check_pattern(pat, n, i, m)+ body = tuple(+ AtomPat(rest[3 * i], rest[3 * i + 1], rest[3 * i + 2]) for i in range(m)+ )+ head = AtomPat(rest[3 * m], rest[3 * m + 1], rest[3 * m + 2])+ body_vars = set(vars_of(body))+ loose = [f[1:] for f in head.fields() if is_var(f) and f[1:] not in body_vars]+ if loose:+ raise RuleTableError(+ f"rules line {n}: rule {name!r} has head variable ?{loose[0]}, which does not "+ f"occur in the body. The checker accepts such a rule, because SatRule "+ f"quantifies over every substitution, but this engine has nothing to bind it "+ f"to and would have to invent a term. Refusing is the only honest option"+ )+ rules.append(RulePattern(name=name, body=body, head=head))+ return rules+++def _check_pattern(pat: str, line: int, index: int, body_len: int) -> None:+ which = (+ f"body atom {index // 3 + 1} position {index % 3 + 1}"+ if index < 3 * body_len+ else f"head position {index - 3 * body_len + 1}"+ )+ if is_var(pat):+ if len(pat) == 1:+ raise RuleTableError(+ f"rules line {line}: {which} is '?' with no variable name"+ )+ checked_field(pat, f"rules line {line} {which}")+ return+ if not (pat.startswith("<") or pat.startswith("_:") or pat.startswith('"')):+ raise RuleTableError(+ f"rules line {line}: {which} is {pat!r}, which is neither a variable (?x) nor an "+ f"N-Triples term (<iri>, _:blank, or a quoted literal). The store spells every "+ f"term in N-Triples, so a constant in any other spelling would match nothing and "+ f"the rule would silently never fire. That is a typo, not a rule"+ )+ checked_field(pat, f"rules line {line} {which}")+++def rules_tsv(rules: Sequence[RulePattern]) -> str:+ """Render a rule table back to `rules.tsv`.++ Byte-for-byte `OOCert.HornParse.ruleStr` per line, LF-terminated, so a table+ read here and written back out digests to the value it came in with. The+ fields are re-checked on the way out because a `RulePattern` can be built+ programmatically by a caller who never went through `parse_rules`.+ """+ lines = []+ for r in rules:+ fields = [checked_field(r.name, f"rule {r.name!r} name"), str(len(r.body))]+ for a in r.atoms():+ for f in a.fields():+ fields.append(checked_field(f, f"rule {r.name!r} pattern field"))+ lines.append("\t".join(fields))+ return "".join(line + "\n" for line in lines)+++def builtin_rules_bytes() -> bytes:+ """The vendored built-in table, as BYTES, to be written verbatim.++ Verbatim and not re-rendered: `lean/HMain.lean` decides which warrant a run+ earned by `tableLines R == tableLines Builtin.asHorn`, a full ordered+ equality over the canonical rendering of the whole table. Copying bytes+ removes every way a renderer could cost the absolute verdict.+ """+ return (+ resources.files("open_ontologies_lite.horn")+ .joinpath("tables/builtin_rules.tsv")+ .read_bytes()+ )+++@lru_cache(maxsize=1)+def builtin_rules() -> tuple[RulePattern, ...]:+ """The vendored built-in table, parsed, for matching against a graph.++ A rule's identity in a certificate is its INDEX, never its name: `scm-eqc1`+ occupies rows 11 and 12 and `scm-eqp1` rows 13 and 14, because each licenses+ two conclusions. There is deliberately no name-to-index map anywhere in this+ package; a `dict[str, int]` would silently lose one of each pair.+ """+ return tuple(parse_rules(builtin_rules_bytes().decode("utf-8")))diff --git a/python/src/open_ontologies_lite/horn/tables/README.md b/python/src/open_ontologies_lite/horn/tables/README.mdnew file mode 100644index 00000000..2754e58f--- /dev/null+++ b/python/src/open_ontologies_lite/horn/tables/README.md@@ -0,0 +1,38 @@+# `builtin_rules.tsv` is a copy, and the direction it can drift in matters++This file is a verbatim copy of `tests/fixtures/horn/builtin_rules.tsv` in the+repository root. The original is whatever `oo-horn rules` prints, which is+`OOCert.Builtin.asHorn` rendered by `OOCert.HornParse.ruleStr`, and+`tests/lean_horn_certificate_test.rs::the_built_in_rules_are_emitted_as_data`+pins the fixture to the checker.++It is copied rather than generated because `lean/HMain.lean` decides which+warrant a run earned by `tableLines R == tableLines Builtin.asHorn`, a full+ordered equality over the canonical rendering of the whole table. The emitter+therefore writes these bytes verbatim and never re-renders them: a renderer that+changed one byte would cost the absolute verdict, silently, and the run would+still look like a success.++A drifted copy can only weaken a verdict from the absolute one to the+relativised one, never strengthen one, because the comparison happens inside the+checker over the file it was handed. That is the safe direction, and it is also+a silent one, which is why `test_horn_checked.py` compares these bytes against+`oo-horn rules` and fails rather than skips on a mismatch, and why the report+carries `rules_table_drift` when they differ.++Do not edit this file. Copy the fixture again.++## Why this directory is called `tables` and not `data`++The repository's root `.gitignore` carries `data/` on line 3, with no leading+slash, so it matches a directory of that name at ANY depth. A vendored table+under `horn/data/` is therefore invisible to git: `uv build` would still produce+a working wheel on the machine that wrote the file, because hatchling reads the+filesystem, and a wheel built from a fresh clone or from CI would ship without+the table and raise `FileNotFoundError` on the first call to `builtin_rules()`.++The root `.gitignore` already carries four negation entries for exactly this+collision under `case-studies/`. Renaming is the version that needs no+coordination: it survives anyone regenerating that file, and it cannot be+re-broken by a change in a directory this package does not own. Do not rename it+back.diff --git a/python/src/open_ontologies_lite/horn/tables/builtin_rules.tsv b/python/src/open_ontologies_lite/horn/tables/builtin_rules.tsvnew file mode 100644index 00000000..19ffe87e--- /dev/null+++ b/python/src/open_ontologies_lite/horn/tables/builtin_rules.tsv@@ -0,0 +1,27 @@+rdfs2 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+rdfs3 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c ?o <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+rdfs5 2 ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?c ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?c+rdfs7 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?q ?s ?q ?o+rdfs9 2 ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?a ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?b+rdfs11 2 ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c+prp-trp 3 ?p <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#TransitiveProperty> ?x ?p ?y ?y ?p ?z ?x ?p ?z+prp-symp 2 ?p <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#SymmetricProperty> ?x ?p ?y ?y ?p ?x+prp-inv1 2 ?p <http://www.w3.org/2002/07/owl#inverseOf> ?q ?x ?p ?y ?y ?q ?x+prp-inv2 2 ?p <http://www.w3.org/2002/07/owl#inverseOf> ?q ?x ?q ?y ?y ?p ?x+eq-sym 1 ?a <http://www.w3.org/2002/07/owl#sameAs> ?b ?b <http://www.w3.org/2002/07/owl#sameAs> ?a+scm-eqc1 1 ?a <http://www.w3.org/2002/07/owl#equivalentClass> ?b ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b+scm-eqc1 1 ?a <http://www.w3.org/2002/07/owl#equivalentClass> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?a+scm-eqp1 1 ?a <http://www.w3.org/2002/07/owl#equivalentProperty> ?b ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?b+scm-eqp1 1 ?a <http://www.w3.org/2002/07/owl#equivalentProperty> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?a+cls-svf1 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#someValuesFrom> ?c ?x ?p ?y ?y <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r+cls-avf 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#allValuesFrom> ?c ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?y ?y <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+cls-hv1 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?v+cls-hv2 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x ?p ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r+scm-svf1 5 ?c1 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y1 ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p ?c2 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y2 ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p ?y1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?y2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-svf2 5 ?c1 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p1 ?c2 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-avf1 5 ?c1 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y1 ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p ?c2 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y2 ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p ?y1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?y2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-avf2 5 ?c1 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p1 ?c2 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?c2 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c1+scm-dom1 2 ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c1 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2 ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c2+scm-dom2 2 ?p2 <http://www.w3.org/2000/01/rdf-schema#domain> ?c ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#domain> ?c+scm-rng1 2 ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c1 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2 ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c2+scm-rng2 2 ?p2 <http://www.w3.org/2000/01/rdf-schema#range> ?c ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#range> ?cdiff --git a/python/src/open_ontologies_lite/horn/terms.py b/python/src/open_ontologies_lite/horn/terms.pynew file mode 100644index 00000000..b79f3e71--- /dev/null+++ b/python/src/open_ontologies_lite/horn/terms.py@@ -0,0 +1,63 @@+"""The one place a term becomes a certificate field.++The Lean parsers do nothing but split on tab and newline. There is no quoting+layer, no length prefix and no escape pass: ``OOCert.HornParse.parseHornSteps``+calls ``line.splitOn "\\t"`` and reads the fields off by position. It relies on+the fact that an N-Triples term cannot contain a raw tab or newline, because the+serialisation escapes them. That invariant is the format's entire safety+argument, so it is asserted here on every field of every line rather than+assumed, and a violation aborts the run instead of writing a file.++A raw tab inside a bound term shifts every later field of a ``horn.tsv`` line by+one. ``rest.take (2 * k)`` then grabs the wrong fields, the conclusion is read+from the wrong positions, and the checker verifies something that is not what+the engine derived. That is the difference between a format and an attack+surface, and it is why this module exists at all rather than the emitter calling+``str()`` at six different places.+"""++from __future__ import annotations++FORBIDDEN = ("\t", "\n", "\r")+++class CertificateFieldError(ValueError):+ """A term or rule field carried a separator. The run stops here."""+++def checked_field(text: str, where: str) -> str:+ """Return ``text`` if it can be a certificate field; raise otherwise."""+ for ch in FORBIDDEN:+ if ch in text:+ raise CertificateFieldError(+ f"{where}: the field contains {ch!r}, which is the certificate's "+ f"field or record separator. A term reaching here must already be "+ f"in N-Triples spelling, where tab, newline and carriage return "+ f"are escaped. Field was {text!r}"+ )+ return text+++def spell(term, where: str) -> str:+ """The N-Triples spelling of a pyoxigraph term.++ ``str()`` and nothing else. pyoxigraph delegates to oxrdf's Display, which is+ the same code the Rust engine's ``quad.subject.to_string()`` goes through, so+ byte-compatibility with the Lean parser is structural rather than a Python+ re-implementation that can drift.++ Never ``.value``: that is the UNQUOTED lexical form. ``ox.Literal('a\\tb').value``+ returns a string with a RAW tab in it, and an IRI's ``.value`` loses its angle+ brackets, so the field starts with none of ``<``, ``_:`` or ``"`` and matches+ nothing the store holds. ``engine.py``'s ``_terms()`` and ``query()`` use+ ``.value`` for display, and ``dataframe.py``'s ``_literal`` escapes backslash,+ quote and newline but neither tab nor carriage return; none of that code may be+ reused on this path, and the type refusal below is what stops it being.+ """+ if isinstance(term, str):+ raise TypeError(+ f"{where}: spell() takes a pyoxigraph term, not a str. A string that "+ f"is already a spelling goes through checked_field(); a string that is "+ f"not must be parsed into a term first, never formatted into one"+ )+ return checked_field(str(term), where)diff --git a/python/src/open_ontologies_lite/server.py b/python/src/open_ontologies_lite/server.pyindex 40145d1c..3bc60bc9 100644--- a/python/src/open_ontologies_lite/server.py+++ b/python/src/open_ontologies_lite/server.py@@ -93,6 +93,31 @@ def onto_lint() -> dict:return _engine.lint()+def onto_reason(+ certificate_dir: str, rules_file: str | None = None, check: bool = True+) -> dict:+ """Derive the closure of a Horn rule table over the loaded store and write a+ certificate the proved-sound Lean checker verifies.++ With no `rules_file` this runs the BUILT-IN table, the only table that can+ earn the absolute verdict. Pass `rules_file` to run a table you wrote: those+ rules are ASSUMED and never checked, so a certificate over them holds only in+ models of the asserted graph that ALSO satisfy your rules. A rule saying+ every supplier is compliant produces certificates that check green for ever.++ The verdict comes from that checker and not from here, because rules you+ supply are assumed and never checked. If the checker is not installed the+ report says so under `check`, names the binary and how to build it, and+ carries no verdict at all.++ Nothing is materialised into the store: the certificate is the output of the+ run. Only the default graph is asserted, so a previous run's inferences+ cannot be read back in as assertions.+ """+ return _engine.reason_horn(certificate_dir, rules=rules_file, check=check)++@mcp.tool()def onto_kgcl_diff(data_a: str, data_b: str, format: str = "turtle") -> dict:"""Classify the change from version A to B as KGCL change records.diff --git a/python/tests/test_horn_certificate_bytes.py b/python/tests/test_horn_certificate_bytes.pynew file mode 100644index 00000000..ac4f3511--- /dev/null+++ b/python/tests/test_horn_certificate_bytes.py@@ -0,0 +1,268 @@+"""The certificate format is a field-position format, so this is the forgery test.++CI has no Lean binary. Everything the Lean checker would catch about a MALFORMED+certificate therefore has to be caught here, and this file is where the format is+held to its contract byte by byte.++The Lean parsers do nothing but split on tab and newline and read the fields off+by position. There is no quoting layer and no escape pass. A raw tab inside a+bound term shifts every later field of a `horn.tsv` line by one: `rest.take (2*k)`+grabs the wrong fields, the conclusion is read from the wrong positions, and the+checker verifies something that is not what the engine derived. A serialiser that+gets that wrong is not a cosmetic bug, it is a place where a derivation step can+be forged, so the store below is built deliberately full of terms that would+break a naive emitter: a literal with a real tab, a real newline, a real carriage+return, a quote, a backslash, a language tag and a datatype.++The last test in the file is the one that no amount of inspecting the certificate+could replace. An emitter that wrote `.value` instead of `str()` produces a+certificate that is internally CONSISTENT: every line has the right field count,+every premise matches its rule, and `oo-horn` accepts it and reports the absolute+verdict about a graph that is not the graph anyone loaded. The only way to catch+it is to parse `asserted.tsv` back into terms and compare with the store.+"""++import pyoxigraph as ox+import pytest++from open_ontologies_lite.horn.reason import run_horn+from open_ontologies_lite.horn.rules import builtin_rules+from open_ontologies_lite.horn.terms import CertificateFieldError, spell++NASTY = """+@prefix ex: <http://ex.org/> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .++ex:A rdfs:subClassOf ex:B .+ex:B rdfs:subClassOf ex:C .+ex:a a ex:A .+ex:label rdfs:domain ex:A ; rdfs:range ex:Text .+ex:a ex:label "tab\\there and nl\\nhere and cr\\rhere and quote\\"here and bs\\\\here" .+ex:a ex:label "lang tagged"@en-GB .+ex:a ex:label "42"^^xsd:integer .+_:blank a ex:A .+"""+++def _load():+ store = ox.Store()+ store.load(NASTY.encode("utf-8"), format=ox.RdfFormat.TURTLE)+ return store+++def test_every_line_of_every_file_splits_into_the_field_count_the_parser_expects(tmp_path):+ result = run_horn(_load(), certificate_dir=tmp_path)+ table = builtin_rules()++ rules_lines = (tmp_path / "rules.tsv").read_text("utf-8").split("\n")[:-1]+ assert len(rules_lines) == len(table)+ for line, rule in zip(rules_lines, table):+ fields = line.split("\t")+ assert fields[1] == str(len(rule.body))+ assert len(fields) - 2 == 3 * len(rule.body) + 3++ for line in (tmp_path / "asserted.tsv").read_text("utf-8").split("\n")[:-1]:+ assert len(line.split("\t")) == 3++ horn_lines = (tmp_path / "horn.tsv").read_text("utf-8").split("\n")[:-1]+ assert len(horn_lines) == result.derived_triples+ for line in horn_lines:+ fields = line.split("\t")+ index, binds = int(fields[0]), int(fields[1])+ rest = fields[2:]+ # This is `parseHornSteps`' arithmetic: 2*k binding fields, then a+ # conclusion, then whole triples for the body of the cited rule.+ assert len(rest) == 2 * binds + 3 + 3 * len(table[index].body)+++def test_no_field_anywhere_carries_a_separator(tmp_path):+ run_horn(_load(), certificate_dir=tmp_path)+ for name in ("rules.tsv", "asserted.tsv", "horn.tsv"):+ raw = (tmp_path / name).read_bytes()+ assert b"\r" not in raw, f"{name} carries a CR; HornParse splits on LF alone"+ assert raw == b"" or raw.endswith(b"\n"), f"{name} does not end with a newline"+ for line in raw.decode("utf-8").split("\n")[:-1]:+ for field in line.split("\t"):+ assert "\t" not in field and "\n" not in field and "\r" not in field+++def test_binding_variables_are_written_bare_with_no_question_mark(tmp_path):+ """`rules.tsv` spells `?x` and `horn.tsv` spells `x`, because `patOf` strips+ the '?' when it parses the rule and `substOf` looks the bare name up. Getting+ this wrong is exit 1 with a rejection JSON that names nothing at all: no+ diagnostic, no first-rejected index. It is the likeliest emitter bug and the+ one with the worst debugging experience, so it gets its own test."""+ run_horn(_load(), certificate_dir=tmp_path)+ for line in (tmp_path / "horn.tsv").read_text("utf-8").split("\n")[:-1]:+ fields = line.split("\t")+ binds = int(fields[1])+ for i in range(binds):+ var = fields[2 + 2 * i]+ assert not var.startswith("?"), f"binding variable {var!r} carries a '?'"+ assert var != ""+++def test_each_step_cites_its_rule_body_instantiated_in_body_order(tmp_path):+ """`checkHornStep` demands `st.premises = r.body.map (inst)`: the DECLARED+ body order, exactly. The engine is free to JOIN the atoms in any order it+ likes, and does, so this is the assertion that keeps the two apart. A+ certificate with the right triples in the wrong order is rejected."""+ result = run_horn(_load(), certificate_dir=tmp_path)+ table = builtin_rules()+ assert result.derived_triples > 0+ for step in result.steps:+ rule = table[step.rule]+ env = dict(step.binds)+ expected = tuple(+ tuple(env[f[1:]] if f.startswith("?") else f for f in atom.fields())+ for atom in rule.body+ )+ assert step.premises == expected+ head = rule.head+ assert step.conclusion == tuple(+ env[f[1:]] if f.startswith("?") else f for f in head.fields()+ )+++def test_every_premise_was_asserted_or_concluded_on_an_earlier_line(tmp_path):+ """`checkHornAll`'s requirement, and the reason a step cannot cite itself.+ Asserting it here means the property is tested even where Lean cannot run."""+ result = run_horn(_load(), certificate_dir=tmp_path)+ known = {+ tuple(line.split("\t"))+ for line in (tmp_path / "asserted.tsv").read_text("utf-8").split("\n")[:-1]+ }+ for step in result.steps:+ for premise in step.premises:+ assert premise in known, f"{premise} is cited before it is known"+ assert step.conclusion not in known, "a step re-derives something already known"+ known.add(step.conclusion)+++def test_the_asserted_file_reparses_into_exactly_the_graph_that_was_loaded(tmp_path):+ """The `.value` disaster, and nothing that only inspects the certificate can+ catch it. An emitter using the unquoted lexical form writes a certificate+ that is internally consistent and that `oo-horn` ACCEPTS, reporting the+ absolute verdict about a graph nobody loaded."""+ store = _load()+ run_horn(store, certificate_dir=tmp_path)+ text = (tmp_path / "asserted.tsv").read_text("utf-8")+ ntriples = "".join(+ line.replace("\t", " ") + " .\n" for line in text.split("\n")[:-1]+ )+ reparsed = {+ (str(t.subject), str(t.predicate), str(t.object))+ for t in ox.parse(ntriples.encode("utf-8"), format=ox.RdfFormat.N_TRIPLES)+ }+ loaded = {+ (str(q.subject), str(q.predicate), str(q.object))+ for q in store.quads_for_pattern(None, None, None, ox.DefaultGraph())+ }+ # Blank-node labels are scoped to a parse, so compare the shape of each+ # triple with blank labels normalised away rather than the labels themselves.+ def norm(triples):+ return sorted(+ tuple("_:_" if t.startswith("_:") else t for t in triple)+ for triple in triples+ )++ assert norm(reparsed) == norm(loaded)+++def test_the_field_guard_refuses_a_term_carrying_a_tab():+ """pyoxigraph will never trip this: its N-Triples spelling escapes tab,+ newline and CR, and NamedNode refuses a tab outright. An untested guard is a+ guard someone deletes, so it is driven here by a hand-built fake term."""++ class ForgedTerm:+ def __str__(self):+ return '<http://ex.org/a>\t<http://ex.org/p>\t"forged"'++ with pytest.raises(CertificateFieldError, match="separator"):+ spell(ForgedTerm(), "subject")+++def test_spell_refuses_a_string_because_a_spelling_is_not_a_term():+ """`.value` returns a str, and so does every display path in engine.py. The+ type refusal is what stops that code being reused on this path."""+ with pytest.raises(TypeError, match="not a str"):+ spell("http://ex.org/a", "subject")+++def test_a_literal_in_subject_position_is_refused_rather_than_written(tmp_path):+ """`eq-sym` over an owl:sameAs whose subject is a literal instantiates a head+ no serialiser can write. Lean would certify the step, because it compares+ strings and has no RDF well-formedness notion. Refusing derives LESS, which+ is the sound direction, and the count says so out loud."""+ store = ox.Store()+ store.load(+ b'<http://ex.org/a> <http://www.w3.org/2002/07/owl#sameAs> "a literal" .',+ format=ox.RdfFormat.N_TRIPLES,+ )+ result = run_horn(store, certificate_dir=tmp_path)+ assert result.skipped_unserialisable == 1+ assert result.derived_triples == 0+ assert result.skipped_examples+ assert (tmp_path / "horn.tsv").read_bytes() == b""+++def test_an_rdf_star_quoted_triple_is_carried_and_counted_not_dropped(tmp_path):+ """Measured against pyoxigraph 0.5.9 and 0.5.11, and pinned because the+ behaviour decides the shape of the serialisability guard.++ A quoted triple is accepted in OBJECT position only; `Quad` refuses one in+ subject or predicate position outright. Its `str()` is `<s> <p> "v"` with RAW+ SPACES, and NOT the `<<( ... )>>` spelling, so a guard keyed on a `<<` prefix+ would be checking for something these versions never produce while a bare+ `<`-prefix test would admit the space-separated spelling as a predicate.++ Carrying it is the right call: it contains no separator, so it occupies one+ field, the checker treats it as an opaque name and soundness is unaffected.+ Dropping it would silently remove an assertion. What it does cost is that+ `asserted.tsv` stops being re-parsable as N-Triples, which is why the count+ and the note exist.+ """+ quoted = ox.Triple(+ ox.NamedNode("http://ex.org/a"),+ ox.NamedNode("http://ex.org/p"),+ ox.Literal("v"),+ )+ with pytest.raises(TypeError):+ ox.Quad(quoted, ox.NamedNode("http://ex.org/q"), ox.NamedNode("http://ex.org/c"))+ with pytest.raises(TypeError):+ ox.Quad(ox.NamedNode("http://ex.org/a"), quoted, ox.NamedNode("http://ex.org/c"))++ store = ox.Store()+ store.add(ox.Quad(ox.NamedNode("http://ex.org/a"), ox.NamedNode("http://ex.org/q"), quoted))+ store.load(+ b"<http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> "+ b"<http://ex.org/A> .\n"+ b"<http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> "+ b"<http://ex.org/B> .",+ format=ox.RdfFormat.N_TRIPLES,+ )+ result = run_horn(store, certificate_dir=tmp_path)+ report = result.to_dict()+ assert report["quoted_triples"] == 1+ assert "no longer re-parsable as N-Triples" in report["quoted_triples_note"]+ assert " " in str(quoted) and not str(quoted).startswith("<<")+ # The term is carried, in one field, with no separator in it.+ lines = (tmp_path / "asserted.tsv").read_text("utf-8").split("\n")[:-1]+ carried = [line for line in lines if line.endswith(str(quoted))]+ assert len(carried) == 1+ assert len(carried[0].split("\t")) == 3+ # And the rest of the run is unaffected.+ assert result.derived_triples == 1+++def test_a_non_atomic_term_can_never_reach_predicate_position():+ from open_ontologies_lite.horn.reason import _serialisable, is_atomic_term++ spelling = '<http://ex.org/a> <http://ex.org/p> "v"'+ assert not is_atomic_term(spelling)+ assert not _serialisable("<http://ex.org/s>", spelling)+ assert not _serialisable("<http://ex.org/s>", "<<(x)>>")+ assert _serialisable("<http://ex.org/s>", "<http://ex.org/p>")+ assert not _serialisable('"a literal"', "<http://ex.org/p>")+ assert _serialisable("_:b0", "<http://ex.org/p>")diff --git a/python/tests/test_horn_checked.py b/python/tests/test_horn_checked.pynew file mode 100644index 00000000..4f947646--- /dev/null+++ b/python/tests/test_horn_checked.py@@ -0,0 +1,348 @@+"""The Lean checker's verdict on certificates this package produced.++GATED on `oo-horn`. It skips loudly, naming the binary and how to build it,+because CI installs `[dev]` and nothing else: no elan, no `lake`. A green tick on+that job says the unchecked path is fine and says NOTHING about whether a single+certificate has ever been accepted, and pretending otherwise is the failure this+whole layer exists to prevent. Run `cd lean && lake build` and these run.++Four things are established here and nowhere else.++1. A certificate this Python engine wrote is ACCEPTED by the proved-sound checker+ and earns the absolute verdict, because the table it cites is the built-in one+ byte for byte.+2. A certificate over a table with one extra rule earns the RELATIVISED verdict+ instead, names a different theorem, and reports a different digest. The rule+ appended below says every supplier is compliant, which is true of nothing and+ checks green for ever; that is the point. If this test ever reports the+ absolute word, the layer has become a machine for turning an assumption into a+ fact with a proof attached.+3. Every forgery is REJECTED. A gate that cannot fail is decoration, so the+ certificates below are mutated five ways after being written, on top of the+ six committed fixtures, and each must come back rejected with no verdict.+4. A read or parse error is NOT a rejection. Exit 2 and exit 1 mean different+ things and are never folded together, because folding them is how an emitter+ bug gets mistaken for an uninstalled checker and never investigated.+"""+++import shutil+import subprocess+from pathlib import Path++import pyoxigraph as ox+import pytest++from open_ontologies_lite import OntologyEngine+from open_ontologies_lite.horn.certify import CheckerUnavailable, check_horn, find_checker+from open_ontologies_lite.horn.reason import run_horn+from open_ontologies_lite.horn.rules import (+ AtomPat,+ RulePattern,+ builtin_rules,+ builtin_rules_bytes,+)++TYPE = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"+SUPPLIER = "<http://ex.org/Supplier>"+COMPLIANT = "<http://ex.org/Compliant>"++ONT = """+@prefix ex: <http://ex.org/> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+ex:A rdfs:subClassOf ex:B . ex:B rdfs:subClassOf ex:C .+ex:a a ex:A .+ex:acme a ex:Supplier .+ex:knows a owl:SymmetricProperty . ex:a ex:knows ex:b .+ex:p rdfs:domain ex:A ; rdfs:range ex:B . ex:x ex:p ex:y .+"""++EVERY_SUPPLIER_IS_COMPLIANT = RulePattern(+ name="every-supplier-is-compliant",+ body=(AtomPat("?s", TYPE, SUPPLIER),),+ head=AtomPat("?s", TYPE, COMPLIANT),+)+++def _checker() -> Path:+ try:+ return find_checker("oo-horn")+ except CheckerUnavailable as exc:+ pytest.skip(str(exc))+++def _store() -> ox.Store:+ s = ox.Store()+ s.load(ONT.encode("utf-8"), format=ox.RdfFormat.TURTLE)+ return s+++def _fixtures() -> Path:+ d = Path(__file__).resolve().parents[2] / "tests" / "fixtures" / "horn"+ if not d.is_dir():+ pytest.skip(f"not in a repository checkout: {d} is absent")+ return d+++def test_the_built_in_table_earns_the_absolute_verdict(tmp_path):+ """THE test. A certificate produced by the PYTHON reasoner, accepted by the+ LEAN checker, over the table `Builtin.asHorn_sound` discharges."""+ _checker()+ result = run_horn(_store(), certificate_dir=tmp_path)+ assert result.derived_triples > 0+ outcome = check_horn(tmp_path)+ assert outcome["status"] == "accepted"+ assert outcome["checked"] is True+ assert outcome["verdict"] == "entailed"+ assert outcome["theorem"] == "OOCert.entails_of_builtin_horn"+ assert outcome["digests_agree"] is True+ assert outcome["vacuous"] is False+ assert outcome["derivations"] == result.derived_triples+ assert "consistency_warning" not in outcome+++def test_a_user_rule_never_earns_the_absolute_verdict(tmp_path):+ """The Python mirror of `tests/lean_horn_certificate_test.rs`' test of the+ same name. The table is the built-ins PLUS ONE ROW, which is still not the+ built-in table, and the rule it adds is false of the world."""+ _checker()+ table = list(builtin_rules()) + [EVERY_SUPPLIER_IS_COMPLIANT]+ result = run_horn(_store(), table, certificate_dir=tmp_path)+ assert any(+ conclusion[2] == COMPLIANT for conclusion in result.derived()+ ), "the appended rule must actually fire, or this proves nothing"+ outcome = check_horn(tmp_path)+ assert outcome["status"] == "accepted"+ assert outcome["verdict"] == "entailed_under_supplied_rules"+ assert outcome["theorem"] == "OOCert.horn_certificate_sound"+ assert "assumed, not checked" in outcome["means"]+ assert outcome["digests_agree"] is False+ assert outcome["rules_digest"] != outcome["builtin_rules_digest"]+++def test_dropping_one_built_in_rule_also_loses_the_absolute_verdict(tmp_path):+ """A SUBSET of the built-ins is not the built-in table either. `HMain.lean`+ compares the whole rendering in order, so this is a full equality and not a+ containment, and a user who prunes the table for speed must be told."""+ _checker()+ table = list(builtin_rules())[:10]+ run_horn(_store(), table, certificate_dir=tmp_path)+ outcome = check_horn(tmp_path)+ assert outcome["status"] == "accepted"+ assert outcome["verdict"] == "entailed_under_supplied_rules"+ assert outcome["digests_agree"] is False+++def test_a_certificate_with_no_derivations_is_reported_as_vacuous(tmp_path):+ """An empty `horn.tsv` is accepted with the absolute verdict and zero+ derivations, and the checker is right: vacuously, every step in an empty list+ holds. The Python report would be what was wrong, so the count travels beside+ the verdict and `vacuous` says so in one word."""+ _checker()+ empty = ox.Store()+ result = run_horn(empty, certificate_dir=tmp_path)+ assert result.derived_triples == 0+ outcome = check_horn(tmp_path)+ assert outcome["status"] == "accepted"+ assert outcome["vacuous"] is True+ assert outcome["derivations"] == 0+++def test_every_committed_forgery_fixture_is_rejected():+ """The six certificates in `tests/fixtures/horn/` are the repository's own+ adversarial cases: a wrong conclusion, a rule index off the end of the table,+ a premise that was never asserted, a step citing its own conclusion, and a+ binding that does not instantiate the body."""+ _checker()+ fixtures = _fixtures()+ for bad in (+ "bad_conclusion",+ "bad_index",+ "bad_premise",+ "bad_self",+ "bad_binding",+ ):+ outcome = _check_files(+ fixtures / "builtin_rules.tsv",+ fixtures / "asserted.tsv",+ fixtures / f"{bad}.tsv",+ )+ assert outcome["status"] == "rejected", f"{bad} was not rejected"+ assert outcome["checked"] is True+ assert outcome["verdict"] is None+ assert "establishes nothing" in outcome["means"]+++def test_a_rule_index_past_a_short_table_is_rejected():+ """`short_rules.tsv` holds three rules and `good.tsv` cites index 4. The same+ certificate is accepted against the full table, so this isolates the index+ check rather than testing the certificate."""+ _checker()+ fixtures = _fixtures()+ short = _check_files(+ fixtures / "short_rules.tsv", fixtures / "asserted.tsv", fixtures / "good.tsv"+ )+ assert short["status"] == "rejected"+ full = _check_files(+ fixtures / "builtin_rules.tsv", fixtures / "asserted.tsv", fixtures / "good.tsv"+ )+ assert full["status"] == "accepted"+++MUTATIONS = {+ # Each rewrites one field of a freshly emitted, freshly accepted certificate.+ "a forged conclusion": lambda f: _swap(f, 5, "<http://ex.org/FORGED>"),+ "a premise that was never asserted": lambda f: _swap(f, 8, "<http://ex.org/ghost>"),+ "a rule index off the end of the table": lambda f: _swap(f, 0, "99"),+ "a binding that does not instantiate the body": lambda f: _swap(+ f, 3, "<http://ex.org/WRONG>"+ ),+ "a binding variable that kept its question mark": lambda f: _swap(+ f, 2, "?" + f[2]+ ),+}+++def test_every_mutation_of_an_accepted_certificate_is_rejected(tmp_path):+ """The fixtures above are static. These mutate a certificate this engine+ produced MOMENTS AGO and that the checker has just accepted, which is the+ only way to be sure the acceptance was not an accident of the fixture."""+ _checker()+ run_horn(_store(), certificate_dir=tmp_path)+ assert check_horn(tmp_path)["status"] == "accepted"+ original = (tmp_path / "horn.tsv").read_text("utf-8")+ first, rest = original.split("\n", 1)++ for label, mutate in MUTATIONS.items():+ fields = first.split("\t")+ (tmp_path / "horn.tsv").write_text(+ "\t".join(mutate(fields)) + "\n" + rest, encoding="utf-8"+ )+ outcome = check_horn(tmp_path)+ assert outcome["status"] == "rejected", f"{label} was not rejected"+ assert outcome["verdict"] is None+ assert outcome["checked"] is True+ (tmp_path / "horn.tsv").write_text(original, encoding="utf-8")+++def test_a_step_that_cites_its_own_conclusion_is_rejected(tmp_path):+ """Structurally impossible for this engine to emit, because `known` is only+ mutated at the end of a round. Forged by hand here so the property is tested+ and not merely argued."""+ _checker()+ run_horn(_store(), certificate_dir=tmp_path)+ lines = (tmp_path / "horn.tsv").read_text("utf-8").split("\n")[:-1]+ fields = lines[0].split("\t")+ binds = int(fields[1])+ conclusion_at = 2 + 2 * binds+ conclusion = fields[conclusion_at : conclusion_at + 3]+ # Replace the first premise with the step's own conclusion.+ fields[conclusion_at + 3 : conclusion_at + 6] = conclusion+ (tmp_path / "horn.tsv").write_text(+ "\n".join(["\t".join(fields)] + lines[1:]) + "\n", encoding="utf-8"+ )+ outcome = check_horn(tmp_path)+ assert outcome["status"] == "rejected"+ assert outcome["verdict"] is None+++def test_an_unreadable_file_is_not_a_rejection(tmp_path):+ """Exit 2 against exit 1. A missing or unparseable file means the checker+ could not read what it was given; it does not mean a step was rejected, and+ the two must never share a status word."""+ _checker()+ run_horn(_store(), certificate_dir=tmp_path)+ (tmp_path / "horn.tsv").unlink()+ outcome = check_horn(tmp_path)+ assert outcome["status"] == "unreadable"+ assert outcome["checked"] is False+ assert outcome["verdict"] is None+ assert "cannot read" in outcome["error"]+ assert "exit 2" in outcome["means"]+++def test_the_engine_raises_when_the_checker_cannot_read_what_it_just_wrote(+ tmp_path, monkeypatch+):+ """`check_horn` is a library primitive over a directory it did not+ necessarily write, so it returns the negative in the package's+ `ValidationResult(ok=False, error=...)` idiom. `reason_horn` wrote the three+ files itself, so the same outcome is an emitter bug and must stop the run+ rather than be reported as one more unchecked state.++ The unreadable outcome is injected, because an emitter that can produce one+ on demand is a bug this suite would rather not have. The injected value is+ the real thing: `check_horn` against a certificate with a mangled+ `asserted.tsv`, produced a few lines above."""+ from open_ontologies_lite import CertificateUnreadable+ from open_ontologies_lite.horn import certify++ _checker()+ engine = OntologyEngine()+ engine.load(ONT, "turtle")+ engine.reason_horn(str(tmp_path / "real"), check=False)+ (tmp_path / "real" / "asserted.tsv").write_text(+ "not\ta\ttriple\tat\tall\n", encoding="utf-8"+ )+ genuine = check_horn(tmp_path / "real")+ assert genuine["status"] == "unreadable"++ monkeypatch.setattr(certify, "check_horn", lambda *a, **k: genuine)+ with pytest.raises(CertificateUnreadable, match="emitter"):+ engine.reason_horn(str(tmp_path / "again"))+++def test_a_malformed_rule_table_is_unreadable_and_not_a_rejection(tmp_path):+ _checker()+ run_horn(_store(), certificate_dir=tmp_path)+ (tmp_path / "rules.tsv").write_text("garbage\tnotanumber\n", encoding="utf-8")+ outcome = check_horn(tmp_path)+ assert outcome["status"] == "unreadable"+ assert outcome["verdict"] is None+++def test_the_vendored_table_is_what_oo_horn_prints():+ """A drifted copy can only weaken a verdict from the absolute one to the+ relativised one, which is the safe direction and also a silent one. This+ FAILS rather than skips, because a silent weakening is precisely the thing a+ skip would let through."""+ checker = _checker()+ proc = subprocess.run([str(checker), "rules"], capture_output=True)+ assert proc.returncode == 0, proc.stderr.decode()+ assert proc.stdout == builtin_rules_bytes(), (+ "the vendored tables/builtin_rules.tsv has drifted from what oo-horn prints. "+ "Every run over the built-in table now earns the relativised verdict instead "+ "of the absolute one, silently. Re-copy tests/fixtures/horn/builtin_rules.tsv"+ )+++def test_the_environment_variable_points_at_the_checker(tmp_path, monkeypatch):+ """`OO_HORN` is the documented escape hatch, and the warning text tells users+ to set it, so it had better work."""+ checker = _checker()+ staged = tmp_path / "oo-horn"+ shutil.copy2(checker, staged)+ monkeypatch.setenv("OO_HORN", str(staged))+ assert find_checker("oo-horn") == staged+ monkeypatch.setenv("OO_HORN", str(tmp_path / "absent"))+ # A missing environment binary falls through to the repo and PATH, matching+ # the Rust precedent; an explicit path does not.+ assert find_checker("oo-horn") == checker+++def _check_files(rules: Path, asserted: Path, horn: Path) -> dict:+ """Check three files that do not share a directory, by staging them."""+ import tempfile++ with tempfile.TemporaryDirectory() as d:+ shutil.copy2(rules, Path(d) / "rules.tsv")+ shutil.copy2(asserted, Path(d) / "asserted.tsv")+ shutil.copy2(horn, Path(d) / "horn.tsv")+ return check_horn(d)+++def _swap(fields: list[str], index: int, value: str) -> list[str]:+ out = list(fields)+ out[index] = value+ return outdiff --git a/python/tests/test_horn_differential.py b/python/tests/test_horn_differential.pynew file mode 100644index 00000000..12ab7cc1--- /dev/null+++ b/python/tests/test_horn_differential.py@@ -0,0 +1,227 @@+"""Three independent implementations over one corpus, and what a difference means.++This is the reason a second reasoner is worth writing at all. The Rust engine,+this Python engine and the Lean checker are three separate implementations of one+specification, so running all three over the same graphs finds defects that none+of them finds alone. What this file does NOT do is adjudicate: it is modelled on+`tools/fol_differential.py`, whose first paragraph is "THE ATP IS AN ORACLE, NOT+AN AUTHORITY", and the same discipline applies here. A disagreement is a defect in+ONE OF THE THREE and the job is to report it, not to decide which.++GATED on both binaries and skips loudly wherever it cannot run. CI has neither.++WHAT IS COMPARED, AND WHAT IS NOT.++The assertion is SET EQUALITY OF DERIVED TRIPLES against the Rust `run_horn`, over+the same `builtin_rules.tsv`. Byte identity of the two `horn.tsv` files is NOT a+goal and must not be asserted: the Rust emitter sorts interned `u32` triples+(`src/reason.rs:1513`, `all.sort_unstable()` over `Vec<(u32,u32,u32)>`), so its+line order is first-appearance order in the store, not lexicographic order.+Reproducing it from Python would mean reimplementing the interner and betting on+identical store-iteration order across two bindings, to buy nothing the set+comparison does not already give.++The target is `run_horn` and not `run_full`, and conflating the two will burn a+day. `run_full` is the hardcoded-arm engine and it carries guards the rule table+does not: `rdfs11` is guarded `a != b && b != c && a != c` and `rdfs3` is guarded+on a non-literal object. `run_horn` is generic over the table and carries none of+them, which is why exact agreement is the right expectation here. A comparison+against `run_full` is a CHARACTERISATION run, not an assertion, and anyone who+sees a gap there and "fixes" Python to match will break the table equality and+lose the absolute verdict.++Measured on 14 September 2026 over `demo/derived/_store.ttl`, the largest graph+in the corpus that derives anything: `run_full` under `--profile owl-rl` derives+859 and both table-driven engines derive 859, in three iterations each. So the+predicted divergence does not materialise on this corpus. That is a fact about+the corpus and not about the guards: `rdfs11`'s `a != b && b != c && a != c` and+`rdfs3`'s literal-object filter only bite where those patterns occur, and here+they do not. Do not read the agreement as evidence that the guards are absent,+and do not read a future divergence as a defect.++Blank-node-bearing triples are compared separately and by shape, because blank+node labels are scoped to a parse and two parses of one file may label them+differently. A label difference is not a disagreement about what follows.+"""++import json+import os+import shutil+import subprocess+from pathlib import Path++import pyoxigraph as ox+import pytest++from open_ontologies_lite.horn.certify import CheckerUnavailable, check_horn, find_checker+from open_ontologies_lite.horn.reason import run_horn+from open_ontologies_lite.horn.rules import builtin_rules_bytes++REPO = Path(__file__).resolve().parents[2]+++def _oo_binary() -> Path:+ for candidate in (+ os.environ.get("OO_BIN"),+ REPO / "target" / "release" / "open-ontologies",+ REPO / "target" / "debug" / "open-ontologies",+ shutil.which("open-ontologies"),+ ):+ if candidate and Path(candidate).is_file():+ return Path(candidate)+ pytest.skip(+ "the Rust engine is not built. `cargo build --release --bin open-ontologies`, "+ "or set OO_BIN"+ )+++def _checker() -> Path:+ try:+ return find_checker("oo-horn")+ except CheckerUnavailable as exc:+ pytest.skip(str(exc))+++def _corpus() -> list[Path]:+ demo = REPO / "demo"+ if not demo.is_dir():+ pytest.skip(f"not in a repository checkout: {demo} is absent")+ return sorted(+ p+ for pattern in ("*.ttl", "*.owl", "*.rdf")+ for p in demo.rglob(pattern)+ )+++CORPUS = (+ sorted(+ p+ for pattern in ("*.ttl", "*.owl", "*.rdf")+ for p in (REPO / "demo").rglob(pattern)+ )+ if (REPO / "demo").is_dir()+ else []+)+++def _conclusions(horn_tsv: Path, rules_tsv: Path) -> set[tuple[str, str, str]]:+ """Read the conclusion of every step out of a `horn.tsv`, whoever wrote it.++ The conclusion sits after the binding pairs, whose count is the second field,+ so this is `parseHornSteps`' own arithmetic and it works on both engines'+ output without either engine's help.+ """+ out = set()+ for line in horn_tsv.read_text("utf-8").split("\n"):+ if not line:+ continue+ fields = line.split("\t")+ at = 2 + 2 * int(fields[1])+ out.add(tuple(fields[at : at + 3]))+ return out+++def _ground(triples):+ return {t for t in triples if not any(x.startswith("_:") for x in t)}+++def _shapes(triples):+ """Blank labels normalised away, so two parses can still be compared."""+ return sorted(+ tuple("_:_" if x.startswith("_:") else x for x in t)+ for t in triples+ if any(x.startswith("_:") for x in t)+ )+++def _rust_run(binary: Path, source: Path, out: Path, rules: Path, data_dir: Path) -> dict:+ batch = (+ f"load {source}\n"+ f"reason --rules {rules} --certificate {out}\n"+ )+ proc = subprocess.run(+ [+ str(binary),+ "batch",+ "--no-connect",+ "--json",+ "--data-dir",+ str(data_dir),+ "-",+ ],+ input=batch,+ capture_output=True,+ text=True,+ timeout=300,+ )+ assert proc.returncode == 0, proc.stderr+ lines = [json.loads(line) for line in proc.stdout.splitlines() if line.strip()]+ results = {entry["command"]: entry["result"] for entry in lines}+ assert results["load"].get("ok") is True, results["load"]+ assert "error" not in results["reason"], results["reason"]+ return results["reason"]++[email protected]("source", CORPUS, ids=lambda p: p.name)+def test_the_two_engines_derive_the_same_triples(source, tmp_path, capsys):+ binary = _oo_binary()+ _checker()+ rules = tmp_path / "builtin_rules.tsv"+ rules.write_bytes(builtin_rules_bytes())++ store = ox.Store()+ fmt = ox.RdfFormat.from_extension(source.suffix.lstrip("."))+ try:+ store.load(path=str(source), format=fmt)+ except (SyntaxError, ValueError) as exc:+ pytest.skip(f"{source.name} does not parse: {exc}")++ py_dir = tmp_path / "python"+ py = run_horn(store, certificate_dir=py_dir)+ rust_dir = tmp_path / "rust"+ rust = _rust_run(binary, source, rust_dir, rules, tmp_path / "data")++ py_concl = _conclusions(py_dir / "horn.tsv", py_dir / "rules.tsv")+ rust_concl = _conclusions(rust_dir / "horn.tsv", rust_dir / "rules.tsv")++ # Both certificates must stand on their own before their contents are+ # compared. A disagreement between two certificates one of which the checker+ # rejects is not a differential result, it is one broken emitter.+ py_check = check_horn(py_dir)+ rust_check = check_horn(rust_dir)+ assert py_check["status"] == "accepted", py_check+ assert rust_check["status"] == "accepted", rust_check+ assert py_check["verdict"] == rust_check["verdict"]+ assert py_check["digests_agree"] is True+ assert rust_check["digests_agree"] is True++ with capsys.disabled():+ print(+ f"\n {source.relative_to(REPO)}: asserted {py.asserted_triples}, "+ f"python derived {len(py_concl)}, rust derived {len(rust_concl)}, "+ f"python refused {py.skipped_unserialisable}, "+ f"rust refused {rust.get('skipped_unserialisable', 0)}, "+ f"iterations {py.iterations}/{rust['iterations']}"+ )++ only_py = _ground(py_concl) - _ground(rust_concl)+ only_rust = _ground(rust_concl) - _ground(py_concl)+ assert not only_py and not only_rust, (+ f"the two engines disagree on {source.name}. A difference here is a defect in "+ f"one of the three implementations, and this test does not adjudicate which.\n"+ f" only Python derived: {sorted(only_py)[:5]}\n"+ f" only Rust derived: {sorted(only_rust)[:5]}"+ )+ assert _shapes(py_concl) == _shapes(rust_concl), (+ "the two engines derive the same ground triples but a different number or shape "+ "of blank-node conclusions"+ )+ assert py.fixpoint_reached is True+ assert rust["fixpoint_reached"] is True+ assert py.skipped_unserialisable == rust.get("skipped_unserialisable", 0)+++def test_the_corpus_is_not_empty():+ """A parametrised test over an empty list passes silently, which would make+ every claim above vacuous."""+ assert _corpus(), "no .ttl/.owl/.rdf under demo/ — the differential ran over nothing"diff --git a/python/tests/test_horn_fixpoint_and_scope.py b/python/tests/test_horn_fixpoint_and_scope.pynew file mode 100644index 00000000..61ae765d--- /dev/null+++ b/python/tests/test_horn_fixpoint_and_scope.py@@ -0,0 +1,242 @@+"""Termination, determinism, and which graph the certificate says was asserted.++Three properties, none of which the Lean checker can catch for you.++TERMINATION. There is no iteration cap by default, and there does not need to be+one: `parse_rules` refuses a head variable that does not occur in the body, so no+rule can mint a term, the Herbrand base over the terms in the graph and the table+is finite, and `known` grows monotonically, so the rounds are bounded by the size+of that base. `fixpoint_reached: True` is therefore an earned fact and not a hope.+The Rust `run_full` engine, by contrast, stops at a 64-iteration cap and reports+neither `fixpoint_reached` nor `incomplete`, so a capped run there reports a+number that reads as the closure and is not; `run_horn` gets this right and is+what this engine was copied from.++DETERMINISM. Python randomises string hashing per process, so a candidate list+built by iterating a set gives different bytes on every run. `horn.tsv` is sorted+at the top of each round for exactly that reason, and the test below runs the same+graph through two interpreters with different `PYTHONHASHSEED` and demands+identical bytes.++SCOPE. This is the one that matters most. The Rust `run_horn` flattens every named+graph into `asserted.tsv` (`src/reason.rs:1449`, `graph.all_triples()`), so a store+that holds a previous materialisation in the inferred graph turns derived triples+into ASSERTIONS. The checker cannot detect it: the soundness theorem is+conditional on the assertions, and it is TOLD what they are. The result is a green+absolute verdict about a graph nobody asserted. This package defaults to the+default graph alone and refuses the inferred graph outright.+"""++import os+import subprocess+import sys++import pyoxigraph as ox+import pytest++from open_ontologies_lite.horn.reason import INFERRED_GRAPH, AssertedGraphError, run_horn++RDFS = "http://www.w3.org/2000/01/rdf-schema#"+TYPE = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"++CHAIN = f"""+@prefix ex: <http://ex.org/> .+@prefix rdfs: <{RDFS}> .+ex:A rdfs:subClassOf ex:B . ex:B rdfs:subClassOf ex:C .+ex:C rdfs:subClassOf ex:D . ex:D rdfs:subClassOf ex:E .+ex:a a ex:A .+"""+++def _store(turtle: str = CHAIN) -> ox.Store:+ s = ox.Store()+ s.load(turtle.encode("utf-8"), format=ox.RdfFormat.TURTLE)+ return s+++def test_a_run_with_no_cap_reaches_a_genuine_fixpoint(tmp_path):+ result = run_horn(_store(), certificate_dir=tmp_path)+ assert result.fixpoint_reached is True+ assert result.incomplete is None+ assert result.derived_triples > 0+++def test_running_again_over_the_closure_derives_nothing(tmp_path):+ """The definition of a fixpoint, tested rather than asserted. The closure is+ fed back in as ASSERTIONS of a second store, which is the only honest way to+ ask the question given that nothing is materialised."""+ first = run_horn(_store(), certificate_dir=tmp_path / "one")+ closed = _store()+ ntriples = "".join(f"{s} {p} {o} .\n" for s, p, o in sorted(first.derived()))+ closed.load(ntriples.encode("utf-8"), format=ox.RdfFormat.N_TRIPLES)+ second = run_horn(closed, certificate_dir=tmp_path / "two")+ assert second.derived_triples == 0+ assert second.fixpoint_reached is True+ assert second.iterations == 1+++def test_a_cap_that_bites_says_the_count_is_a_lower_bound(tmp_path):+ result = run_horn(_store(), certificate_dir=tmp_path, max_iterations=1)+ assert result.fixpoint_reached is False+ assert result.incomplete is not None+ assert "LOWER BOUND" in result.incomplete+ assert result.iterations == 1+++def test_the_refusal_count_is_distinct_conclusions_not_attempts(tmp_path):+ """A refused conclusion never enters `known`, so every later round matches+ the same body and re-derives it. A counter would grow with the iteration+ count and report 4 where a reader expects 1."""+ turtle = CHAIN + '\nex:a <http://www.w3.org/2002/07/owl#sameAs> "a literal" .\n'+ result = run_horn(_store(turtle), certificate_dir=tmp_path)+ assert result.iterations >= 3, "the graph must run several rounds for this to bite"+ assert result.skipped_unserialisable == 1+ assert len(result.skipped_examples) == 1+++def test_a_graph_that_only_produces_refusals_still_terminates(tmp_path):+ """The round list is what decides the fixpoint, not the refusal set. Testing+ the refusal set instead would spin for ever here."""+ s = ox.Store()+ s.load(+ b'<http://ex.org/a> <http://www.w3.org/2002/07/owl#sameAs> "lit" .',+ format=ox.RdfFormat.N_TRIPLES,+ )+ result = run_horn(s, certificate_dir=tmp_path)+ assert result.fixpoint_reached is True+ assert result.iterations == 1+ assert result.derived_triples == 0+ # The refusal is still counted and still reported, so a reader is never left+ # to conclude that the table simply did not fire.+ assert result.skipped_unserialisable == 1+++def test_named_graphs_are_not_asserted_by_default(tmp_path):+ s = _store()+ s.add(+ ox.Quad(+ ox.NamedNode("http://ex.org/x"),+ ox.NamedNode(f"{RDFS}subClassOf"),+ ox.NamedNode("http://ex.org/y"),+ ox.NamedNode("http://ex.org/other"),+ )+ )+ result = run_horn(s, certificate_dir=tmp_path)+ assert result.asserted_graphs == ["default"]+ assert "http://ex.org/x" not in (tmp_path / "asserted.tsv").read_text("utf-8")+++def test_asking_for_every_graph_reports_which_ones_were_asserted(tmp_path):+ s = _store()+ s.add(+ ox.Quad(+ ox.NamedNode("http://ex.org/x"),+ ox.NamedNode(f"{RDFS}subClassOf"),+ ox.NamedNode("http://ex.org/y"),+ ox.NamedNode("http://ex.org/other"),+ )+ )+ result = run_horn(s, certificate_dir=tmp_path, graphs="all")+ assert result.asserted_graphs == ["<http://ex.org/other>", "default"]+ assert "http://ex.org/x" in (tmp_path / "asserted.tsv").read_text("utf-8")+++def test_a_previous_materialisation_can_never_be_asserted(tmp_path):+ """The defect this package exists not to have. A certificate whose asserted+ set contains a previous run's conclusions certifies entailment from a graph+ nobody asserted, and the checker is TOLD what the assertions are, so it+ cannot notice."""+ s = _store()+ s.add(+ ox.Quad(+ ox.NamedNode("http://ex.org/a"),+ ox.NamedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),+ ox.NamedNode("http://ex.org/E"),+ ox.NamedNode(INFERRED_GRAPH),+ )+ )+ with pytest.raises(AssertedGraphError, match="DERIVED"):+ run_horn(s, certificate_dir=tmp_path, graphs="all")+ with pytest.raises(AssertedGraphError):+ run_horn(s, certificate_dir=tmp_path, graphs=[INFERRED_GRAPH])+ # and the default is unaffected, because it never looked at that graph+ assert run_horn(s, certificate_dir=tmp_path).asserted_graphs == ["default"]+++def test_a_nonsense_graph_selector_is_refused(tmp_path):+ with pytest.raises(ValueError, match="neither 'default' nor 'all'"):+ run_horn(_store(), certificate_dir=tmp_path, graphs="everything")+ with pytest.raises(ValueError, match="selects nothing"):+ run_horn(_store(), certificate_dir=tmp_path, graphs=[])+++EMIT = """+import sys, pathlib+import pyoxigraph as ox+from open_ontologies_lite.horn.reason import run_horn+s = ox.Store()+s.load(pathlib.Path(sys.argv[1]).read_bytes(), format=ox.RdfFormat.TURTLE)+run_horn(s, certificate_dir=sys.argv[2])+sys.stdout.buffer.write(pathlib.Path(sys.argv[2], 'horn.tsv').read_bytes())+"""+++def test_the_bytes_do_not_depend_on_the_hash_seed(tmp_path):+ """Without `sorted(known)` at the top of each round the candidate order comes+ off a set, and Python randomises string hashing per process."""+ import open_ontologies_lite+ import pyoxigraph++ turtle = tmp_path / "g.ttl"+ turtle.write_bytes(CHAIN.encode("utf-8"))+ pythonpath = os.pathsep.join(+ [+ str(__import__("pathlib").Path(open_ontologies_lite.__file__).parents[1]),+ str(__import__("pathlib").Path(pyoxigraph.__file__).parents[1]),+ ]+ )+ outputs = []+ for seed in ("0", "1", "12345"):+ env = dict(os.environ, PYTHONHASHSEED=seed, PYTHONPATH=pythonpath)+ out = tmp_path / f"cert{seed}"+ proc = subprocess.run(+ [sys.executable, "-c", EMIT, str(turtle), str(out)],+ capture_output=True,+ env=env,+ )+ assert proc.returncode == 0, proc.stderr.decode()+ outputs.append(proc.stdout)+ assert outputs[0] == outputs[1] == outputs[2]+ assert outputs[0] != b""+++def test_naming_a_graph_explicitly_asserts_that_graph_and_only_it(tmp_path):+ """The explicit-list path builds `NamedNode`s out of strings a caller wrote,+ which is the one place in this module where a user string becomes a term. It+ accepts a graph either bare or in its N-Triples spelling, because anyone+ reading `asserted_graphs` out of a previous report will paste the spelled+ form straight back in."""+ s = _store()+ other = ox.NamedNode("http://ex.org/other")+ s.add(+ ox.Quad(+ ox.NamedNode("http://ex.org/x"),+ ox.NamedNode(f"{RDFS}subClassOf"),+ ox.NamedNode("http://ex.org/y"),+ other,+ )+ )+ for n, spelling in enumerate(("http://ex.org/other", "<http://ex.org/other>")):+ out = tmp_path / f"run{n}"+ result = run_horn(s, certificate_dir=out, graphs=[spelling])+ assert result.asserted_graphs == ["<http://ex.org/other>"]+ assert result.asserted_triples == 1+ text = (out / "asserted.tsv").read_text("utf-8")+ assert "http://ex.org/x" in text+ assert "http://ex.org/a>" not in text, "the default graph leaked in"+++def test_naming_the_default_graph_in_a_list_selects_the_default_graph(tmp_path):+ result = run_horn(_store(), certificate_dir=tmp_path, graphs=["default"])+ assert result.asserted_graphs == ["default"]+ assert result.asserted_triples == 5diff --git a/python/tests/test_horn_rule_table.py b/python/tests/test_horn_rule_table.pynew file mode 100644index 00000000..0245a906--- /dev/null+++ b/python/tests/test_horn_rule_table.py@@ -0,0 +1,231 @@+"""The rule table is data, and every refusal in the parser is load-bearing.++Runs with no Lean binary, so it runs in CI. A rule's identity in a certificate is+its INDEX into this table, never its name: `scm-eqc1` occupies rows 11 and 12 and+`scm-eqp1` rows 13 and 14, because each licenses two conclusions. Pinning the+whole table in order is how a reordering that silently repoints every certificate+in the wild gets caught, and it is why nothing in this package keeps a+name-to-index map.++The refusals below go beyond what the Lean parser rejects. That asymmetry is+correct: Lean only has to CHECK a binding, while this side has to PRODUCE one, so+a rule the checker would happily accept can still be one this engine has nothing+to bind. Refusing is the only honest option, and each refusal names the line and+what was wrong rather than guessing.+"""++from pathlib import Path++import pytest++from open_ontologies_lite.horn.rules import (+ AtomPat,+ RulePattern,+ RuleTableError,+ builtin_rules,+ builtin_rules_bytes,+ parse_rules,+ rules_tsv,+ vars_of,+)++SUBCLASS_OF = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>"+TYPE = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"++# (index, name, body length), the whole table, in order.+EXPECTED_TABLE = [+ (0, "rdfs2", 2),+ (1, "rdfs3", 2),+ (2, "rdfs5", 2),+ (3, "rdfs7", 2),+ (4, "rdfs9", 2),+ (5, "rdfs11", 2),+ (6, "prp-trp", 3),+ (7, "prp-symp", 2),+ (8, "prp-inv1", 2),+ (9, "prp-inv2", 2),+ (10, "eq-sym", 1),+ (11, "scm-eqc1", 1),+ (12, "scm-eqc1", 1),+ (13, "scm-eqp1", 1),+ (14, "scm-eqp1", 1),+ (15, "cls-svf1", 4),+ (16, "cls-avf", 4),+ (17, "cls-hv1", 3),+ (18, "cls-hv2", 3),+ (19, "scm-svf1", 5),+ (20, "scm-svf2", 5),+ (21, "scm-avf1", 5),+ (22, "scm-avf2", 5),+ (23, "scm-dom1", 2),+ (24, "scm-dom2", 2),+ (25, "scm-rng1", 2),+ (26, "scm-rng2", 2),+]+++def test_the_builtin_table_has_twenty_seven_rows_in_this_order():+ table = builtin_rules()+ assert len(table) == 27+ got = [(i, r.name, len(r.body)) for i, r in enumerate(table)]+ assert got == EXPECTED_TABLE+++def test_the_two_double_rows_license_opposite_conclusions():+ """`scm-eqc1` and `scm-eqp1` are two rows each, and the second is the+ converse of the first. A name-keyed map would keep one and lose the other,+ and every certificate citing the lost index would then be checked against+ the wrong rule."""+ table = builtin_rules()+ assert table[11].head.fields() == ("?a", SUBCLASS_OF, "?b")+ assert table[12].head.fields() == ("?b", SUBCLASS_OF, "?a")+ assert table[13].head != table[14].head+++def test_scm_avf2_head_is_reversed():+ """`lean/OOCert/Rules.lean:47` records that the natural way round is+ unsound: from `?c1 allValuesFrom ?y` and `?p1 subPropertyOf ?p2` the+ subclass runs `?c2 subClassOf ?c1`, not the other way. Pinning it here+ means a "tidy-up" that flips it fails in Python before it reaches Lean."""+ rule = builtin_rules()[22]+ assert rule.name == "scm-avf2"+ assert rule.head.fields() == ("?c2", SUBCLASS_OF, "?c1")+++def test_rendering_the_builtin_table_reproduces_its_bytes():+ """The emitter writes the vendored bytes verbatim, so this is not what makes+ the absolute verdict safe; it is what proves the renderer would have been+ safe too, which is the precondition for rendering a table a user supplied."""+ raw = builtin_rules_bytes()+ assert rules_tsv(parse_rules(raw.decode("utf-8"))).encode("utf-8") == raw+++def test_the_vendored_table_matches_the_repo_fixture():+ fixture = Path(__file__).resolve().parents[2] / "tests" / "fixtures" / "horn" / "builtin_rules.tsv"+ if not fixture.is_file():+ pytest.skip(f"not in a repository checkout: {fixture} is absent")+ assert builtin_rules_bytes() == fixture.read_bytes()+++def test_the_vendored_table_has_no_carriage_return_and_ends_with_a_newline():+ raw = builtin_rules_bytes()+ assert b"\r" not in raw+ assert raw.endswith(b"\n")+++def test_variables_are_listed_in_first_occurrence_order():+ """The binding list in horn.tsv is written in this order, matching the Rust+ emitter so a human can diff the two certificates."""+ rule = builtin_rules()[4] # rdfs9: ?x type ?a . ?a subClassOf ?b -> ?x type ?b+ assert vars_of(rule.atoms()) == ["x", "a", "b"]+++def test_a_carriage_return_is_refused_rather_than_stripped():+ line = f"r\t1\t?a\t{SUBCLASS_OF}\t?b\t?a\t{SUBCLASS_OF}\t?b\r\n"+ with pytest.raises(RuleTableError, match="carriage return"):+ parse_rules(line)+++def test_a_constant_that_is_not_an_ntriples_term_is_refused():+ """A constant in any other spelling can never equal a term the store holds,+ so the rule silently never fires. That is a typo, not a rule."""+ line = f"r\t1\t?a\trdfs:subClassOf\t?b\t?a\t{SUBCLASS_OF}\t?b\n"+ with pytest.raises(RuleTableError, match="N-Triples term"):+ parse_rules(line)+++def test_a_bare_question_mark_is_refused():+ line = f"r\t1\t?\t{SUBCLASS_OF}\t?b\t?b\t{SUBCLASS_OF}\t?b\n"+ with pytest.raises(RuleTableError, match="no variable name"):+ parse_rules(line)+++def test_a_head_variable_that_is_not_in_the_body_is_refused():+ line = f"r\t1\t?a\t{SUBCLASS_OF}\t?b\t?a\t{SUBCLASS_OF}\t?zzz\n"+ with pytest.raises(RuleTableError, match="does not occur in the body"):+ parse_rules(line)+++def test_a_wrong_field_count_is_refused():+ with pytest.raises(RuleTableError, match="pattern fields"):+ parse_rules(f"r\t2\t?a\t{SUBCLASS_OF}\t?b\t?a\t{SUBCLASS_OF}\t?b\n")+++def test_a_non_ascii_digit_body_length_is_refused():+ """`str.isdigit()` is true of '٣' and int() accepts it, so a body length+ Lean's `toNat?` would reject could otherwise be read here."""+ with pytest.raises(RuleTableError, match="not a decimal number"):+ parse_rules(f"r\t٣\t?a\t{SUBCLASS_OF}\t?b\t?a\t{SUBCLASS_OF}\t?b\n")+++def test_an_empty_rule_name_is_refused():+ with pytest.raises(RuleTableError, match="name is empty"):+ parse_rules(f"\t1\t?a\t{SUBCLASS_OF}\t?b\t?a\t{SUBCLASS_OF}\t?b\n")+++def test_a_tab_in_a_programmatically_built_rule_name_is_refused_on_the_way_out():+ """No parsed table can carry this, because the line was already split on tab.+ A caller building a RulePattern in Python can, and a tab in a rule name would+ shift every field of that line by one."""+ rule = RulePattern(+ name="bad\tname",+ body=(AtomPat("?a", SUBCLASS_OF, "?b"),),+ head=AtomPat("?a", TYPE, "?b"),+ )+ with pytest.raises(ValueError, match="separator"):+ rules_tsv([rule])+++def test_blank_lines_and_a_trailing_newline_are_accepted():+ """`HornParse.parseRules` skips empty lines, so this parser must too or a+ file the checker reads happily would be refused here."""+ body = f"r\t1\t?a\t{SUBCLASS_OF}\t?b\t?a\t{SUBCLASS_OF}\t?b\n"+ assert len(parse_rules(body + "\n" + body)) == 2+++def test_the_vendored_table_is_tracked_by_git_and_not_ignored():+ """The wheel is built from the FILESYSTEM and the repository is shared from+ GIT, so a data file that is present locally and ignored by git produces a+ working wheel on the machine that wrote it and a BROKEN one from a fresh+ clone or from CI, failing with FileNotFoundError on the first call to+ `builtin_rules()`.++ That is not hypothetical here. The root `.gitignore` carries `data/` with no+ leading slash, which matches a directory of that name at ANY depth, and it+ already carries four negation entries for the same collision under+ `case-studies/`. The directory holding this table is called `tables` for that+ reason, and this test is what keeps it that way: renaming it back to `data`+ fails here rather than three weeks later in someone else's checkout.++ The file is LOCATED BY SEARCHING and then CONFIRMED to be the one the code+ reads, rather than reconstructed from a path spelled here. A reconstructed+ path that no longer exists makes `git check-ignore` report "not ignored",+ which is a vacuous pass: the first version of this test did exactly that and+ passed against the very layout it was written to reject.+ """+ import shutil+ import subprocess++ import open_ontologies_lite.horn as horn++ if shutil.which("git") is None:+ pytest.skip("git is not on PATH")+ repo = Path(__file__).resolve().parents[2]+ if not (repo / ".git").exists():+ pytest.skip("not in a git checkout")++ found = sorted(Path(horn.__file__).parent.rglob("builtin_rules.tsv"))+ assert len(found) == 1, f"expected exactly one vendored table, found {found}"+ table = found[0]+ assert table.read_bytes() == builtin_rules_bytes(), (+ "the file found on disk is not the one importlib.resources reads, so this "+ "test would be checking the wrong path"+ )++ ignored = subprocess.run(+ ["git", "check-ignore", str(table)], cwd=repo, capture_output=True, text=True+ )+ assert ignored.returncode != 0, (+ f"{table} is ignored by git, so it will not be in a fresh clone and every "+ f"wheel built from one ships without the built-in rule table:\n{ignored.stdout}"+ )diff --git a/python/tests/test_horn_unchecked_never_reports_checked.py b/python/tests/test_horn_unchecked_never_reports_checked.pynew file mode 100644index 00000000..5fe4dca9--- /dev/null+++ b/python/tests/test_horn_unchecked_never_reports_checked.py@@ -0,0 +1,135 @@+"""A result the Lean checker never saw must carry no verdict, in its own words.++This is the C2/C3 gate and the one CI actually runs, because CI installs `[dev]`+and nothing else: no elan, no `lake`, no `oo-horn`. Every green tick on this+repository's Python job is therefore a statement about the UNCHECKED path, and+this file is what makes that statement worth anything.++The failure being guarded against is not a crash. It is a report that looks+successful: a derivation count, a certificate directory, and a verdict word+sitting beside them that no checker ever pronounced. That is assurance+laundering with the engine's own output as the source, and the only defence that+survives refactoring is a test asserting that the verdict word does not appear+ANYWHERE in the report when nothing was checked, not merely that some `checked`+flag is False.++The first test simulates the real shape of the absence: a package with no+repository above it, which is what `pip install open-ontologies-lite` gives, and+an empty PATH. It copies the installed package to a temporary directory for+exactly that reason, since the repo probe in `find_checker` would otherwise find+the `lake build` output sitting two levels above this checkout and the test would+prove nothing about a wheel.+"""++import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++import open_ontologies_lite++SCRIPT = """+import json, sys, tempfile+import pyoxigraph as ox+from open_ontologies_lite import OntologyEngine++e = OntologyEngine()+e.load('<http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/A> .\\n'+ '<http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B> .',+ 'ntriples')+report = e.reason_horn(tempfile.mkdtemp(){extra})+print(json.dumps(report))+"""+++def _run(script: str, env: dict) -> dict:+ proc = subprocess.run(+ [sys.executable, "-c", script], capture_output=True, text=True, env=env+ )+ assert proc.returncode == 0, proc.stderr+ return json.loads(proc.stdout)+++def test_a_run_the_checker_never_saw_carries_no_verdict(tmp_path):+ """A wheel install: no repository above the package, nothing on PATH."""+ installed = Path(open_ontologies_lite.__file__).parent+ staged = tmp_path / "site" / "open_ontologies_lite"+ shutil.copytree(installed, staged, ignore=shutil.ignore_patterns("__pycache__"))+ assert not (tmp_path / "lean" / "lakefile.toml").exists()++ env = dict(os.environ)+ env["PATH"] = ""+ env.pop("OO_HORN", None)+ env["PYTHONPATH"] = str(tmp_path / "site") + os.pathsep + _pyoxigraph_dir()++ report = _run(SCRIPT.format(extra=""), env)+ check = report["check"]+ assert check["status"] == "unchecked_no_checker"+ assert check["checked"] is False+ assert check["verdict"] is None+ assert check["pronounced_by"] is None+ assert "oo-horn" in check["warning"]+ assert "lake build" in check["warning"]+ assert "OO_HORN" in check["how_to_get_it"]+ # The load-bearing one. It catches the relativised verdict word too, since+ # that word contains this one, and it catches a verdict smuggled into any+ # field of the report rather than only into `check["verdict"]`.+ assert "entailed" not in json.dumps(report)+++def test_naming_a_checker_that_is_not_there_is_not_silently_replaced():+ """An explicit path does not fall through to a search. A caller who named a+ binary meant that binary, and a report about a different checker found on+ PATH would be a report about something the caller did not run."""+ env = dict(os.environ)+ env["PYTHONPATH"] = str(Path(open_ontologies_lite.__file__).parents[1])+ report = _run(+ SCRIPT.format(extra=", checker='/nonexistent/oo-horn'"), env+ )+ check = report["check"]+ assert check["status"] == "unchecked_no_checker"+ assert check["checked"] is False+ assert check["verdict"] is None+ assert "/nonexistent/oo-horn" in check["how_to_get_it"]+ assert "entailed" not in json.dumps(report)+++def test_check_false_writes_a_certificate_and_claims_nothing():+ env = dict(os.environ)+ env["PYTHONPATH"] = str(Path(open_ontologies_lite.__file__).parents[1])+ report = _run(SCRIPT.format(extra=", check=False"), env)+ check = report["check"]+ assert check["status"] == "not_requested"+ assert check["checked"] is False+ assert check["verdict"] is None+ assert check["pronounced_by"] is None+ assert "NOT checked" in check["warning"]+ assert "entailed" not in json.dumps(report)+ # The certificate is still on disk and the report says how to check it later.+ assert "oo-horn check" in check["check_with"]+++def test_the_engine_reports_the_certificate_without_a_checker_installed(tmp_path):+ """The library half must WORK with no binary, not merely refuse politely."""+ from open_ontologies_lite import OntologyEngine++ e = OntologyEngine()+ e.load(+ "<http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> "+ "<http://ex.org/A> .\n"+ "<http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> "+ "<http://ex.org/B> .",+ "ntriples",+ )+ report = e.reason_horn(str(tmp_path), checker="/nonexistent/oo-horn")+ assert report["derived_triples"] == 1+ assert (tmp_path / "horn.tsv").read_bytes().count(b"\n") == 1+ assert report["check"]["checked"] is False+++def _pyoxigraph_dir() -> str:+ import pyoxigraph++ return str(Path(pyoxigraph.__file__).parents[1])diff --git a/python/tests/test_the_verdict_words_are_never_written_in_python.py b/python/tests/test_the_verdict_words_are_never_written_in_python.pynew file mode 100644index 00000000..4fd6f677--- /dev/null+++ b/python/tests/test_the_verdict_words_are_never_written_in_python.py@@ -0,0 +1,142 @@+"""No verdict word may appear as an executable string anywhere in this package.++This is the gate. If either verdict word is ever assigned, defaulted, compared or+formatted in Python, the verdict is being synthesised here and the work is wrong+regardless of what every other test in the suite says.++The scan is over the ABSTRACT SYNTAX TREE and not over grep output, and the+distinction is the whole design. A grep-based rule would have to forbid the word+everywhere, which is impossible and also wrong: `onto_reason`'s docstring and+`horn/__init__.py` have to TEACH the reader what `entailed_under_supplied_rules`+means, and a docstring that cannot name the thing it is warning about is useless.+An AST scan separates the two cleanly. Docstrings are exempt by construction,+comments never reach the tree at all, and every other string constant, f-string+fragment included, is forbidden. The word `entailed` is the whole test, because+the relativised verdict contains it.++The second half of the file pins the module split. `reason.py` must run with no+checker installed and `certify.py` must be usable against a certificate this+package did not write, so neither may import the other. That is what makes "works+with no binary" structural rather than a promise, and an import added in a hurry+is exactly how such a property is lost.+"""++import ast+from pathlib import Path++import open_ontologies_lite++PACKAGE = Path(open_ontologies_lite.__file__).parent+FORBIDDEN = "entailed"+++def _python_files():+ return sorted(p for p in PACKAGE.rglob("*.py") if "__pycache__" not in p.parts)+++def _docstring_ids(tree: ast.AST) -> set[int]:+ """Identity of every node that is a docstring: the first statement of a+ module, class or function when it is a bare string."""+ out: set[int] = set()+ for node in ast.walk(tree):+ if isinstance(+ node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)+ ):+ body = getattr(node, "body", None)+ if not body:+ continue+ first = body[0]+ if (+ isinstance(first, ast.Expr)+ and isinstance(first.value, ast.Constant)+ and isinstance(first.value.value, str)+ ):+ out.add(id(first.value))+ return out+++def test_no_module_writes_a_verdict_word_outside_a_docstring():+ offenders = []+ for path in _python_files():+ tree = ast.parse(path.read_text("utf-8"), filename=str(path))+ exempt = _docstring_ids(tree)+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.Constant)+ and isinstance(node.value, str)+ and id(node) not in exempt+ and FORBIDDEN in node.value+ ):+ offenders.append(+ f"{path.relative_to(PACKAGE)}:{node.lineno}: {node.value[:80]!r}"+ )+ assert offenders == [], (+ "a verdict word appears as an executable string, so the verdict is being "+ "decided in Python rather than copied from the checker:\n" + "\n".join(offenders)+ )+++def test_the_scan_would_catch_a_verdict_word_if_one_were_added():+ """A gate that cannot fail is decoration. This runs the same scan over a+ source file that does synthesise a verdict, and requires it to be caught."""+ source = (+ '"""A docstring may say entailed, and must not be flagged."""\n'+ "def f(ok):\n"+ ' """Nor may this docstring be flagged when it says entailed."""\n'+ ' return "entailed" if ok else None\n'+ )+ tree = ast.parse(source)+ exempt = _docstring_ids(tree)+ caught = [+ node.value+ for node in ast.walk(tree)+ if isinstance(node, ast.Constant)+ and isinstance(node.value, str)+ and id(node) not in exempt+ and FORBIDDEN in node.value+ ]+ assert caught == ["entailed"]+++def test_an_fstring_fragment_is_not_a_hiding_place():+ """`JoinedStr` holds `Constant` nodes, so splicing the word into an f-string+ is caught by the same walk. Pinned because it is the obvious way round."""+ tree = ast.parse('def f(x):\n return f"the run is {x} entailed"\n')+ caught = [+ node.value+ for node in ast.walk(tree)+ if isinstance(node, ast.Constant)+ and isinstance(node.value, str)+ and FORBIDDEN in node.value+ ]+ assert caught != []+++def _imports(path: Path) -> set[str]:+ tree = ast.parse(path.read_text("utf-8"), filename=str(path))+ names: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom) and node.module:+ names.add(node.module)+ elif isinstance(node, ast.Import):+ names.update(a.name for a in node.names)+ return names+++def test_the_reasoner_never_imports_the_checker_bridge():+ """`reason.py` must run with nothing installed but pyoxigraph."""+ assert not any("certify" in m for m in _imports(PACKAGE / "horn" / "reason.py"))+++def test_the_checker_bridge_never_imports_the_reasoner():+ """`certify.py` is standard library only and must be usable against a+ certificate directory this package did not write."""+ assert not any("reason" in m for m in _imports(PACKAGE / "horn" / "certify.py"))+++def test_the_rule_table_module_needs_no_triple_store():+ """A rule table is text. Keeping pyoxigraph out of `rules.py` is what lets+ the table be parsed, rendered and tested without a store."""+ assert not any(+ "pyoxigraph" in m for m in _imports(PACKAGE / "horn" / "rules.py")+ )