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
Ask whether a retrieved slice still entails the answer's claims, and treat a projection-only entailment as an engine bug
FABIOTESS4f957de2312b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 26f5be19..3505abc5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -341,6 +341,36 @@ jobs:# fact, and it is the reason this job exists rather than being folded# into the line above.run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_horn_certificate_test -- --nocapture+ - name: Check that a projection preserves the claims an answer rests on+ # Coverage is a proxy, and the first two legs here are the argument for+ # that sentence: a slice of a SHIPPED ontology at coverage 1.0 with+ # ok:true that has dropped the one triple the answer depends on, and+ # its converse at coverage 0.001 preserving every claim with a+ # Lean-checked certificate. The rest are the verdict discipline and the+ # three conditions under which the monotonicity gate is disarmed.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_projection_entailment_test -- --nocapture+ - name: Check the goal-free closure diff+ run: OO_REQUIRE_FIXTURES=1 cargo test --test closure_diff_test -- --nocapture+ - name: Run the monotonicity differential over every shipped ontology+ # OWL RL is monotone and a projection is a subset, so anything the+ # projection entails and the source does not is a soundness bug in the+ # engine. This leg runs that check for real over the shipped corpus and+ # prints what it found, INCLUDING if it found nothing: a sweep whose+ # gate was disarmed everywhere establishes nothing, so the test fails+ # if the gate was armed on fewer than half the ontologies.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test projection_monotonicity_corpus_test -- --nocapture+ - name: Check the preserve and closure-diff command lines, including their exit codes+ # Wiring nothing exercises is how `push` came to be proxied to a batch+ # runner with no arm for it. These run the real binary, and they pin+ # that a lost claim fails the process rather than printing a finding+ # and exiting 0.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test preserve_cli_test -- --nocapture+ - name: Show every gate firing on its own broken input+ # A gate that cannot fail is decoration, and a gate whose failure+ # nobody has read is close to it. This leg feeds each gate the input+ # built to trip it and PRINTS what the tool said, so the evidence is in+ # the job log rather than in a doc.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test gate_demonstration_test -- --nocapture# The official W3C SHACL test suite, as a ratchet.#diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d3f01c7d..90292639 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,100 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]### Added+- **Entailment preservation under graph projection, because coverage is the+ wrong measure and looks like assurance.** `src/projection_entailment.rs`+ (CLI `preserve`, MCP `graph_projection_entailment_check`) takes the claims an+ answer rests on and reports, for each one, whether the retrieved slice entails+ it exactly when the source does, with a sub-certificate the Lean checker+ accepts for every claim it preserves. `src/closure_diff.rs` (CLI+ `closure-diff`, MCP `onto_closure_diff`) is the goal-free form, for auditing a+ retrieval strategy rather than one answer, and reuses the same certificate+ index, checker runner, subset precondition, skolemiser and differential, so+ there is one place in the crate where each verdict word is produced. No new+ Lean was written: `OOCert.certificate_sound` covers the sub-certificates+ unchanged, and `OOCert.horn_certificate_sound` covers a run over a supplied+ Horn table, which earns+ `preserved_under_supplied_rules_checked` and never the plain word.+ Four outcomes are kept apart, because a lossy retriever and a hallucinating+ generator have opposite fixes: `preserved_*`, `lost_under_profile_unchecked`,+ `ungrounded_in_source` (NEITHER graph derives the claim) and+ `projection_only`. Measured on `benchmark/reference/pizza-reference.owl`, a+ file this repository ships: the whole ontology minus one `rdfs:subClassOf`+ triple scores `aggregate_coverage_ratio: 1.0` with `ok: true` while the+ conclusion the answer rests on is gone, and a three-triple slice scores+ 0.00128 and preserves every claim with a checked certificate. Both are tests.+ See [decision 0007](docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md)+ and [docs/projection-entailment.md](docs/projection-entailment.md).+- **A monotonicity differential that runs on every call and is a defect+ detector for the engine, not for the retrieval.** OWL RL is monotone and a+ projection is a subset, so anything the projection entails and the source does+ not is a soundness bug in this engine. It is reported at `STOP_THE_LINE` with+ exit 2, and it is DISARMED, loudly and with its own reason, whenever its+ antecedent fails: the projection is not a subset (computed every run, never+ inferred from provenance), blank nodes could not be matched, or either run+ stopped at the iteration cap instead of a fixpoint. A green+ `violations: []` under a disarmed gate means "we did not look", so the two can+ never render the same. Run for real over the shipped corpus+ (`tests/projection_monotonicity_corpus_test.rs`): 275 ontologies swept, the+ gate ARMED on all 275, every source certificate accepted by `oo-cert`, and+ **no violations found**.+- `tests/gate_demonstration_test.rs`, which feeds every gate in this work the+ input built to trip it, PRINTS what the tool said, and asserts the same+ thing. A gate that cannot fail is decoration, and a gate whose failure nobody+ has read is close to it. Run it with `--nocapture`; a CI leg does.+- `Reasoner::run_full` reports `fixpoint_reached`, matching `run_horn`. A run+ that stopped at `reasoner_max_iterations` has a closure that is a LOWER BOUND,+ and until now a truncated closure was indistinguishable from a complete one,+ which is what would have made a correct engine look unsound to any consumer+ comparing two closures.+- `GraphStore::graph_store`, `graph_triples`, `named_graph_iris`,+ `materialised_inference_count`, `all_quads`, `parse_triples_ordered` and+ `canonicalise_triples`. The first copies a named graph into a fresh store's+ default graph BY MODEL TERM, which is the only route by which a slice can be a+ subset of its source in the strong sense, blank nodes included.++### Fixed+- **`onto_segment_retrieve` emitted slices that do not parse, which broke the+ pairing it advertises.** Every term was wrapped in angle brackets+ unconditionally, so a blank-node `owl:Restriction` superclass came out as+ `<_:b0>`, which is not a legal IRI. Since issue #93 `load_turtle` collects all+ or nothing, so one restriction superclass made the ENTIRE slice unreadable and+ `graph_projection_lossy_check` then reported `projection_parses: false` with+ `aggregate_coverage_ratio: 0.0` and no diagnosis. Measured on+ `benchmark/ontoaxiom/data/ontoaxiom/ontologies/pizza.ttl` and+ `benchmark/reference/pizza-reference.owl`, which is to say on essentially+ every OWL ontology here. Blank nodes are now written bare, and the+ angle-bracket trim no longer eats the closing bracket of a typed literal's+ datatype IRI.+- **`check_projection_loss` reported `ok: true` on a projection holding MORE+ than the source.** `coverage_ratio` clamps with `.min()`, so a seed whose+ slice carries triples the source does not read exactly 1.0 with empty dropped+ lists: a hallucinating retriever, or a slice of a different graph, scored a+ clean bill of health on the one input that should stop a pipeline. The clamp+ stays, because an unclamped "ratio" above 1.0 is not a ratio; the surplus is+ now named in `seeds_with_surplus` and `ok` requires it to be empty.+- `docs/lean-certificates.md` said the certified corpus was 122 files. Counted+ on 14 September 2026 under the test's own filter it is 290 tracked RDF files,+ 21,256,445 bytes.+- The advertised tool count was stale before this change and is now measured.+ `src/server.rs` carried 110 distinct `#[tool(name = ...)]` macros while the+ README, the docs and the server's own instructions said 109: `onto_fol_export`+ landed without the count moving. With the two added here it is 112, counted+ from the source rather than incremented. The narrative comment in+ `src/graph.rs` about the removed store mutex no longer names a number, since+ what it is about is the lock and not the tool count.++### Changed+- **`coverage_ratio` is demoted, not deleted.** `ProjectionLossReport` gains+ `is_a_warrant: false` and a `warning` field carrying the sentence in the+ payload rather than only in the docs, so a renderer that walks the data still+ emits it, and the `graph_projection_lossy_check` tool description now carries+ it too, because a tool description is the text an agent reads when choosing+ and that is where the trap was living unlabelled. The number is neither+ necessary nor sufficient for entailment preservation and it moves the wrong+ way, rising as the projection grows, so a retriever tuned on it learns to+ fetch more rather than the right thing.+- **First-order export, over the translation a machine-checked adequacy theoremis about.** `fol --out DIR --format tptp|clif` (also `onto_fol_export` andbatch `fol`) writes the loaded ontology as TPTP FOF or as ISO/IEC 24707diff --git a/README.md b/README.mdindex eb4d21ca..30584836 100644--- a/README.md+++ b/README.md@@ -40,7 +40,7 @@----Open Ontologies is a **Rust MCP server** and **desktop Studio** for AI-native ontology engineering. It exposes **109 tools** that let Claude build, validate, query, diff, lint, version, reason over, align, plan, certify, and govern RDF/OWL ontologies using an in-memory Oxigraph triple store, alongside a three-layer Dynamics → Causal → Planner architecture, a marketplace of 33 standard ontologies, clinical crosswalks, semantic embeddings, and a lineage audit trail. A default build advertises all 109 tools. Eight of them need an optional Cargo feature and return an error without it: four need `embeddings`, two need `plugins`, and two need `postgres` or `duckdb`. The published binaries and the GHCR image are built with the default feature set, so they do not carry those eight. Build from source with `cargo build --release --features embeddings,plugins,sql` to get them.+Open Ontologies is a **Rust MCP server** and **desktop Studio** for AI-native ontology engineering. It exposes **112 tools** that let Claude build, validate, query, diff, lint, version, reason over, align, plan, certify, and govern RDF/OWL ontologies using an in-memory Oxigraph triple store, alongside a three-layer Dynamics → Causal → Planner architecture, a marketplace of 33 standard ontologies, clinical crosswalks, semantic embeddings, and a lineage audit trail. A default build advertises all 112 tools. Eight of them need an optional Cargo feature and return an error without it: four need `embeddings`, two need `plugins`, and two need `postgres` or `duckdb`. The published binaries and the GHCR image are built with the default feature set, so they do not carry those eight. Build from source with `cargo build --release --features embeddings,plugins,sql` to get them.The **Studio** wraps the engine in a visual desktop environment: virtualized ontology tree with hierarchy lines, breadcrumb navigation, and connection explorer; AI chat panel with `/build` (IES-level deep) and `/sketch` (quick prototype) commands; Protégé-style property inspector; and lineage viewer.@@ -74,7 +74,8 @@ The full **Dynamics → Causal → Planner** stack plus 13 new primitives. Every- **`onto_align_flora`**, end-to-end alignment pipeline pairing the signal extractor to the fuzzy adjudicator.- **`onto_policy_register`** + **`onto_policy_list`** + **`onto_policy_check`**, authorisation gate that composes with `onto_certify_action` (Causal = risk; policy = authorisation).- **`eval_rag`** + **`eval_rag_mmrag`**, Hit@k / MRR / faithfulness / token-Jaccard / ROUGE-1 scoring for retriever pipelines, with a dataset adapter.-- **`graph_projection_lossy_check`**, the auditor that pairs with `onto_segment_retrieve`.+- **`graph_projection_lossy_check`**, the auditor that pairs with `onto_segment_retrieve`. Its coverage ratio is a proxy and is labelled as one.+- **`graph_projection_entailment_check`** + **`onto_closure_diff`**, entailment preservation under projection: for each claim an answer rests on, does the slice entail it exactly when the source does, with a Lean-checked certificate per preserved claim, and a free monotonicity differential that treats a projection-only entailment as a soundness bug in the engine rather than a retrieval result. See [decision 0007](docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md).### Validating end-to-end@@ -878,7 +879,7 @@ The same tool, applied to any ontology, produces the same kind of improvement. T## Tools-109 tools organized by function, available as MCP tools (prefixed `onto_`) and CLI subcommands. A default build advertises all 109. Eight require an optional Cargo feature at call time: `embed`, `search`, `similarity` and `hnsw_build` need `embeddings`; `plugin_list` and `plugin_call` need `plugins`; `import-schema` and `sql-ingest` need `postgres` or `duckdb`.+112 tools organized by function, available as MCP tools (prefixed `onto_`) and CLI subcommands. A default build advertises all 112. Eight require an optional Cargo feature at call time: `embed`, `search`, `similarity` and `hnsw_build` need `embeddings`; `plugin_list` and `plugin_call` need `plugins`; `import-schema` and `sql-ingest` need `postgres` or `duckdb`.| Category | Tools | Purpose || --- | --- | --- |@@ -902,7 +903,8 @@ The same tool, applied to any ontology, produces the same kind of improvement. T| **Causal** | `certify_action` | Four-verdict causal certificate (EXECUTE / REJECT / EXPERIMENT / ABSTAIN); optional `causal-pywhy` feature enables backdoor identification || **Planner** | `plan_compile_pddl` `plan_classical` `plan_validate` | Compile + validate on the server; solver (Fast Downward) is a client-side subprocess || **Governance** | `policy_register` `policy_list` `policy_check` | Authorisation rules; composes with `certify_action` |-| **RAG** | `segment_retrieve` `graph_projection_lossy_check` | TBox-slice retrieval + projection-loss auditor |+| **RAG** | `segment_retrieve` `graph_projection_lossy_check` | TBox-slice retrieval + projection-loss auditor. The coverage ratio is a PROXY and not assurance: it rises as the slice grows, so a retriever tuned on it fetches more rather than the right thing |+| **RAG, the property** | `graph_projection_entailment_check` `onto_closure_diff` | Does the slice still ENTAIL the claims the answer rests on? Per-claim, with a machine-checked certificate for each one preserved, and a stop-the-line monotonicity gate on every run || **Extraction** | `extract_scaffold` `extract_validate` | Schema-guided structured-extraction prompt + validator || **CQs** | `cq_run` `verify_cq` `cq_verdicts_list` | Competency-question runner with pitfall hints + judgement loop || **Shape induction** | `shape_combinatorics` `shape_induce` | Property-combination lattice + data-driven SHACL induction |diff --git a/docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md b/docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.mdnew file mode 100644index 00000000..7275db72--- /dev/null+++ b/docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md@@ -0,0 +1,253 @@+# 0007 · A slice preserves a conclusion, or it does not++- **Status**: implemented, both forms · `src/projection_entailment.rs` (goal-directed, `preserve`,+ `graph_projection_entailment_check`) and `src/closure_diff.rs` (goal-free, `closure-diff`,+ `onto_closure_diff`) · every preserved-and-derived goal carries a sub-certificate `oo-cert`+ accepted, so `OOCert.certificate_sound` is named and no new Lean was written · the monotonicity+ differential runs on EVERY call and is disarmed, loudly, when its antecedent does not hold ·+ `coverage_ratio` is DEMOTED, not deleted · gated by `tests/lean_projection_entailment_test.rs`,+ `tests/closure_diff_test.rs`, `tests/projection_monotonicity_corpus_test.rs`,+ `tests/preserve_cli_test.rs` and `tests/gate_demonstration_test.rs`, the last of which feeds every+ gate the input built to trip it and PRINTS what the tool said+- **Written**: 2026-09-14+- **Related**: decision 0002 (an inference carries a certificate), whose format and checker this+ reuses unchanged; decision 0003 (a rule is data), whose verdict discipline and whose+ `entailed_under_supplied_rules` word this reuses verbatim; decision 0005 item 7 (the differential+ exported from a reasoned store), whose defect is re-armed here in a new place and guarded++## On the number++0007, not 0004 and not 0006. `0004` is a known gap: decision 0002 references it, it is absent from+`docs/decisions/`, and decision 0006 already records that the description-logic model certificate it+points at is implemented while only the record is missing. Writing someone else's decision record is+not this work's to do, so the gap is left rather than filled silently. `0006` is taken by the model+certificate record, which exists in a working tree on another branch and will land; taking the+number here would collide on merge.++## The problem++`src/projection_check.rs` audits a retrieved slice by reporting dropped predicates, dropped objects+and a `coverage_ratio` of projected triples over source triples. It is the primitive+`onto_segment_retrieve` is advertised to pair with, and it is the wrong measure, dangerously so,+because it looks like assurance.++A slice at 99% coverage can have dropped the one triple an answer depends on. A slice at 60%+coverage can preserve every conclusion that matters. Worse, the failure is silent and inverted: the+number goes UP as the projection gets larger, so a system tuned on it learns to retrieve more rather+than to retrieve the right thing. A retrieval-augmented answer grounded in such a slice can be FALSE+while every displayed metric is green.++That is not a hypothetical. Measured on `benchmark/reference/pizza-reference.owl`, a file this+repository ships: the whole ontology minus the single triple `NamedPizza rdfs:subClassOf Pizza`+scores `aggregate_coverage_ratio: 1.0` and `ok: true` over the twenty-three named-pizza seeds, while+`Veneziana rdfs:subClassOf Food`, a conclusion the source derives, is gone. The number cannot see+the damage at all. The converse, from the same file: a three-triple slice scores 0.00128 and+preserves every claim asked of it, each with a Lean-checked certificate. Both are pinned as tests.++## Decisions++1. **The property is entailment preservation, and it is asked per claim.** For a source `G`, a+ projection `P` and a set `Q` of ground positive triples an answer rests on, the question is not+ how much of `G` survived in `P`. It is whether, for each `q` in `Q`, `P` entails `q` exactly when+ `G` does, decided under ONE pinned rule profile.++2. **Four cells, and they are four different answers.** `G` yes / `P` yes is *preserved*, the only+ cell that can carry a certificate. `G` yes / `P` no is *lost by the projection*, the retrieval+ finding. `G` no / `P` yes is either a projection that is not a subset or an unsound engine, and+ is never a retrieval finding. `G` no / `P` no is `ungrounded_in_source`: the claim has no support+ in the graph at all, the generator invented it, and a better retriever will not fix it. A tool+ that reports the last two as "not preserved" sends every investigation to the wrong team, because+ a lossy retriever and a hallucinating generator have opposite fixes. `ungrounded_in_source` does+ not mean the claim is false: RDF entailment is open-world and this engine covers 29 of OWL 2 RL's+ 78 rules, so it means "not derivable from `G` under this profile" and nothing stronger.++3. **Membership is decided over the certificate FILES, not over an in-memory closure.**+ `Reasoner::run_full` runs twice with `materialize = false` and a `certificate_dir`, and every+ goal is looked up in `asserted.tsv` and `derivations.tsv` read back off disk. The Lean checker+ only ever sees those two files. If membership were decided against a set the checker never reads,+ the engine could report "derived" over a certificate that does not contain the derivation, and+ the verdict would be unchecked while wearing the checked word. Deciding over the artefact the+ checker reads makes that class of bug impossible rather than tested against.++4. **A preserved goal's certificate is a SUB-CERTIFICATE of the run's, and no new Lean was+ written.** The line concluding `q` is taken from `derivations.tsv`, its premises are walked to+ fixpoint, and the lines are emitted in ascending original-file order beside `P`'s own+ `asserted.tsv`. `oo-cert` exiting 0 over that pair is exactly "`P` entails `q`", machine-checked,+ under `OOCert.certificate_sound` unchanged. The ordering is valid and it is provable from the+ emitter rather than hoped for: `run_full` computes a round's conclusions from `triple_set` as it+ stood at the START of the round and inserts them only afterwards, so every premise of a line was+ asserted or concluded strictly earlier. `oo-cert` rejects a premise that is "neither asserted nor+ derived earlier", so the claim is load-bearing and+ `file_order_is_a_topological_order_of_the_derivations` pins it over the whole pizza ontology+ rather than leaving it as a comment.++5. **The free differential is not optional, and it is DISARMED rather than trusted.** OWL RL is+ monotone and `P` is a subset of `G`, so `closure(P) ⊆ closure(G)`. A conclusion of `P` that is not+ a conclusion of `G` is a SOUNDNESS BUG IN THE ENGINE, reported at `STOP_THE_LINE` with exit 2,+ never filed under "other". It is worth nothing unless its antecedent is established, and there+ are three conditions that fail on real input: the projection is not a subset (COMPUTED every run,+ never inferred from provenance, because a retriever that normalises an IRI or adds a tidy+ `rdf:type owl:Class` declaration produces a non-subset that looks like a faithful slice); blank+ nodes could not be matched; or either run stopped at the iteration cap rather than a fixpoint,+ which makes the larger closure a LOWER BOUND and manufactures spurious `P`-only entailments. Each+ disarming is REPORTED with its own reason, because a green `violations: []` under a disarmed gate+ means "we did not look" and the two must never render the same.++6. **`coverage_ratio` is demoted, not deleted, and the label travels in the payload.**+ `check_projection_loss` keeps running and its output is nested under `coverage_proxy` with+ `is_a_warrant: false` and one sentence a reader cannot miss, carried as a FIELD rather than a doc+ comment so a renderer that walks only the data still emits it. The same sentence went into the+ `graph_projection_lossy_check` tool description, because a tool description is the text an agent+ actually reads when choosing, and that is where the trap was living unlabelled. Removing the+ number would lose a cheap signal; leaving it unlabelled would keep the trap.++7. **Three kinds of word, never collapsed.** `preserved_checked` names+ `OOCert.certificate_sound`. `preserved_under_supplied_rules_checked` names+ `OOCert.horn_certificate_sound`, carries the table's sha256, and is never shortened to the plain+ word, because a rule reading "every supplier is compliant" produces certificates that check green+ for ever. `preserved_asserted` is exact-string membership and names no theorem, so a lookup can+ never inflate the checked count. `preserved_unchecked` is the engine's opinion about its own+ output and carries the install line and the exact `lake exe oo-cert` command.+ `an_unchecked_result_never_prints_the_checked_word` asserts over the SERIALISED report rather+ than over the enum, because the enum is where the discipline is easy and the serialisation is+ where it leaks, and it carries no skip guard, so it is the one gate a machine without Lean still+ enforces.++8. **A negative carries no certificate in this layer, ever.** `q ∉ closure(P)` is the engine's+ opinion bounded by a rule table implementing 29 of OWL 2 RL's 78 rules, so the word is+ `lost_under_profile_unchecked`. Printing "the projection does not entail `q`" flat would do in the+ negative direction exactly what `coverage_ratio` does in the positive: present an unchecked+ judgement in the grammar of a warrant.++9. **A rejected sub-certificate stops the line and downgrades to nothing.** If `oo-cert` exits 1 on a+ slice this module assembled, the defect is in the extractor or in the emitter's premise order.+ The tempting code is `.unwrap_or(PreservedUnchecked)`, which converts a defect in this code into a+ marginally weaker verdict nobody will ever investigate, and it is precisely the treatment+ `tools/shacl_differential.py` refuses to give a `FALSE_CLEAN`. Exit 2, `what:+ "certificate_rejected"`, and `a_rejected_slice_never_downgrades_to_preserved_unchecked` asserts+ the non-downgrade explicitly.++10. **Refusals are counted in the headline.** A blank node in a goal is an existential, not a claim.+ "No supplier is sanctioned" is not a triple, and mapping absence-from-the-closure onto such a+ claim would convert an open-world absence into a closed-world fact with a certificate stapled to+ it, which is the laundering this work exists to attack, produced by the anti-laundering tool.+ Both are refused BY NAME, the closed-world message points at `onto_shacl`, and the count sits in+ the headline so a refusal cannot shrink the denominator unnoticed.++11. **An empty goal set is an error, not a green report.** Every aggregate over zero goals is+ trivially perfect, which is decision 0006 item 8's empty-problem shape, and "all my goals were+ refused" is the realistic way to arrive at zero. The error says how many were refused.++12. **Both forms ship, and they share one implementation.** The goal-directed form is the online one,+ for auditing an answer at query time. The closure-diff form supplies no goals and computes+ `closure(G) \ closure(P)`, which is what an offline audit of a retrieval STRATEGY needs.+ `src/closure_diff.rs` reuses the certificate index, the checker runner, the subset precondition,+ the skolemiser and the differential from `src/projection_entailment.rs`, so there is exactly one+ place in the crate where each verdict word is produced.++13. **The closure-diff headline is `lost_in_projection_vocabulary`, and its gaming direction is in+ the payload.** `|closure(G) \ closure(P)|` grows with `|G|` and is nearly all of `closure(G)` for+ any real slice, so minimising it means retrieving more: the same perverse gradient wearing a+ better name. A lost entailment is dangerous exactly when every one of its terms occurs in `P`,+ because then an answer grounded in `P` is a claim over those terms. That number has its own+ gaming direction, since shrinking `terms(P)` shrinks it, and the report says so as a field, not only+ in the docs, because the docs are not what a dashboard renders.++## What the monotonicity differential found++Run for real over the shipped corpus (`tests/projection_monotonicity_corpus_test.rs`): each ontology+skolemised, sliced by `onto_segment_retrieve` from its twelve busiest subjects at two hops, both+closures certified and diffed.++| | |+|---|---|+| ontologies swept | 275 |+| monotonicity gate ARMED | 275 |+| gate disarmed | 0 |+| source certificates the Lean checker ACCEPTED | 275 |+| **monotonicity violations** | **0** |+| incompleteness warnings | 0 |+| conclusions lost, total | 117,105 |+| of them over terms the slice itself mentions | 899 |+| excluded (over the 1 MB sweep cap, or unparseable) | 9, each named |+| wall clock | 41.6 s |++Nothing was found, and that is the result. It is worth more than it looks because the gate was+ARMED on all 275 rather than disarmed: subsethood was computed and held, both runs reached a+fixpoint, and every source closure carried a certificate `oo-cert` accepted. A sweep in which the+gate is disarmed everywhere establishes nothing, so the two counts are reported separately and the+test fails if the gate is disarmed on more than half the corpus.++## What was found on the way, and fixed++1. **`onto_segment_retrieve` emitted slices that do not parse.** Every term was wrapped in angle+ brackets unconditionally, so a blank-node `owl:Restriction` superclass came out as `<_:b0>`,+ which is not a legal IRI. Since issue #93 `load_turtle` collects all or nothing, so ONE+ restriction superclass made the ENTIRE slice unparseable, and `check_projection_loss` then+ reported `projection_parses: false` with `aggregate_coverage_ratio: 0.0` and no diagnosis. The+ two tools are advertised as a pair, and the pair was broken for essentially every OWL ontology in+ this repository. Measured on `benchmark/ontoaxiom/.../pizza.ttl` and+ `benchmark/reference/pizza-reference.owl`. Blank nodes are now written bare, the angle-bracket+ trim no longer eats the closing bracket of a typed literal's datatype IRI, and+ `a_slice_with_a_blank_node_superclass_still_parses` pins it.++2. **`check_projection_loss` reported `ok: true` on a projection holding MORE than the source.**+ `coverage_ratio` clamps with `.min()`, so a seed whose slice carries triples the source does not+ read exactly 1.0 with empty dropped lists. A hallucinating retriever, or a slice of a different+ graph, scored a clean bill of health. The clamp stays, because an unclamped "ratio" above 1.0 is+ not a ratio; the surplus is now named in `seeds_with_surplus` and `ok` requires it to be empty.++3. **Literal canonicalisation happens on STORE INSERT, not at parse.** Measured: oxigraph's parser+ returns `"01"^^xsd:integer` exactly as written, and the same literal comes out of `all_triples`+ as `"1"^^xsd:integer`. A goal routed through the parser alone therefore matches nothing in a+ certificate and is reported LOST, which is a false loss with a green-looking pipeline round it. Goals are+ now round-tripped through a real `GraphStore`, one triple per named graph so a set cannot collapse+ duplicates or shift the caller's pairing, and both `as_written` and `goal` are printed.++4. **`GraphStore::canonicalize_blank_nodes` is the wrong tool and is now pinned as such.** RDFC-1.0+ labels are a function of the WHOLE graph. Measured on `pizza-reference.owl`, taking a genuine+ subgraph: canonicalising both sides separately and diffing reports 630 triples of the subgraph as+ absent from the source, out of 2,276, while comparing the store's own labels reports 0. It is+ correct for "are these two graphs isomorphic", which is not the question, and it looks+ principled, which is worse. `skolemise` is the answer, and+ `canonicalising_both_sides_separately_is_worse_than_doing_nothing` stops a future implementer+ reaching for the method that is already in the repository.++5. **The FNV-1a 64 digest was written with the prime `0x1000000001b3`, one zero too many.** Nothing+ would have looked broken, because a digest is only ever compared against itself. It was caught by+ pinning the published test vectors instead of a round trip through the function, which would have+ agreed with any constant at all.++## What this does not claim++- **Nothing about the negative side.** `lost_under_profile_unchecked` is the engine's opinion,+ bounded by a rule table covering 29 of OWL 2 RL's 78 rules. The escalation the design allows for is+ a machine-checked countermodel over `P` from the model-certificate layer, whose word would be+ `lost_not_entailed_under_unproved_translation` and which rides on `OwlLean.adequacy` plus a+ Rust-to-Lean correspondence that decision 0005 item 2 states is pinned by tests and NOT proved.+ That layer is not on this branch, so the escalation is **not built**, and the default word stands.+- **`OOCert`'s entailment is not datatype-aware.** `"1"^^xsd:int` and `"1"^^xsd:integer` are two+ distinct goals, and a `preserved_checked` on one says nothing about the other. In the `limits`+ block of every report, not only here.+- **Blank-node subgraph matching is not solved and will not be.** Deciding whether one graph is a+ subgraph of another up to blank-node renaming is simple entailment: NP-complete in general,+ polynomial only when the target is ground. The `not_compared` bucket is a consequence of that+ complexity, documented as such so nobody tries to close it, and skolemising the source before the+ retriever sees it is what empties it.+- **The proxy's own limits are named, not fixed.** `neighbourhood_pairs` is subject-only, so an+ inbound-edge loss is invisible to it, and its SPARQL carries `LIMIT 1000`, so a seed with more+ than a thousand outbound triples has its ratio computed against a truncated source. Both are+ reported (`truncated_seeds`, `known_limits`) and left to their own change.++## Still not done++- **No CI leg installs Lean for these tests.** They skip loudly through `common::skip_unless` and the+ existing `lean` job's `OO_REQUIRE_FIXTURES=1` makes that skip fatal; wiring the new test files into+ that job is a one-line change to `.github/workflows/ci.yml` and is done, but nothing has run it on+ a runner yet.+- **The corpus sweep uses a 1 MB cap** rather than the certificate test's 4 MB, because it does two+ reasoner runs and a retrieval per file. Four ontologies are excluded by it and are named in the+ output. Raising it is a question of CI budget, not of correctness.+- **`closure_diff` has no Horn arm.** A supplied rule table is supported in the goal-directed form+ only. The closure-diff form would need to read `horn.tsv` on both sides and run `oo-horn check`,+ which is the same shape and is simply not written.diff --git a/docs/interop-with-graph-platforms.md b/docs/interop-with-graph-platforms.mdindex 3efffbdc..6ba5def8 100644--- a/docs/interop-with-graph-platforms.md+++ b/docs/interop-with-graph-platforms.md@@ -15,7 +15,7 @@ entities and relationships, and assemble a graph. They are pipelines, writtenin Python, with orchestration, storage, and retrieval included.Open Ontologies **verifies and governs**: it is a single Rust binary with no-model client inside it, exposing 109 MCP tools over a formal store. Its job+model client inside it, exposing 112 MCP tools over a formal store. Its jobstarts where extraction ends.```diff --git a/docs/lean-certificates.md b/docs/lean-certificates.mdindex 63a03004..e6f9d1a9 100644--- a/docs/lean-certificates.md+++ b/docs/lean-certificates.md@@ -132,9 +132,14 @@ kept in `tests/lean_certificate_test.rs` as a forged certificate the checker musThe `lean` job builds `lean/` (which is the proof check), then runs`tests/lean_certificate_test.rs` with `OO_REQUIRE_FIXTURES=1`. Every RDF file the repositorytracks, enumerated from `git ls-files`, is loaded, reasoned under `owl-rl-ext` with a certificate,-and the certificate checked: 122 files and 37,133 derivations at the time of writing. Files over-4 MB and files that do not parse are listed with the reason, never dropped silently. The same test-appends three forgeries and requires each to be rejected.+and the certificate checked. Files over 4 MB and files that do not parse are listed with the reason,+never dropped silently. The same test appends three forgeries and requires each to be rejected.++The corpus was 122 files and 37,133 derivations when that was written. Counted on 14 September 2026+under the test's own `SKIP_DIRS` filter it is **290 tracked RDF files, 21,256,445 bytes (20.3 MiB)**, one of which+(`case-studies/skills-england-occupational-maps/ontology/occupational-map.ttl`, 5.70 MB) is over the+4 MB cap and is therefore already excluded and named. The derivation count is not restated here,+because the only honest source for it is the run's own output.The corpus used to be five hand-named directories, three of which hold no RDF, so 46% of therepository's RDF was never walked and was excluded without being named. Widening it is what@@ -176,6 +181,42 @@ The Rust reasoner does not yet evaluate a supplied rule table, so today this laycertificates rather than producing them. See[decision 0003](decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).+## Does a retrieved slice still support the answer?++A certificate says the engine's inferences over ONE graph are entailed by it. A GraphRAG pipeline+asks a different question: an answer was grounded in a retrieved slice, so does that slice still+entail the claims the answer rests on?++`preserve` and `graph_projection_entailment_check` ask it per claim, and every preserved-and-derived+claim gets a SUB-CERTIFICATE extracted from the projection's own `derivations.tsv` and checked by+`oo-cert` against the projection's own `asserted.tsv`. No new Lean was written:+`OOCert.certificate_sound` covers it unchanged, and the sub-certificate's line order is valid+because `run_full` computes a round's conclusions from the closure as it stood at the start of the+round, so every premise was asserted or concluded strictly earlier.++The verdict table follows the one above.++| verdict | theorem | means |+|---|---|---|+| `preserved_checked` | `OOCert.certificate_sound` | the projection entails the claim, machine-checked |+| `preserved_under_supplied_rules_checked` | `OOCert.horn_certificate_sound` | true in every model of the projection that **also satisfies** your rules. Carries the table's digest. Never shortened |+| `preserved_asserted` | none | the claim is literally in the slice. A lookup, not a theorem |+| `preserved_unchecked` | none | the ENGINE derived it and no checker looked |+| `lost_under_profile_unchecked` | none | not derivable from the slice under this profile, bounded by a rule table covering 29 of the profile's 78 rules |+| `ungrounded_in_source` | none | NEITHER graph derives it, so the generator invented it and a better retriever will not help |++Every run also checks monotonicity: OWL RL is monotone and a projection is a subset, so anything the+projection entails and the source does not is a soundness bug in this engine, reported at+`STOP_THE_LINE` rather than as a retrieval result. It is disarmed, loudly and with its own reason,+when the projection is not a subset, when blank nodes could not be matched, or when either run+stopped at the iteration cap instead of a fixpoint.++Run over the shipped corpus, 275 ontologies swept with the gate armed on all 275 and every source+certificate accepted by `oo-cert`, it found nothing.++See [docs/projection-entailment.md](projection-entailment.md) and+[decision 0007](decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md).+## Known limitationsStated rather than discovered later.diff --git a/docs/projection-entailment.md b/docs/projection-entailment.mdnew file mode 100644index 00000000..6b5c327d--- /dev/null+++ b/docs/projection-entailment.md@@ -0,0 +1,232 @@+# Does the slice still support the answer?++`graph_projection_lossy_check` reports how much of a seed's neighbourhood survived a retrieval.+That number is a proxy. It is neither necessary nor sufficient for the property that matters, and it+moves the wrong way: it rises as the projection grows, so a retriever tuned on it learns to fetch+more rather than to fetch the right thing.++The property is **entailment preservation**. For a source `G`, a retrieved slice `P` and a claim `q`+an answer rests on, the question is whether `P` entails `q` exactly when `G` does. That is decidable+under the engine's rule tables, it is checkable, and every preserved claim carries a certificate the+Lean checker accepts.++This page is the how-to. The design and its limits are in+[decision 0007](decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md).++## The number that cannot see the damage++Measured on `benchmark/reference/pizza-reference.owl`, which this repository ships. Seeds are the+twenty-three classes under `NamedPizza`; the claim is `Veneziana rdfs:subClassOf Food`, which the+source derives through `NamedPizza rdfs:subClassOf Pizza` and `Pizza rdfs:subClassOf Food`.++| projection | `aggregate_coverage_ratio` | `ok` | the claim |+|---|---|---|---|+| the whole ontology minus that one `subClassOf` triple | **1.00000** | **true** | **lost** |+| three triples: `Veneziana ⊑ NamedPizza ⊑ Pizza ⊑ Food` | **0.00128** | false | **preserved, checked** |++Both rows are tests, in `tests/lean_projection_entailment_test.rs`. The first is why the coverage+ratio cannot be read as assurance; the second is why deleting it and reporting the size of the+difference set instead would not help either.++## Ask it of the claims an answer rests on++```bash+# The store is in-memory per process, so `batch` is the way to load a source+# and then ask about a slice of it in one run, exactly as for+# `reason --certificate`.+open-ontologies --no-connect --data-dir /tmp/store batch - <<'EOF'+load benchmark/reference/pizza-reference.owl+preserve --projection /tmp/slice.ttl --goals /tmp/goals.ttl --out /tmp/preserve \+ --profile owl-rl-ext \+ --seed https://raw.githubusercontent.com/owlcs/pizza-ontology/refs/heads/master/pizza.owl#Veneziana+EOF+```++`--goals` is a Turtle document in which every triple is a claim. It is parsed by the SAME parser the+store uses and round-tripped through a store, which is the only thing that makes a caller's spelling+of a term comparable with the interner's: `"01"^^xsd:integer` is stored as `"1"^^xsd:integer`, and a+goal that skipped the store would match nothing and be reported lost. A TSV works too, with+`--goals-skip-columns 1` so `derivations.tsv` from `reason --certificate` pipes straight in.++Over MCP, `graph_projection_entailment_check` takes `goals_ttl` and either `projected_ttl` or+`projection_graph`.++Exit codes: 0 every goal preserved and nothing refused, 1 something was lost, ungrounded or refused,+2 a stop-the-line disagreement.++### Where the goals come from++Four sources, ranked by how much trust each needs. The tool never extracts claims itself: a server+that decomposed an answer into triples would be embedding a language model in the server, which this+project has ruled out.++1. **The BGP of the query the answer was rendered from, with the answer's bindings substituted.** No+ trust in a generator at all, fully mechanical. `projection_entailment::goals_from_bindings`.+2. **The generator's own declared support set.** At query time the system knows what it is about to+ assert, so it lists the triples each sentence rests on before emitting. This is the intended+ caller.+3. **A prior full-graph certificate.** `derivations.tsv` over `G`, filtered to the conclusions that+ mention the seeds, turns the tool into a regression suite for the retriever at index-build time.+4. **Competency questions**, which an ontology project already has and which are goals by+ construction.++## Ask it of everything at once++```bash+open-ontologies --no-connect --data-dir /tmp/store batch - <<'EOF'+load benchmark/reference/pizza-reference.owl+closure-diff --projection /tmp/slice.ttl --out /tmp/diff --profile owl-rl-ext+EOF+```++No goals. Both graphs are reasoned to a fixpoint under the same table and `closure(G) \ closure(P)`+is reported. This is the offline form, for auditing a retrieval **strategy** rather than one answer,+and `SourceClosure::build` is paid once so a run comparing fifty projections pays for `closure(G)`+once.++The headline is `lost_in_projection_vocabulary`, not `lost_total`. `|closure(G) \ closure(P)|` grows+with `|G|` and is nearly all of it for any real slice, so minimising it means retrieving more: the+same perverse gradient wearing a better name. A lost conclusion is dangerous exactly when every one+of its terms occurs in `P`, because then an answer grounded in `P` is a claim over those terms. That+number has its own gaming direction, since shrinking `terms(P)` shrinks it, and the report says so in+the payload.++Each lost inference names the premises `closure(P)` does not hold. That is the triple the retriever+dropped, and the conclusion went with it.++## The verdicts++Three kinds of word, never collapsed.++| verdict | produced by | theorem | means |+|---|---|---|---|+| `preserved_checked` | the goal is in `P`'s `derivations.tsv`, the sub-certificate was extracted, and `oo-cert` exited 0 over `P`'s own `asserted.tsv` | `OOCert.certificate_sound` | `P` entails the goal, true in every model of `P` under `lean/OOCert/Semantics.lean`. Machine-checked |+| `preserved_under_supplied_rules_checked` | the same, over a SUPPLIED Horn table, pronounced by `oo-horn check` | `OOCert.horn_certificate_sound` | true in every model of `P` that **also satisfies** the supplied rules. The rules are assumed and never checked. Carries the table's sha256. Never shortened |+| `preserved_asserted` | the goal is in `P`'s `asserted.tsv` by exact string | none, and none is required | the goal is literally in the slice. Set membership over the canonical spelling. Not a theorem and it does not pretend to be |+| `preserved_unchecked` | the goal is derived and no checker ran | none | the ENGINE derived it. Its opinion about its own output, which is what the certificate layer exists to stop being trusted. The report carries the install line and the exact `lake exe oo-cert` command |+| `lost_under_profile_unchecked` | in `G`'s certificate and in neither part of `P`'s | none | not derivable from `P` under this profile. The engine implements 29 of OWL 2 RL's 78 rules, so this is bounded by the rule table and is not "`P` does not entail it" |+| `ungrounded_in_source` | in NEITHER certificate | none | the source does not derive it either, so the projection did not lose it. The fix is in the generator and not the retriever. Open-world: this is not "false" |+| `projection_only` | in `P`'s certificate and not in `G`'s | none, and it is a defect report | see the differential below |+| `certificate_rejected` | the checker REJECTED the sub-certificate this code assembled | none | a defect HERE or in the emitter. It downgrades to nothing, exits 2, and never becomes `preserved_unchecked` |+| `refused` | not a positive ground triple | none | counted in the headline so a refusal cannot shrink the denominator unnoticed |++For the closure diff, the warrant on a lost row is one of `checked`, `asserted_in_source` (a lookup,+so the checked count cannot rise without the checker running) and `engine_opinion`.++`coverage_ratio`, `aggregate_coverage_ratio`, `total_dropped_predicates` and+`total_dropped_objects` are not verdicts. They live under `coverage_proxy`, carry+`is_a_warrant: false`, and carry the label in the payload.++## The free differential++OWL RL is monotone and `P` is a subset of `G`, so `closure(P) ⊆ closure(G)`. A conclusion of `P` that+is not a conclusion of `G` is a **soundness bug in the engine**, not a retrieval finding, and it+exits 2 with `severity: "STOP_THE_LINE"`.++It is only allowed to speak when its antecedent holds:++| subset verified | both at a fixpoint | `P`-only conclusions | outcome |+|---|---|---|---|+| yes | yes | none | `armed`, nothing to report |+| yes | yes | some | `STOP_THE_LINE`, `monotonicity_violated`, exit 2 |+| no | either | any | `disarmed`, `projection_is_not_a_subset`. A `P`-only entailment from a non-subset is ordinary |+| yes | no | any | `disarmed`, `fixpoint_not_reached`. A truncated closure is a lower bound and cannot refute anything |+| blank nodes unmatched | either | any | `disarmed`, `blank_nodes_unmatched` |++A second stop-the-line, on the same block shape, is `certificate_rejected`, when `oo-cert` exits 1 on+a sub-certificate this code assembled. That means the extractor or the emitter is wrong. It+downgrades to nothing.++Subsethood is **computed** every run, never inferred from provenance: a retriever that normalises+IRIs, re-prefixes, inlines an imported vocabulary or adds a tidy `rdf:type owl:Class` declaration+produces a non-subset that looks like a faithful slice.++### What it found++Run over the shipped corpus, each ontology skolemised, sliced by `onto_segment_retrieve` from its+twelve busiest subjects at two hops, both closures certified and diffed+(`tests/projection_monotonicity_corpus_test.rs`):++```+swept 275+gate ARMED 275+gate DISARMED 0+source certificate CHECKED 275+VIOLATIONS (stop-the-line) 0+incompleteness warnings 0+conclusions lost, total 117105+ of them in the slice's own vocabulary 899+excluded 9 (four over the 1 MB sweep cap, five unparseable; each named)+seconds 41.6+```++Nothing was found. That is worth more than it looks because the gate was ARMED on all 275 rather+than disarmed: subsethood held, both runs reached a fixpoint, and every source closure carried a+certificate `oo-cert` accepted. A sweep in which the gate is disarmed everywhere establishes+nothing, so the test fails if the gate was armed on fewer than half the corpus.++## Watching the gates fail++A gate that cannot fail is decoration, and a gate whose failure nobody has read is close to it.+`tests/gate_demonstration_test.rs` feeds each gate the input built to trip it, prints what the tool+actually said, and asserts the same thing:++```bash+cargo test --test gate_demonstration_test -- --nocapture+```++Thirteen gates, each with its broken input named on the line above the tool's answer. Nothing in it+is a mock.++## Blank nodes++`owl:Restriction` superclasses, `owl:intersectionOf` list cells and `owl:Axiom` reification are all+blank-node bearing, so a TBox slice of any real ontology hits this immediately. Oxigraph mints fresh+labels on every parse, so a slice serialised and re-read differs textually from the source in every+blank-node-bearing triple: the subset check reports spurious extras and the differential fires+against a correct engine.++**Skolemise the source before the retriever sees it.** `projection_entailment::skolemise` replaces+every blank node with an IRI under `https://open-ontologies.org/.well-known/genid/`, which RDF 1.1+section 3.5 reserves for exactly this. `closure-diff` does it by default. Measured on+`pizza-reference.owl`: 400 blank nodes skolemised, a 783-triple retrieved slice, zero triples not in+the source, the gate armed.++**Do not reach for `GraphStore::canonicalize_blank_nodes`.** RDFC-1.0 labels are a function of the+WHOLE graph, so the same blank node canonicalises differently in a slice than in the source, exactly+because the slice has fewer triples around it. Measured on `pizza-reference.owl` against a genuine+subgraph: canonicalising both sides separately and diffing reports 630 triples of the subgraph as+absent from the source, out of 2,276, where comparing the store's own labels reports 0. It is correct+for "are these two graphs isomorphic", which is not the question, and it looks principled, which is+worse. `canonicalising_both_sides_separately_is_worse_than_doing_nothing` pins it.++Deciding whether one graph is a subgraph of another up to blank-node renaming is simple entailment:+NP-complete in general, polynomial only when the target is ground. The `not_compared` bucket is a+consequence of that complexity rather than an unfinished feature, and it is never subtracted from a+denominator.++## What is refused, and why++- **A blank node in a goal** is an existential, not a claim. This layer asks whether a ground triple+ is entailed and cannot ask "there exists something such that".+- **A closed-world or negative claim**: "no supplier is sanctioned", "exactly one registered+ address". Not a triple. Reading "absent from the closure" as "the claim holds" would convert an+ open-world absence into a closed-world fact with a certificate stapled to it, which is the+ laundering this tool exists to attack, produced by the anti-laundering tool. The refusal message+ points at `onto_shacl`.+- **An empty goal set** is an error, not a green report. Every aggregate over zero goals is trivially+ perfect, and "all my goals were refused" is the realistic way to arrive at zero.++## Known limits++- `OOCert`'s entailment is not datatype-aware. `"1"^^xsd:int` and `"1"^^xsd:integer` are two distinct+ goals, and a `preserved_checked` on one says nothing about the other.+- A `lost_*` verdict is an engine opinion about a negative and carries no certificate in this layer,+ ever.+- The rule table is this engine's, not W3C's: 29 of OWL 2 RL's 78 rules.+- The coverage proxy is subject-only, so an inbound-edge loss is invisible to it, and its SPARQL+ carries `LIMIT 1000`, so a seed with more than a thousand outbound triples has its ratio computed+ against a truncated source. Seeds in that position are listed in `truncated_seeds`.+- A store that has been reasoned into makes `asserted.tsv` a lie, because the engine's own output+ appears as an axiom and `ungrounded_in_source` becomes unreachable.+ `source_hygiene.source_side_unreliable` says so; reload the source from its files.diff --git a/src/batch.rs b/src/batch.rsindex afee4117..bf37c35c 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -70,8 +70,21 @@ impl BatchRunner {"result": result,}));+ // A command that reports its own `exit_code` keeps it through the+ // batch. `preserve` and `closure-diff` are the only ones with more+ // than two outcomes: clean, something was lost, and a stop-the-line+ // disagreement that means a defect in the engine or in this code.+ // Without this the exit code was invisible in the ONLY path these+ // commands can realistically run through, since the store is+ // in-memory per process, and a stop-the-line would have exited 0.+ if let Some(c) = result.get("exit_code").and_then(|c| c.as_i64())+ && c > exit_code as i64+ {+ exit_code = c as i32;+ }+if has_error {- exit_code = 1;+ exit_code = exit_code.max(1);if bail {break;}@@ -99,6 +112,8 @@ impl BatchRunner {"lint" => self.exec_lint(&cmd.args),"reason" => self.exec_reason(&cmd.args),"fol" => self.exec_fol(&cmd.args),+ "preserve" => self.exec_preserve(&cmd.args),+ "closure-diff" | "closure_diff" => self.exec_closure_diff(&cmd.args),"shacl" => self.exec_shacl(&cmd.args),// The CLI subcommand is spelled with a hyphen and this arm accepted// only the underscore, so every documented invocation was rejected@@ -305,6 +320,104 @@ impl BatchRunner {serde_json::from_str(&result).unwrap_or(json!({"raw": result}))}+ /// Entailment preservation over a supplied goal set.+ ///+ /// Needed here for the same reason `reason --certificate` is: the store is+ /// in-memory per process, so `batch` is the only way to load a source and+ /// then ask about a slice of it in one run.+ fn exec_preserve(&self, args: &[String]) -> Value {+ use crate::projection_entailment as pe;+ let Some(goals_path) = Self::flag_value(args, "--goals") else {+ return json!({"error": "preserve requires --goals FILE"});+ };+ let Some(out) = Self::flag_value(args, "--out") else {+ return json!({"error": "preserve requires --out DIR"});+ };+ let ttl_path = Self::flag_value(args, "--projection");+ let graph_name = Self::flag_value(args, "--projection-graph");+ if ttl_path.is_some() == graph_name.is_some() {+ return json!({"error":+ "preserve needs exactly one of --projection FILE and --projection-graph IRI. A \+ named graph of the loaded store keeps blank node identity, so P ⊆ G can be \+ verified over every triple rather than over ground triples only"});+ }+ let goals_text = match std::fs::read_to_string(&goals_path) {+ Ok(t) => t,+ Err(e) => return json!({"error": format!("cannot read {goals_path}: {e}")}),+ };+ let skip: usize = Self::flag_value(args, "--goals-skip-columns")+ .and_then(|v| v.parse().ok())+ .unwrap_or(0);+ // A TSV is asked for by --goals-skip-columns or by a .tsv name; Turtle+ // otherwise. The goal document goes through the store's OWN parser+ // either way, which is the only thing that makes a caller's spelling of+ // a term comparable with the interner's.+ let parsed = if skip > 0 || goals_path.ends_with(".tsv") {+ pe::parse_goals_tsv(&goals_text, skip)+ } else {+ pe::parse_goals_turtle(&goals_text)+ };+ let (goals, refused) = match parsed {+ Ok(v) => v,+ Err(e) => return json!({"error": e.to_string()}),+ };+ let opts = pe::Opts {+ profile: Self::flag_value(args, "--profile").unwrap_or("owl-rl".into()),+ rules: Self::flag_value(args, "--rules").map(std::path::PathBuf::from),+ work_dir: std::path::PathBuf::from(&out),+ checker: Self::flag_value(args, "--checker").map(std::path::PathBuf::from),+ require_checker: args.iter().any(|a| a == "--require-checker"),+ seed_iris: Self::flag_values(args, "--seed"),+ };+ let projection_ttl;+ let projection = match (&ttl_path, &graph_name) {+ (Some(p), _) => match std::fs::read_to_string(p) {+ Ok(t) => {+ projection_ttl = t;+ pe::Projection::Turtle(&projection_ttl)+ }+ Err(e) => return json!({"error": format!("cannot read {p}: {e}")}),+ },+ (_, Some(g)) => pe::Projection::NamedGraph(g),+ _ => unreachable!("checked above"),+ };+ match pe::check_entailment_preservation(&self.graph, projection, &goals, &refused, &opts) {+ Ok(r) => serde_json::to_value(r).unwrap_or_else(|e| json!({"error": e.to_string()})),+ Err(e) => json!({"error": e.to_string()}),+ }+ }++ /// The goal-free form: which conclusions a projection preserves.+ fn exec_closure_diff(&self, args: &[String]) -> Value {+ use crate::closure_diff as cd;+ let Some(proj) = Self::flag_value(args, "--projection") else {+ return json!({"error": "closure-diff requires --projection FILE"});+ };+ let Some(out) = Self::flag_value(args, "--out") else {+ return json!({"error": "closure-diff requires --out DIR"});+ };+ let ttl = match std::fs::read_to_string(&proj) {+ Ok(t) => t,+ Err(e) => return json!({"error": format!("cannot read {proj}: {e}")}),+ };+ let opts = cd::DiffOptions {+ profile: Self::flag_value(args, "--profile").unwrap_or("owl-rl-ext".into()),+ out: std::path::PathBuf::from(&out),+ checker: Self::flag_value(args, "--checker").map(std::path::PathBuf::from),+ skolemise_source: Self::flag_value(args, "--skolemise-source")+ .map(|v| v != "false")+ .unwrap_or(true),+ max_rows: Self::flag_value(args, "--max-rows")+ .and_then(|v| v.parse().ok())+ .unwrap_or(200),+ seed_iris: Self::flag_values(args, "--seed"),+ };+ match cd::closure_diff(&self.graph, &ttl, &opts) {+ Ok(r) => serde_json::to_value(r).unwrap_or_else(|e| json!({"error": e.to_string()})),+ Err(e) => json!({"error": e.to_string()}),+ }+ }+fn exec_shacl(&self, args: &[String]) -> Value {use crate::shacl::ShaclValidator;let shapes_path = match args.first() {@@ -632,6 +745,19 @@ impl BatchRunner {.position(|a| a == flag).and_then(|i| args.get(i + 1).cloned())}++ /// Every value of a repeatable flag, in order (e.g. `--seed A --seed B`).+ ///+ /// `flag_value` returns the FIRST, which silently drops the rest. A seed+ /// list that lost all but its first element would produce a coverage proxy+ /// over one seed while the report said it was over twenty.+ fn flag_values(args: &[String], flag: &str) -> Vec<String> {+ args.iter()+ .enumerate()+ .filter(|(_, a)| a.as_str() == flag)+ .filter_map(|(i, _)| args.get(i + 1).cloned())+ .collect()+ }}/// Parse batch input — auto-detects JSON array vs line-per-command format.diff --git a/src/closure_diff.rs b/src/closure_diff.rsnew file mode 100644index 00000000..977c27b8--- /dev/null+++ b/src/closure_diff.rs@@ -0,0 +1,898 @@+//! Entailment preservation under graph projection, by closure difference.+//!+//! [`crate::projection_entailment`] asks the question of a SUPPLIED set of+//! goals: the online form, for auditing one answer. This module supplies no+//! goals and computes the whole thing: reason both graphs to a fixpoint under+//! the same rule table and report `closure(G) \ closure(P)`. That is the form+//! an offline audit of a retrieval STRATEGY needs, because a strategy is not+//! evaluated against one question, it is evaluated against every conclusion it+//! could ever be asked to ground.+//!+//! Everything shared with the goal-directed form is shared rather than+//! re-implemented: the certificate index, the checker runner, the subset+//! precondition, the skolemiser and the monotonicity differential all live in+//! [`crate::projection_entailment`], so there is exactly ONE place in this+//! crate where a verdict word is produced.+//!+//! # Replacing a ratio with a count would reproduce the disease+//!+//! `closure(G) \ closure(P)` is enormous by construction: `P` is a slice, so+//! the difference is nearly all of `closure(G)`, and it grows with `|G|`.+//! Minimising it means retrieving MORE, which is the same perverse gradient+//! wearing a better name. The headline is therefore+//! `lost_in_projection_vocabulary`: a lost entailment is dangerous exactly when+//! every one of its terms occurs in `P`, because then an answer grounded in `P`+//! is a claim over those terms and could have rested on it. That number has its+//! own gaming direction, shrinking `terms(P)` shrinks it, and the report says+//! so in the payload rather than only in the docs.+//!+//! # Cost+//!+//! `closure(G)` is the expensive half and `G` does not change between retrieval+//! strategies, so [`SourceClosure::build`] is paid once and [`SourceClosure::diff`]+//! is run N times. The cache is the certificate directory: `asserted.tsv` and+//! `derivations.tsv` already exist, are already the format, and `oo-cert` has+//! already been run over them. [`SourceClosure::load`] RE-RUNS the checker+//! rather than trusting a verdict read off disk, because a cached verdict would+//! be an unchecked result wearing the checked word one indirection away.++use crate::graph::GraphStore;+use crate::projection_entailment as pe;+use crate::projection_entailment::{+ CertKind, CertificateIndex, CheckerStatus, CoverageProxy, Guards, Spelled, LAKE_INSTALL,+ STOP_THE_LINE,+};+use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};+use std::path::{Path, PathBuf};+use std::sync::Arc;++/// An N-Triples-spelled triple, exactly as the store's interner holds it and+/// exactly as `asserted.tsv` writes it.+pub type NtTriple = Spelled;++// ───────────────────────────────────────────────────────────────────────────+// Verdict vocabulary+// ───────────────────────────────────────────────────────────────────────────++/// Why the source is entitled to a conclusion. NEVER COLLAPSED.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Warrant {+ /// The triple IS in the asserted graph. No rule fired, nothing was proved,+ /// and nothing needed to be: a lookup, not an entailment claim. Listed+ /// separately from `Checked` so the checked count cannot rise without the+ /// checker running: 35,000 assertions and 3 inferences reporting "35,003+ /// checked conclusions" on a machine with no Lean is the laundering shape.+ AssertedInSource,+ /// A derivation step for it appears in a certificate `oo-cert` ACCEPTED.+ /// `OOCert.certificate_sound` applies. The only word that may be spoken+ /// when a machine-checked theorem stands behind the row.+ Checked,+ /// The engine says it derived this and no checker has looked: the checker+ /// was not built, was not run, or REJECTED the certificate.+ EngineOpinion,+}++impl Warrant {+ pub fn name(self) -> &'static str {+ match self {+ Warrant::AssertedInSource => "asserted_in_source",+ Warrant::Checked => "checked",+ Warrant::EngineOpinion => "engine_opinion",+ }+ }+ /// The theorem, named only where one stands behind the word.+ pub fn theorem(self) -> Option<&'static str> {+ match self {+ Warrant::Checked => Some("OOCert.certificate_sound"),+ _ => None,+ }+ }+}++/// Whether a term's spelling can be trusted to name the same thing on both+/// sides. Blank nodes do not compare across graphs by name.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Comparability {+ /// Every term is an IRI or a literal. Two spellings name the same thing.+ Ground,+ /// A term is a Skolem IRI THIS RUN minted for a source blank node, and the+ /// projection was produced from the skolemised source, so the binding is+ /// this run's own and is exact.+ SkolemBound,+ /// A blank node with no binding across the two graphs. NOT COMPARED, and no+ /// verdict of any kind is computed from it.+ Unbound,+}++pub fn comparability_of(t: &NtTriple, skolem_map: &BTreeMap<String, String>) -> Comparability {+ if pe::is_blank(&t.0) || pe::is_blank(&t.1) || pe::is_blank(&t.2) {+ return Comparability::Unbound;+ }+ let skolem = |x: &String| x.starts_with(&format!("<{}", pe::SKOLEM_PREFIX));+ if !skolem_map.is_empty() && (skolem(&t.0) || skolem(&t.2)) {+ return Comparability::SkolemBound;+ }+ Comparability::Ground+}++// ───────────────────────────────────────────────────────────────────────────+// What checked the closure this diff is computed from+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct CertificateVerdict {+ /// `"checked"` | `"engine_opinion"` | `"rejected"`. Exactly one place in+ /// this file can produce `"checked"`, and it has just read a zero exit code+ /// off the Lean binary. No other path reaches it.+ pub verdict: &'static str,+ /// `Some("OOCert.certificate_sound")` on `"checked"`, `None` otherwise.+ pub theorem: Option<&'static str>,+ pub asserted: usize,+ pub derivations: usize,+ /// The checker's own output, verbatim, when it ran.+ pub checker_report: Option<String>,+ /// `None` means the checker was never run.+ pub checker_exit: Option<i32>,+ /// Why it was not run, or why it said no. Carries the install line. Loud,+ /// never silent.+ pub skipped: Option<String>,+ /// False when the reasoner stopped at `runtime::reasoner_max_iterations()`+ /// with the closure still growing, so the closure may be TRUNCATED. No+ /// monotonicity verdict may be computed from a truncated source closure.+ pub reached_fixpoint: bool,+ pub iterations: usize,+ pub iteration_cap: usize,+}++impl CertificateVerdict {+ fn from_status(+ status: &CheckerStatus,+ asserted: usize,+ derivations: usize,+ reached_fixpoint: bool,+ iterations: usize,+ ) -> Self {+ // The ONE place `"checked"` is produced. It requires an accepted run,+ // which required exit code 0.+ let (verdict, exit, skipped): (&'static str, Option<i32>, Option<String>) = match status {+ CheckerStatus::Accepted { .. } => ("checked", Some(0), None),+ CheckerStatus::Rejected { stdout } => (+ "rejected",+ Some(1),+ Some(format!(+ "the verified checker REJECTED this certificate, so nothing in this report is \+ checked: {}",+ stdout.trim()+ )),+ ),+ // Exit 2 is "a file could not be read or parsed" and is NOT a+ // rejection: `lean/Main.lean` reserves the two codes for exactly+ // that distinction, and mapping 2 to "rejected" would turn a+ // missing file into a soundness finding.+ CheckerStatus::Unreadable { stdout } => (+ "engine_opinion",+ Some(2),+ Some(format!("the checker could not read the certificate: {}", stdout.trim())),+ ),+ CheckerStatus::Absent { what, install } => (+ "engine_opinion",+ None,+ Some(format!("{what}. {install}")),+ ),+ // The closure diff always has a whole certificate to check, so+ // this arm is unreachable here. It is still mapped to the weakest+ // word rather than left to a wildcard, because a wildcard is how a+ // new status silently becomes "checked" one refactor later.+ CheckerStatus::NotNeeded { what } => ("engine_opinion", None, Some(what.clone())),+ };+ CertificateVerdict {+ verdict,+ theorem: if verdict == "checked" { Some("OOCert.certificate_sound") } else { None },+ asserted,+ derivations,+ checker_report: match status {+ CheckerStatus::Accepted { stdout, .. } => Some(stdout.clone()),+ _ => None,+ },+ checker_exit: exit,+ skipped,+ reached_fixpoint,+ iterations,+ iteration_cap: crate::runtime::reasoner_max_iterations(),+ }+ }++ fn warrant_for_derived(&self) -> Warrant {+ if self.verdict == "checked" { Warrant::Checked } else { Warrant::EngineOpinion }+ }+}++// ───────────────────────────────────────────────────────────────────────────+// Findings+// ───────────────────────────────────────────────────────────────────────────++/// A conclusion of the source that the projection does not reach.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct LostEntailment {+ pub triple: NtTriple,+ pub warrant: Warrant,+ pub warrant_word: &'static str,+ /// Named only when `warrant.theorem()` is `Some`.+ pub theorem: Option<&'static str>,+ /// The rule that first produced it in the source, when it was inferred.+ pub rule: Option<String>,+ /// The premises of that derivation the PROJECTION's closure does not hold.+ /// This is the actionable half: the retriever dropped these, and the+ /// conclusion went with them. Printed rather than summarised.+ pub blocking_premises: Vec<NtTriple>,+ /// True when every term of the triple occurs in the projection, so an+ /// answer grounded in the projection is a claim over those terms and could+ /// have rested on this conclusion. THE headline partition.+ pub in_projection_vocabulary: bool,+ pub comparability: Comparability,+}++/// The stop-the-line case: a conclusion of the projection that is not a+/// conclusion of the source.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct MonotonicityViolation {+ pub triple: NtTriple,+ pub projection_rule: Option<String>,+ /// The premises the projection's rule read, so the step can be replayed by+ /// hand against `asserted.tsv`.+ pub projection_premises: Vec<NtTriple>,+ pub severity: &'static str,+ pub means: &'static str,+}++/// The dual, and the safe direction. Every premise of the source's derivation+/// is present in the projection's closure, the projection reached a fixpoint,+/// and it still did not derive the conclusion. That is an INCOMPLETENESS bug in+/// the engine or a certificate-recording bug. Deriving less is the sound+/// direction (decision 0002 item 8), so this is WARN and never stop-the-line.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct ReachableButNotDerived {+ pub triple: NtTriple,+ pub rule: Option<String>,+ pub premises: Vec<NtTriple>,+ pub severity: &'static str,+ pub means: &'static str,+}++/// Triples no verdict was computed from, with the reason. Counted, never folded+/// into a denominator: if these were dropped from the count rather than+/// reported, `lost_in_projection_vocabulary == 0` would mean "nothing was lost"+/// on a graph where a quarter of the triples were never looked at.+#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct NotCompared {+ pub source_triples: usize,+ pub projection_triples: usize,+ pub distinct_source_blank_nodes: usize,+ pub distinct_projection_blank_nodes: usize,+ pub why: &'static str,+}++pub const NOT_COMPARED_WHY: &str =+ "a blank node has no name that survives a graph boundary, and deciding whether one graph is a \+ subgraph of another up to blank-node renaming is simple entailment, which is NP-complete in \+ general and polynomial only when the target is ground. This bucket is a consequence of that \+ complexity, not an unfinished feature. Skolemise the source before the retriever sees it and \+ it empties.";++pub const NOT_DERIVED_MEANS: &str =+ "every premise of the source's derivation IS in the projection's closure and the projection \+ reached a fixpoint, yet it did not draw the conclusion. That is an incompleteness bug in the \+ engine or a certificate-recording bug. Deriving less is the sound direction, so this is a \+ warning and never a stop-the-line.";++// ───────────────────────────────────────────────────────────────────────────+// The report+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct ClosureDiffReport {+ pub format: &'static str,+ /// One sentence the reader cannot miss, first after `format` in the JSON+ /// and the first line of any human rendering.+ pub headline: String,+ pub profile: String,++ /// What licenses `Warrant::Checked` on the rows below.+ pub source_certificate: CertificateVerdict,+ /// What licenses a monotonicity claim.+ pub projection_certificate: CertificateVerdict,++ pub subset: pe::SubsetReport,++ pub entailments_lost: Vec<LostEntailment>,+ /// Exact totals. `entailments_lost` is capped for rendering; these are not.+ pub lost_total: usize,+ pub lost_in_projection_vocabulary: usize,+ pub lost_by_warrant: BTreeMap<String, usize>,+ /// The gaming direction of the headline number, in the payload rather than+ /// only in the docs, because the docs are not what a dashboard renders.+ pub headline_gaming_direction: &'static str,++ /// Empty except when the engine is wrong.+ pub monotonicity_violations: Vec<MonotonicityViolation>,+ /// Non-null whenever the gate did NOT run, with the reason, so a green+ /// `monotonicity_violations: []` can never mean "we did not look".+ pub monotonicity_gate_skipped: Option<String>,++ pub incompleteness_warnings: Vec<ReachableButNotDerived>,++ pub not_compared: NotCompared,++ pub coverage_proxy: CoverageProxy,++ pub skolemised: usize,+ pub asserted_digest: String,+ /// Set when the run could not do what it says. Loud, never silent.+ pub skipped: Option<String>,+ pub seconds: f64,+ /// 0 clean, 1 something was lost, 2 stop-the-line.+ pub exit_code: i32,+}++pub const HEADLINE_GAMING_DIRECTION: &str =+ "lost_in_projection_vocabulary has its own gaming direction: shrinking the projection's \+ vocabulary shrinks it. It is the right headline because a lost conclusion whose terms the \+ projection never mentions cannot ground an answer the projection supports, and it is not a \+ score to tune on.";++// ───────────────────────────────────────────────────────────────────────────+// Options+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug)]+pub struct DiffOptions {+ /// `rdfs`, `owl-rl` or `owl-rl-ext`. `owl-dl` is REFUSED: the tableaux path+ /// emits no rule trace, so neither side could be checked and the whole+ /// verdict vocabulary would collapse to `engine_opinion` while still+ /// looking like a certified run.+ pub profile: String,+ /// Where both certificates and the report land. A run is reproducible by+ /// hand from what it leaves behind.+ pub out: PathBuf,+ /// Path to the checker. `None` looks at `$OO_CERT`, then the repository's+ /// `lean/.lake/build/bin/`, then `$PATH`.+ pub checker: Option<PathBuf>,+ /// Replace every source blank node with a Skolem IRI before the retriever+ /// ever sees the graph. Without this, every triple touching a blank node+ /// lands in `not_compared` and the monotonicity gate is suppressed for it.+ pub skolemise_source: bool,+ /// Rows rendered per list. Totals are always exact.+ pub max_rows: usize,+ /// Seeds for the demoted coverage proxy.+ pub seed_iris: Vec<String>,+}++impl Default for DiffOptions {+ fn default() -> Self {+ DiffOptions {+ profile: "owl-rl-ext".into(),+ out: PathBuf::from("closure-diff"),+ checker: None,+ skolemise_source: true,+ max_rows: 200,+ seed_iris: Vec::new(),+ }+ }+}++// ───────────────────────────────────────────────────────────────────────────+// The source side, computed once and reused+// ───────────────────────────────────────────────────────────────────────────++/// FNV-1a 64, written out here rather than taken from a library, over a+/// canonical re-serialisation of the asserted set.+///+/// Offset basis `0xcbf29ce484222325`, prime `0x100000001b3`, the same+/// specification `src/vecstore.rs` already writes down for its own fingerprint.+/// `String::hash` is an opaque extern with no specification a second+/// implementation could target, so it is not used.+///+/// It IDENTIFIES so two runs can be compared; it does not COMMIT, and anyone+/// who needs that should hash the file. That is decision 0003 item 5, in the+/// same words, for the same reason.+///+/// The first version of this function grouped the prime's digits wrong and+/// multiplied by `0x1000000001b3`, one zero too many. Nothing would have+/// looked broken: the digest is only compared against itself. The published+/// test vectors below are what caught it, which is why they are pinned rather+/// than left to a round trip that would agree with any constant at all.+pub fn fnv1a64(bytes: &[u8]) -> u64 {+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;+ for b in bytes {+ h ^= *b as u64;+ h = h.wrapping_mul(0x100_0000_01b3);+ }+ h+}++fn digest_of(asserted: &HashSet<Spelled>) -> u64 {+ let mut lines: Vec<String> =+ asserted.iter().map(|t| format!("{}\t{}\t{}", t.0, t.1, t.2)).collect();+ lines.sort();+ fnv1a64(lines.join("\n").as_bytes())+}++/// The source side of a diff: its closure, its certificate verdict, and the+/// skolem map that made it comparable.+pub struct SourceClosure {+ closure: HashSet<Spelled>,+ asserted: HashSet<Spelled>,+ /// For a derived triple, the rule and premises of its FIRST derivation.+ derivation_of: HashMap<Spelled, (String, Vec<Spelled>)>,+ /// Copied onto every report this cache serves. A cache built without a+ /// checker serves `engine_opinion` for ever; it cannot be upgraded in+ /// place, because the upgrade would be a claim nobody made about the file+ /// that was actually diffed. Private, with no setter.+ verdict: CertificateVerdict,+ skolem_map: BTreeMap<String, String>,+ asserted_digest: u64,+ store: Arc<GraphStore>,+}++impl SourceClosure {+ /// Reason the source to a fixpoint, write the certificate under+ /// `opts.out/source`, and run the checker over it.+ pub fn build(source: &Arc<GraphStore>, opts: &DiffOptions) -> anyhow::Result<SourceClosure> {+ refuse_owl_dl(&opts.profile)?;+ let (store, skolem_map) = if opts.skolemise_source {+ pe::skolemise(source)?+ } else {+ (source.clone(), BTreeMap::new())+ };+ let dir = opts.out.join("source");+ let run = reason_side(&store, &opts.profile, &dir)?;+ let cert = CertificateIndex::read(&dir)?;+ let status = pe::run_oo_cert(+ opts.checker.as_deref(),+ &cert.asserted_path(),+ &dir.join("derivations.tsv"),+ );+ Ok(Self::assemble(&cert, status, run, store, skolem_map))+ }++ /// Reload from a certificate directory a previous run wrote, RE-RUNNING the+ /// checker rather than trusting the file.+ pub fn load(dir: &Path, opts: &DiffOptions) -> anyhow::Result<SourceClosure> {+ let cert = CertificateIndex::read(dir)?;+ let status = pe::run_oo_cert(+ opts.checker.as_deref(),+ &cert.asserted_path(),+ &dir.join("derivations.tsv"),+ );+ // A reloaded cache carries no live store and no iteration record. The+ // fixpoint flag is unknown, and an unknown fixpoint disarms the gate+ // rather than arming it on an assumption.+ let run = SideRun { reached_fixpoint: false, iterations: 0 };+ let store = Arc::new(GraphStore::new());+ Ok(Self::assemble(&cert, status, run, store, BTreeMap::new()))+ }++ fn assemble(+ cert: &CertificateIndex,+ status: CheckerStatus,+ run: SideRun,+ store: Arc<GraphStore>,+ skolem_map: BTreeMap<String, String>,+ ) -> SourceClosure {+ let asserted = cert.asserted_set().clone();+ let closure = cert.closure();+ let mut derivation_of = HashMap::new();+ for i in 0..cert.derivation_count() {+ if let (Some(rule), Some(prem)) = (cert.rule_of(i), cert.premises_of(i)) {+ // The index records the FIRST derivation of each conclusion, so+ // inserting only when absent keeps that choice.+ let concl = cert+ .conclusion_of_line(i)+ .expect("a line has a conclusion")+ .clone();+ derivation_of+ .entry(concl)+ .or_insert_with(|| (rule.to_string(), prem.to_vec()));+ }+ }+ let verdict = CertificateVerdict::from_status(+ &status,+ cert.asserted_count(),+ cert.derivation_count(),+ run.reached_fixpoint,+ run.iterations,+ );+ let asserted_digest = digest_of(&asserted);+ SourceClosure { closure, asserted, derivation_of, verdict, skolem_map, asserted_digest, store }+ }++ pub fn verdict(&self) -> &CertificateVerdict {+ &self.verdict+ }+ pub fn asserted_digest(&self) -> u64 {+ self.asserted_digest+ }+ pub fn skolem_map(&self) -> &BTreeMap<String, String> {+ &self.skolem_map+ }+ /// The (possibly skolemised) store the diff is computed against. A+ /// retriever must be pointed at THIS store, not the original, or the slice+ /// will carry blank nodes the source no longer has.+ pub fn store(&self) -> &Arc<GraphStore> {+ &self.store+ }+ pub fn closure_size(&self) -> usize {+ self.closure.len()+ }++ /// Assemble a closure from parts.+ ///+ /// The hook the monotonicity gate's failure test needs: the engine cannot be+ /// made unsound on demand, so the test builds a source closure with a hole+ /// the projection's closure fills.+ #[doc(hidden)]+ pub fn from_parts(+ closure: HashSet<Spelled>,+ asserted: HashSet<Spelled>,+ derivation_of: HashMap<Spelled, (String, Vec<Spelled>)>,+ verdict: CertificateVerdict,+ ) -> SourceClosure {+ let asserted_digest = digest_of(&asserted);+ SourceClosure {+ closure,+ asserted,+ derivation_of,+ verdict,+ skolem_map: BTreeMap::new(),+ asserted_digest,+ store: Arc::new(GraphStore::new()),+ }+ }++ /// Diff one projection against this closure.+ pub fn diff(&self, projection_ttl: &str, opts: &DiffOptions) -> anyhow::Result<ClosureDiffReport> {+ refuse_owl_dl(&opts.profile)?;+ let started = std::time::Instant::now();+ let pstore = Arc::new(GraphStore::new());+ pstore.load_turtle(projection_ttl, None).map_err(|e| {+ let hint = if projection_ttl.contains("<_:") {+ ". The slice contains `<_:`, an angle-bracketed blank node label, which is not a \+ legal IRI: that is what onto_segment_retrieve emits for a blank-node object. \+ Skolemise the source before retrieving"+ } else {+ ""+ };+ anyhow::anyhow!("the projection is not readable as Turtle: {e}{hint}")+ })?;++ let pdir = opts.out.join("projection");+ let prun = reason_side(&pstore, &opts.profile, &pdir)?;+ let pcert = CertificateIndex::read(&pdir)?;+ let pstatus =+ pe::run_oo_cert(opts.checker.as_deref(), &pcert.asserted_path(), &pdir.join("derivations.tsv"));+ let pverdict = CertificateVerdict::from_status(+ &pstatus,+ pcert.asserted_count(),+ pcert.derivation_count(),+ prun.reached_fixpoint,+ prun.iterations,+ );+ let pclosure = pcert.closure();++ // ── Subsethood, the ANTECEDENT of the monotonicity argument ──────+ let proj_asserted = pcert.asserted_set();+ let bn_src = self.asserted.iter().filter(|t| bn(t)).count();+ let bn_prj = proj_asserted.iter().filter(|t| bn(t)).count();+ let ground_only = bn_src > 0 || bn_prj > 0;+ let mut extras: Vec<String> = Vec::new();+ let mut extra_count = 0usize;+ for t in proj_asserted {+ if ground_only && bn(t) {+ continue;+ }+ if !self.asserted.contains(t) {+ extra_count += 1;+ if extras.len() < opts.max_rows.min(25) {+ extras.push(format!("{} {} {}", t.0, t.1, t.2));+ }+ }+ }+ extras.sort();+ let subset = pe::SubsetReport {+ verified: extra_count == 0,+ decided_over: if ground_only { "ground triples only" } else { "all triples" },+ extra_triples: extras,+ extra_count,+ blank_node_bearing_source: bn_src,+ blank_node_bearing_projection: bn_prj,+ blank_nodes_unmatched: ground_only,+ };++ let not_compared = NotCompared {+ source_triples: bn_src,+ projection_triples: bn_prj,+ distinct_source_blank_nodes: distinct_blanks(&self.asserted),+ distinct_projection_blank_nodes: distinct_blanks(proj_asserted),+ why: NOT_COMPARED_WHY,+ };++ // ── The free differential, through the shared pure function ──────+ let both_fixpoint = self.verdict.reached_fixpoint && prun.reached_fixpoint;+ let guards = Guards {+ subset_verified: subset.verified,+ blank_nodes_unmatched: subset.blank_nodes_unmatched,+ both_reached_fixpoint: both_fixpoint,+ };+ let mono = pe::differential(&self.closure, &pclosure, guards);+ let gate_skipped = if mono.status == "disarmed" {+ Some(match mono.reason {+ "projection_is_not_a_subset" => format!(+ "the monotonicity gate did NOT run: the projection is not a subset of the \+ source ({} extra asserted triple(s)). A conclusion the projection reaches \+ and the source does not is then ordinary, and reporting it as an engine \+ soundness bug would be a spectacular false alarm. This is a RETRIEVAL \+ finding",+ subset.extra_count+ ),+ "blank_nodes_unmatched" => format!(+ "the monotonicity gate did NOT run: {} source and {} projection triples carry \+ a blank node with no binding across the two graphs. Set skolemise_source to \+ empty this bucket",+ bn_src, bn_prj+ ),+ _ => format!(+ "the monotonicity gate did NOT run: a closure that stopped at the \+ {}-iteration cap is a LOWER BOUND and cannot refute anything (source \+ fixpoint {}, projection fixpoint {})",+ crate::runtime::reasoner_max_iterations(),+ self.verdict.reached_fixpoint,+ prun.reached_fixpoint+ ),+ })+ } else {+ None+ };+ let mut violations: Vec<MonotonicityViolation> = Vec::new();+ if mono.status == "armed" {+ for t in pclosure.difference(&self.closure) {+ let i = pcert.conclusion_index(t);+ violations.push(MonotonicityViolation {+ triple: t.clone(),+ projection_rule: i.and_then(|i| pcert.rule_of(i)).map(|s| s.to_string()),+ projection_premises: i+ .and_then(|i| pcert.premises_of(i))+ .map(|p| p.to_vec())+ .unwrap_or_default(),+ severity: STOP_THE_LINE,+ means: pe::MONOTONICITY_MEANS,+ });+ }+ violations.sort_by(|a, b| a.triple.cmp(&b.triple));+ }++ // ── The difference, partitioned by projection vocabulary ─────────+ let pterms: HashSet<&str> = proj_asserted+ .iter()+ .flat_map(|t| [t.0.as_str(), t.1.as_str(), t.2.as_str()])+ .chain(+ pclosure+ .iter()+ .flat_map(|t| [t.0.as_str(), t.1.as_str(), t.2.as_str()]),+ )+ .collect();+ let mut lost: Vec<LostEntailment> = Vec::new();+ let mut lost_in_vocab = 0usize;+ let mut by_warrant: BTreeMap<String, usize> = BTreeMap::new();+ let mut incompleteness: Vec<ReachableButNotDerived> = Vec::new();+ let mut ordered: Vec<&Spelled> = self.closure.difference(&pclosure).collect();+ ordered.sort();+ for t in ordered {+ let derivation = self.derivation_of.get(t);+ let warrant = if self.asserted.contains(t) {+ Warrant::AssertedInSource+ } else {+ self.verdict.warrant_for_derived()+ };+ *by_warrant.entry(warrant.name().to_string()).or_default() += 1;+ let in_vocab = [&t.0, &t.1, &t.2].iter().all(|x| pterms.contains(x.as_str()));+ if in_vocab {+ lost_in_vocab += 1;+ }+ let blocking: Vec<Spelled> = derivation+ .map(|(_, prem)| prem.iter().filter(|p| !pclosure.contains(*p)).cloned().collect())+ .unwrap_or_default();+ // The dual detector, free in the same pass.+ if let Some((rule, prem)) = derivation+ && blocking.is_empty()+ && prun.reached_fixpoint+ && incompleteness.len() < opts.max_rows+ {+ incompleteness.push(ReachableButNotDerived {+ triple: t.clone(),+ rule: Some(rule.clone()),+ premises: prem.clone(),+ severity: "WARN",+ means: NOT_DERIVED_MEANS,+ });+ }+ if lost.len() < opts.max_rows {+ lost.push(LostEntailment {+ triple: t.clone(),+ warrant,+ warrant_word: warrant.name(),+ theorem: warrant.theorem(),+ rule: derivation.map(|(r, _)| r.clone()),+ blocking_premises: blocking,+ in_projection_vocabulary: in_vocab,+ comparability: comparability_of(t, &self.skolem_map),+ });+ }+ }+ let lost_total = self.closure.difference(&pclosure).count();++ let coverage_proxy = pe::coverage_proxy(&self.store, &opts.seed_iris, projection_ttl);+ let exit_code = if !violations.is_empty() {+ 2+ } else if lost_in_vocab > 0 {+ 1+ } else {+ 0+ };+ let headline = format!(+ "{lost_total} conclusion(s) of the source are not conclusions of the projection, \+ {lost_in_vocab} of them over terms the projection MENTIONS. Source certificate: {}{}. \+ Monotonicity gate: {}{}. {}",+ self.verdict.verdict,+ match self.verdict.theorem {+ Some(t) => format!(" ({t})"),+ None => String::new(),+ },+ mono.status,+ if mono.reason.is_empty() { String::new() } else { format!(" ({})", mono.reason) },+ pe::COVERAGE_LABEL,+ );++ Ok(ClosureDiffReport {+ format: "oo-closure-diff/1",+ headline,+ profile: opts.profile.clone(),+ source_certificate: self.verdict.clone(),+ projection_certificate: pverdict,+ subset,+ entailments_lost: lost,+ lost_total,+ lost_in_projection_vocabulary: lost_in_vocab,+ lost_by_warrant: by_warrant,+ headline_gaming_direction: HEADLINE_GAMING_DIRECTION,+ monotonicity_violations: violations,+ monotonicity_gate_skipped: gate_skipped,+ incompleteness_warnings: incompleteness,+ not_compared,+ coverage_proxy,+ skolemised: self.skolem_map.len(),+ asserted_digest: format!("{:016x}", self.asserted_digest),+ skipped: None,+ seconds: started.elapsed().as_secs_f64(),+ exit_code,+ })+ }+}++fn bn(t: &Spelled) -> bool {+ pe::is_blank(&t.0) || pe::is_blank(&t.1) || pe::is_blank(&t.2)+}++fn distinct_blanks(set: &HashSet<Spelled>) -> usize {+ let mut s: BTreeSet<&str> = BTreeSet::new();+ for t in set {+ for x in [&t.0, &t.1, &t.2] {+ if pe::is_blank(x) {+ s.insert(x.as_str());+ }+ }+ }+ s.len()+}++fn refuse_owl_dl(profile: &str) -> anyhow::Result<()> {+ if profile == "owl-dl" {+ anyhow::bail!(+ "owl-dl emits no rule trace, so neither certificate could be written and every row \+ would be engine_opinion over a run that still looked like a closure diff. Run rdfs, \+ owl-rl or owl-rl-ext"+ );+ }+ Ok(())+}++struct SideRun {+ reached_fixpoint: bool,+ iterations: usize,+}++fn reason_side(store: &Arc<GraphStore>, profile: &str, dir: &Path) -> anyhow::Result<SideRun> {+ std::fs::create_dir_all(dir)?;+ let out = crate::reason::Reasoner::run_full(+ store,+ profile,+ false,+ crate::reason::InferenceTarget::DefaultGraph,+ Some(dir),+ )?;+ let v: serde_json::Value = serde_json::from_str(&out)?;+ Ok(SideRun {+ reached_fixpoint: v["fixpoint_reached"].as_bool().unwrap_or(false),+ iterations: v["iterations"].as_u64().unwrap_or(0) as usize,+ })+}++/// One-shot: reason both graphs, check both certificates, subtract.+pub fn closure_diff(+ source: &Arc<GraphStore>,+ projection_ttl: &str,+ opts: &DiffOptions,+) -> anyhow::Result<ClosureDiffReport> {+ let src = SourceClosure::build(source, opts)?;+ src.diff(projection_ttl, opts)+}++/// `oo-cert`'s install line, re-exported so a caller does not have to reach+/// into the sibling module for it.+pub const OO_CERT_INSTALL_LINE: &str = LAKE_INSTALL;++/// The kind of certificate this module reads. Fixed: the closure diff is over+/// a built-in profile, so a supplied Horn table has no arm here.+pub const CERT_KIND: CertKind = CertKind::OoCert;++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn fnv1a64_matches_the_specified_constant() {+ // Pinned against the published FNV-1a 64 vectors, not against a round+ // trip through this function, which would agree with any constant.+ assert_eq!(fnv1a64(b""), 0xcbf2_9ce4_8422_2325);+ assert_eq!(fnv1a64(b"a"), 0xaf63_dc4c_8601_ec8c);+ assert_eq!(fnv1a64(b"foobar"), 0x8594_4171_f739_67e8);+ }++ #[test]+ fn a_checked_word_needs_exit_zero() {+ for (status, want) in [+ (+ CheckerStatus::Accepted { theorem: "OOCert.certificate_sound", stdout: "{}".into() },+ "checked",+ ),+ (CheckerStatus::Rejected { stdout: "no".into() }, "rejected"),+ (CheckerStatus::Unreadable { stdout: "boom".into() }, "engine_opinion"),+ (+ CheckerStatus::Absent { what: "not built".into(), install: LAKE_INSTALL },+ "engine_opinion",+ ),+ ] {+ let v = CertificateVerdict::from_status(&status, 1, 1, true, 1);+ assert_eq!(v.verdict, want, "{status:?}");+ assert_eq!(v.theorem.is_some(), want == "checked");+ if want != "checked" {+ assert!(v.skipped.is_some(), "a non-checked verdict must say why: {v:?}");+ }+ }+ }++ #[test]+ fn exit_two_is_not_a_rejection() {+ let v = CertificateVerdict::from_status(+ &CheckerStatus::Unreadable { stdout: "cannot read".into() },+ 0,+ 0,+ true,+ 1,+ );+ assert_ne!(v.verdict, "rejected", "an unreadable file is not a rejected certificate");+ assert_eq!(v.checker_exit, Some(2));+ }+}diff --git a/src/graph.rs b/src/graph.rsindex 87113387..07da2347 100644--- a/src/graph.rs+++ b/src/graph.rs@@ -1,3 +1,4 @@+use std::collections::BTreeSet;use std::io::Cursor;use std::path::Path;@@ -61,7 +62,7 @@ impl SparqlAuth {////// The store is held directly rather than behind a `Mutex`. Oxigraph's `Store`/// is already `Send + Sync` and synchronises internally, so the mutex added-/// nothing but serialisation: every SPARQL read across all 109 tools queued+/// nothing but serialisation: every SPARQL read across all the tools queued/// behind one lock even though the reads do not conflict. It also meant/// fourteen `lock().unwrap()` sites, each of which turned a panic anywhere in/// the process into a poisoned lock and a second panic in every later request.@@ -722,6 +723,161 @@ impl GraphStore {Ok(triples)}+ /// Copy one named graph of this store into a fresh store's DEFAULT graph,+ /// by model term.+ ///+ /// This is the only route by which a projection can be a subset of the+ /// source in the strong sense, blank nodes included. Serialising a slice to+ /// Turtle and re-parsing it mints fresh blank node labels, and every+ /// blank-node-bearing triple then looks like an addition rather than a+ /// copy, which turns a faithful slice into a monotonicity alarm.+ ///+ /// [`canonicalize_blank_nodes`](Self::canonicalize_blank_nodes) is NOT the+ /// alternative and reaching for it is the trap this method exists to close:+ /// RDFC-1.0 labels are a function of the WHOLE graph, so the same blank+ /// node canonicalises differently in a slice than in the source precisely+ /// because the slice has fewer triples around it.+ pub fn graph_store(&self, graph_iri: &str) -> anyhow::Result<GraphStore> {+ let name = NamedNode::new(graph_iri)+ .map_err(|e| anyhow::anyhow!("{graph_iri} is not an IRI: {e}"))?;+ let out = GraphStore::new();+ for quad in self+ .store+ .quads_for_pattern(None, None, None, Some(GraphNameRef::NamedNode(name.as_ref())))+ {+ let q = quad?;+ out.store.insert(&Quad::new(+ q.subject.clone(),+ q.predicate.clone(),+ q.object.clone(),+ GraphName::DefaultGraph,+ ))?;+ }+ Ok(out)+ }++ /// Triples of one named graph, in the same spelling [`all_triples`] yields.+ ///+ /// [`all_triples`]: Self::all_triples+ pub fn graph_triples(&self, graph_iri: &str) -> anyhow::Result<Vec<(String, String, String)>> {+ let name = NamedNode::new(graph_iri)+ .map_err(|e| anyhow::anyhow!("{graph_iri} is not an IRI: {e}"))?;+ let mut triples = Vec::new();+ for quad in self+ .store+ .quads_for_pattern(None, None, None, Some(GraphNameRef::NamedNode(name.as_ref())))+ {+ let q = quad?;+ triples.push((+ q.subject.to_string(),+ q.predicate.to_string(),+ q.object.to_string(),+ ));+ }+ Ok(triples)+ }++ /// The names of the named graphs this store holds, sorted.+ pub fn named_graph_iris(&self) -> anyhow::Result<Vec<String>> {+ let mut names: BTreeSet<String> = BTreeSet::new();+ for quad in self.store.iter() {+ let q = quad?;+ if let GraphName::NamedNode(n) = &q.graph_name {+ names.insert(n.as_str().to_string());+ }+ }+ Ok(names.into_iter().collect())+ }++ /// How many triples sit in [`crate::reason::INFERRED_GRAPH`].+ ///+ /// Non-zero means an earlier `reason` run materialised into this store, so+ /// "what this graph asserts" is no longer "what a person wrote". Any tool+ /// that reads the store as a set of assertions has to be able to say that+ /// rather than quietly treat the engine's own output as an axiom.+ pub fn materialised_inference_count(&self) -> anyhow::Result<usize> {+ Ok(self.graph_triples(crate::reason::INFERRED_GRAPH)?.len())+ }++ /// Every quad as `(subject, predicate, object, graph)` strings, the graph+ /// being `""` for the default graph.+ pub fn all_quads(&self) -> anyhow::Result<Vec<(String, String, String, String)>> {+ let mut out = Vec::new();+ for quad in self.store.iter() {+ let q = quad?;+ out.push((+ q.subject.to_string(),+ q.predicate.to_string(),+ q.object.to_string(),+ match &q.graph_name {+ GraphName::DefaultGraph => String::new(),+ GraphName::NamedNode(n) => n.to_string(),+ GraphName::BlankNode(b) => b.to_string(),+ },+ ))+ }+ Ok(out)+ }++ /// Round-trip triples through a STORE, in order, keeping duplicates.+ ///+ /// Parsing alone is not enough, and this is measured rather than assumed:+ /// oxigraph's parser preserves a literal's lexical form, and it is the+ /// STORE that normalises it. `"01"^^xsd:integer` comes back from+ /// [`parse_triples_ordered`](Self::parse_triples_ordered) exactly as+ /// written and out of [`all_triples`](Self::all_triples) as+ /// `"1"^^xsd:integer`. A caller that compares its own spelling of a term+ /// against what a certificate holds therefore has to push the term through+ /// a store first, or it matches nothing and the miss looks like data loss.+ ///+ /// Each triple gets its own named graph, because a store is a SET: two+ /// identical inputs would otherwise collapse to one and the caller's+ /// pairing between what it wrote and what came back would shift silently.+ ///+ /// A triple no RDF serialiser can write, such as one with a literal+ /// subject, comes back as `None` in its own position rather than shifting+ /// the others.+ pub fn canonicalise_triples(+ triples: &[(String, String, String)],+ ) -> anyhow::Result<Vec<Option<(String, String, String)>>> {+ let store = GraphStore::new();+ let batch: String = triples+ .iter()+ .enumerate()+ .map(|(i, (s, p, o))| format!("{s} {p} {o} <urn:oo:canon:{i}> .\n"))+ .collect();+ if store.load_nquads(&batch).is_err() {+ // One bad line poisons the batch, so fall back to per-line and let+ // only the bad line fail.+ let retry = GraphStore::new();+ for (i, (s, p, o)) in triples.iter().enumerate() {+ let _ = retry.load_nquads(&format!("{s} {p} {o} <urn:oo:canon:{i}> .\n"));+ }+ return Self::collect_canonical(&retry, triples.len());+ }+ Self::collect_canonical(&store, triples.len())+ }++ fn collect_canonical(+ store: &GraphStore,+ n: usize,+ ) -> anyhow::Result<Vec<Option<(String, String, String)>>> {+ let mut out = vec![None; n];+ for (s, p, o, g) in store.all_quads()? {+ let Some(idx) = g+ .strip_prefix("<urn:oo:canon:")+ .and_then(|x| x.strip_suffix('>'))+ .and_then(|x| x.parse::<usize>().ok())+ else {+ continue;+ };+ if idx < out.len() {+ out[idx] = Some((s, p, o));+ }+ }+ Ok(out)+ }+fn detect_format(path: &str) -> RdfFormat {if path.ends_with(".ttl") || path.ends_with(".turtle") {RdfFormat::Turtle@@ -793,6 +949,37 @@ impl GraphStore {ext_format}+ /// Parse RDF text and return the triples in DOCUMENT ORDER, in the same+ /// spelling [`all_triples`](Self::all_triples) yields, without inserting+ /// anything into a store.+ ///+ /// The store is a set, so loading a goal document and reading it back+ /// loses both the order and the duplicates, and a caller that needs to+ /// pair each parsed triple with the line the caller wrote cannot do it+ /// that way. This runs the SAME parser the store runs, which is the only+ /// thing that makes a caller's spelling of a term comparable with the+ /// interner's, and keeps the pairing.+ pub fn parse_triples_ordered(+ text: &str,+ format: &str,+ ) -> anyhow::Result<Vec<(String, String, String)>> {+ let rdf_format = Self::parse_format(format)?;+ let reader = Cursor::new(text.as_bytes());+ let quads: Vec<Quad> = RdfParser::from_format(rdf_format)+ .for_reader(reader)+ .collect::<Result<_, _>>()?;+ Ok(quads+ .into_iter()+ .map(|q| {+ (+ q.subject.to_string(),+ q.predicate.to_string(),+ q.object.to_string(),+ )+ })+ .collect())+ }+fn parse_format(name: &str) -> anyhow::Result<RdfFormat> {match name.to_lowercase().as_str() {"turtle" | "ttl" => Ok(RdfFormat::Turtle),diff --git a/src/inputs.rs b/src/inputs.rsindex 390a5540..07adff24 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -946,6 +946,60 @@ pub struct GraphProjectionLossyCheckInput {pub projected_ttl: String,}+/// Input for `graph_projection_entailment_check`. The goal-directed form: the+/// caller supplies the claims its answer rests on, because at query time it+/// knows what it is about to assert.+#[derive(Deserialize, JsonSchema)]+pub struct GraphProjectionEntailmentCheckInput {+ /// The slice as Turtle. Mutually exclusive with `projection_graph`.+ #[serde(default)]+ pub projected_ttl: Option<String>,+ /// A named graph of the loaded store holding the slice. Preferred: blank+ /// node identity survives, so subsethood is verified over every triple+ /// rather than approximated over the ground ones.+ #[serde(default)]+ pub projection_graph: Option<String>,+ /// Turtle in which every triple is a claim the answer rests on. Blank nodes+ /// and non-triple claims are refused BY NAME, never silently dropped.+ pub goals_ttl: String,+ /// One profile for both runs. Default `owl-rl`.+ #[serde(default)]+ pub profile: Option<String>,+ /// Seeds for the demoted coverage proxy. Never derived from `goals_ttl`.+ #[serde(default)]+ pub seed_iris: Vec<String>,+ /// Where the two certificates and the per-goal slices land. Defaults to a+ /// temporary directory.+ #[serde(default)]+ pub certificate_dir: Option<String>,+ /// Turn an absent Lean checker into an error instead of an honest unchecked+ /// verdict.+ #[serde(default)]+ pub require_checker: Option<bool>,+}++/// Input for `onto_closure_diff` — entailment preservation under projection,+/// with no goals supplied.+#[derive(Deserialize, JsonSchema)]+pub struct OntoClosureDiffInput {+ /// The projected slice, as Turtle.+ pub projected_ttl: String,+ /// Directory for both certificates and the report.+ pub out_dir: String,+ /// `rdfs`, `owl-rl` or `owl-rl-ext`. `owl-dl` is refused.+ #[serde(default)]+ pub profile: Option<String>,+ /// Default true. With it false, every triple touching a blank node is+ /// reported as NOT COMPARED rather than guessed at.+ #[serde(default)]+ pub skolemise_source: Option<bool>,+ #[serde(default)]+ pub max_rows: Option<usize>,+ /// Seeds for the demoted coverage proxy.+ #[serde(default)]+ pub seed_iris: Vec<String>,+}+// ─── Full BC+ semantics (#43 follow-on) ─────────────────────────────────────/// Input for `onto_action_apply_concurrent` — fire a tick of concurrentdiff --git a/src/lib.rs b/src/lib.rsindex 249d40f3..777567d5 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -30,7 +30,9 @@ pub mod pack;pub mod support;pub mod temporal;pub mod policy;+pub mod closure_diff;pub mod projection_check;+pub mod projection_entailment;pub mod shape_combinatorics;// (re-exports keep the alphabetical ordering of the surrounding modules manageable)#[cfg(feature = "embeddings")]diff --git a/src/main.rs b/src/main.rsindex d53049f2..c176806d 100644--- a/src/main.rs+++ b/src/main.rs@@ -478,6 +478,78 @@ enum Commands {#[arg(long, default_value_t = 0)]goals_skip_columns: usize,},+ /// Ask whether a retrieved slice still supports the claims an answer rests on+ ///+ /// Coverage is a proxy. This asks the property: for each goal, does the+ /// projection entail it exactly when the source does, with a machine-checked+ /// certificate for each one it preserves. Exits 1 if any goal was lost,+ /// ungrounded or refused, 2 on a stop-the-line disagreement.+ Preserve {+ /// The slice as Turtle. Blank nodes are relabelled on re-parse, so+ /// subsethood is then decided over ground triples only and the+ /// monotonicity differential is disarmed.+ #[arg(long, conflicts_with = "projection_graph")]+ projection: Option<String>,+ /// A named graph of the LOADED store holding the slice. Blank node+ /// identity survives, so `P ⊆ G` can hold by construction and the+ /// differential can be armed.+ #[arg(long)]+ projection_graph: Option<String>,+ /// Turtle in which every triple is a goal, or a TSV with+ /// --goals-skip-columns. `derivations.tsv` from `reason --certificate`+ /// is a valid input with --goals-skip-columns 1.+ #[arg(long)]+ goals: String,+ #[arg(long, default_value_t = 0)]+ goals_skip_columns: usize,+ /// One profile for BOTH runs. Two profiles compare two rule sets and+ /// the differential then fires on nothing at all.+ #[arg(long, default_value = "owl-rl")]+ profile: String,+ /// A SUPPLIED Horn table instead of a built-in profile. Its presence+ /// changes the verdict WORD for every preserved goal.+ #[arg(long)]+ rules: Option<String>,+ /// Where the two certificates and the per-goal slices land.+ #[arg(long)]+ out: String,+ /// Seeds for the demoted coverage proxy. Independent of --goals.+ #[arg(long)]+ seed: Vec<String>,+ #[arg(long)]+ checker: Option<String>,+ /// Turn an absent checker into a failure. The CI leg sets it.+ #[arg(long, default_value_t = false)]+ require_checker: bool,+ },+ /// Which CONCLUSIONS a projection preserves, with no goals supplied+ ///+ /// The offline form, for auditing a retrieval STRATEGY rather than one+ /// answer: reason both graphs to a fixpoint under the same table and report+ /// `closure(G) \ closure(P)`. Exits 1 when something in the projection's own+ /// vocabulary was lost, 2 on a monotonicity violation.+ ClosureDiff {+ /// The slice as Turtle.+ #[arg(long)]+ projection: String,+ /// Where both certificates and the report land.+ #[arg(long)]+ out: String,+ #[arg(long, default_value = "owl-rl-ext")]+ profile: String,+ /// Replace every source blank node with a Skolem IRI before diffing.+ /// Without it, every triple touching a blank node lands in+ /// `not_compared` and the monotonicity gate is suppressed for it.+ #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]+ skolemise_source: bool,+ #[arg(long)]+ checker: Option<String>,+ #[arg(long, default_value_t = 200)]+ max_rows: usize,+ /// Seeds for the demoted coverage proxy.+ #[arg(long)]+ seed: Vec<String>,+ },/// Full pipeline: ingest → SHACL → reasonExtend {data_path: String,@@ -699,6 +771,84 @@ impl Commands {}cmd("fol", a)}+ Commands::Preserve {+ projection,+ projection_graph,+ goals,+ goals_skip_columns,+ profile,+ rules,+ out,+ seed,+ checker,+ require_checker,+ } => {+ let mut a = vec![+ "--goals".into(),+ absolutize(goals),+ "--goals-skip-columns".into(),+ goals_skip_columns.to_string(),+ "--profile".into(),+ profile.clone(),+ "--out".into(),+ absolutize(out),+ ];+ if let Some(p) = projection {+ a.push("--projection".into());+ a.push(absolutize(p));+ }+ if let Some(g) = projection_graph {+ a.push("--projection-graph".into());+ a.push(g.clone());+ }+ if let Some(r) = rules {+ a.push("--rules".into());+ a.push(absolutize(r));+ }+ for sd in seed {+ a.push("--seed".into());+ a.push(sd.clone());+ }+ if let Some(c) = checker {+ a.push("--checker".into());+ a.push(absolutize(c));+ }+ if *require_checker {+ a.push("--require-checker".into());+ }+ cmd("preserve", a)+ }+ Commands::ClosureDiff {+ projection,+ out,+ profile,+ skolemise_source,+ checker,+ max_rows,+ seed,+ } => {+ let mut a = vec![+ "--projection".into(),+ absolutize(projection),+ "--out".into(),+ absolutize(out),+ "--profile".into(),+ profile.clone(),+ "--skolemise-source".into(),+ skolemise_source.to_string(),+ "--max-rows".into(),+ max_rows.to_string(),+ ];+ for sd in seed {+ a.push("--seed".into());+ a.push(sd.clone());+ }+ if let Some(c) = checker {+ a.push("--checker".into());+ a.push(absolutize(c));+ }+ cmd("closure-diff", a)+ }Commands::Shacl { shapes } => cmd("shacl", vec![absolutize(shapes)]),Commands::Status => cmd("status", vec![]),Commands::Pull { url, sparql, query } => {@@ -952,6 +1102,27 @@ fn output_result_checked(result: &str, pretty: bool) {}}+/// Print a report and exit with the code IT names.+///+/// `output_result_checked` maps "there is an `error` field" to exit 1, which is+/// the right rule for a command whose only two outcomes are worked and did not.+/// A preservation report has three: clean, something was lost, and a+/// stop-the-line disagreement that means a defect in the engine or in this+/// code. Folding the third into the second would make the one outcome nobody+/// may ship look like an ordinary finding.+fn output_result_with_exit(result: &str, pretty: bool) {+ let parsed = serde_json::from_str::<serde_json::Value>(result).ok();+ let code = match &parsed {+ Some(v) if v.get("error").is_some() => 1,+ Some(v) => v.get("exit_code").and_then(|c| c.as_i64()).unwrap_or(0) as i32,+ None => 1,+ };+ output_result(result, pretty);+ if code != 0 {+ std::process::exit(code);+ }+}+fn output_result(result: &str, pretty: bool) {if json_mode() || pretty {if pretty {@@ -2430,6 +2601,31 @@ async fn async_main() -> anyhow::Result<()> {};output_result_checked(&result, cli.pretty);}+ Commands::Preserve { .. } | Commands::ClosureDiff { .. } => {+ // Both need a loaded source and are reached through `batch` in the+ // normal case, exactly as `reason --certificate` is: the store is+ // in-memory per process. Running them locally still works against+ // whatever the configured store holds, and says so when it is+ // empty rather than reporting a perfect run over nothing.+ let (db, graph) = setup(&cli.data_dir)?;+ let Some(batch) = cli.command.to_batch_command() else {+ anyhow::bail!("internal: this command is proxy-able and must serialise");+ };+ let name = batch["command"].as_str().unwrap_or_default().to_string();+ let args: Vec<String> = batch["args"]+ .as_array()+ .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())+ .unwrap_or_default();+ let runner = open_ontologies::batch::BatchRunner::new(db, graph, false);+ let payload =+ serde_json::json!([{ "command": name, "args": args }]).to_string();+ let (results, _) = runner.run_collect(&payload, false).await;+ let result = results+ .first()+ .map(|r| r["result"].clone())+ .unwrap_or_else(|| serde_json::json!({"error": "no result"}));+ output_result_with_exit(&result.to_string(), cli.pretty);+ }Commands::Extend {data_path,format: _format,@@ -2961,6 +3157,27 @@ mod proxy_serialization_tests {Commands::Drift { file_a: "a.ttl".into(), file_b: "b.ttl".into() },Commands::Lock { iris: vec!["http://example.org/A".into()], reason: None },Commands::Marketplace { action: "list".into(), id: None, domain: None },+ Commands::Preserve {+ projection: Some("p.ttl".into()),+ projection_graph: None,+ goals: "g.ttl".into(),+ goals_skip_columns: 0,+ profile: "owl-rl".into(),+ rules: None,+ out: "/tmp/preserve".into(),+ seed: vec![],+ checker: None,+ require_checker: false,+ },+ Commands::ClosureDiff {+ projection: "p.ttl".into(),+ out: "/tmp/cd".into(),+ profile: "owl-rl-ext".into(),+ skolemise_source: true,+ checker: None,+ max_rows: 200,+ seed: vec![],+ },]}diff --git a/src/projection_check.rs b/src/projection_check.rsindex 6ecdaeef..62151efd 100644--- a/src/projection_check.rs+++ b/src/projection_check.rs@@ -8,9 +8,34 @@//!//! Designed as a complementary primitive to `onto_segment_retrieve` (#34) — the//! retriever produces the slice; this auditor reports what it left behind.+//!+//! # `coverage_ratio` is a PROXY and it is demoted, not deleted+//!+//! It is neither necessary nor sufficient for the property that matters. A+//! slice at 0.99 can have dropped the one triple an answer rests on, and a+//! slice at 0.60 can preserve every conclusion a report asks about. It also+//! moves the wrong way: it rises as the projection grows, so a retriever tuned+//! on it learns to fetch MORE rather than to fetch the right thing.+//!+//! Measured on this repository's own `benchmark/reference/pizza-reference.owl`:+//! the whole ontology minus the single triple `NamedPizza rdfs:subClassOf+//! Pizza` scores `aggregate_coverage_ratio: 1.0` and `ok: true` over the 23+//! named-pizza seeds, while `Veneziana rdfs:subClassOf Food` — a conclusion the+//! source derives — is gone. The number cannot see the damage at all.+//!+//! The property is entailment preservation, and it is asked by+//! [`crate::projection_entailment`] (goal-directed, one answer) and+//! [`crate::closure_diff`] (goal-free, a whole retrieval strategy). This module+//! stays because a cheap signal is worth keeping; the label stays with it+//! because an unlabelled one is a trap.use crate::graph::GraphStore;use serde::{Deserialize, Serialize};++/// The sentence that travels with the number, in the payload rather than only+/// in the docs. Re-exported from [`crate::projection_entailment`] so there is+/// one spelling of it in the crate.+pub use crate::projection_entailment::COVERAGE_LABEL;use std::collections::BTreeSet;use std::sync::Arc;@@ -45,6 +70,22 @@ pub struct ProjectionLossReport {pub total_dropped_predicates: usize,/// Total dropped objects across all seeds (deduped).pub total_dropped_objects: usize,+ /// Always false. A FIELD rather than a doc comment, so a consumer reading+ /// the JSON sees it without reading prose, and a renderer that walks only+ /// the data still emits it.+ pub is_a_warrant: bool,+ /// [`COVERAGE_LABEL`], carried in the payload.+ pub warning: &'static str,+ /// Seeds whose projection side holds MORE triples than the source side.+ ///+ /// `coverage_ratio` clamps with `.min()`, so such a seed reads 1.0 with+ /// empty dropped lists, and `ok` used to be true on exactly the input that+ /// should stop a pipeline: a projection that is not a subset of the source,+ /// which is either a hallucinating retriever or a slice of a different+ /// graph. The clamp stays, because an unclamped "ratio" above 1.0 is not a+ /// ratio; the surplus is named instead and `ok` now requires it to be+ /// empty.+ pub seeds_with_surplus: Vec<String>,}/// Audit a projected Turtle slice against the loaded ontology's full@@ -62,6 +103,11 @@ pub fn check_projection_loss(let projected = GraphStore::new();let parse_ok = projected.load_turtle(projected_ttl, None).is_ok();if !parse_ok {+ // NOTE: `aggregate_coverage_ratio: 0.0` on a parse failure is this+ // module's oldest trap: "we could not read the file" renders as "0%+ // coverage". `projection_parses` is the field that separates them, and+ // `projection_entailment::coverage_proxy` drops the number entirely+ // rather than pass a 0.0 on to a reader.return Ok(ProjectionLossReport {projection_parses: false,aggregate_coverage_ratio: 0.0,@@ -69,6 +115,9 @@ pub fn check_projection_loss(ok: false,total_dropped_predicates: 0,total_dropped_objects: 0,+ is_a_warrant: false,+ warning: COVERAGE_LABEL,+ seeds_with_surplus: Vec::new(),});}@@ -127,7 +176,13 @@ pub fn check_projection_loss(let n = seed_iris.len().max(1) as f64;let aggregate = sum_ratio / n;- let ok = per_seed.iter().all(|r| (r.coverage_ratio - 1.0).abs() < 1e-9);+ let surplus: Vec<String> = per_seed+ .iter()+ .filter(|r| r.projected_triples > r.source_triples)+ .map(|r| r.seed_iri.clone())+ .collect();+ let ok = surplus.is_empty()+ && per_seed.iter().all(|r| (r.coverage_ratio - 1.0).abs() < 1e-9);Ok(ProjectionLossReport {projection_parses: true,@@ -136,6 +191,9 @@ pub fn check_projection_loss(ok,total_dropped_predicates: all_dropped_preds.len(),total_dropped_objects: all_dropped_objs.len(),+ is_a_warrant: false,+ warning: COVERAGE_LABEL,+ seeds_with_surplus: surplus,})}@@ -210,6 +268,43 @@ mod tests {assert!(cat_report.dropped_predicates.iter().any(|p| p.contains("species")));}+ /// The clamp used to report a clean bill of health on the one input that+ /// should stop a pipeline: a projection holding MORE about a seed than the+ /// source does, which is a hallucinating retriever or a slice of a+ /// different graph.+ #[test]+ fn a_projection_with_more_than_the_source_is_not_ok() {+ let source = r#"+ @prefix ex: <http://ex.org/> .+ ex:Cat ex:hasColour ex:Black .+ "#;+ let projection = r#"+ @prefix ex: <http://ex.org/> .+ ex:Cat ex:hasColour ex:Black ; ex:invented ex:Nonsense .+ "#;+ let g = loaded(source);+ let r = check_projection_loss(&g, &["http://ex.org/Cat".to_string()], projection).unwrap();+ assert_eq!(r.per_seed[0].coverage_ratio, 1.0, "the clamp still clamps");+ assert!(r.per_seed[0].dropped_predicates.is_empty(), "nothing was dropped");+ assert_eq!(r.seeds_with_surplus.len(), 1, "the surplus must be named: {r:?}");+ assert!(!r.ok, "a non-subset projection must not report ok: {r:?}");+ }++ #[test]+ fn the_label_travels_with_the_number() {+ let g = loaded(r#"@prefix ex: <http://ex.org/> . ex:X ex:p ex:Y ."#);+ for ttl in [r#"@prefix ex: <http://ex.org/> . ex:X ex:p ex:Y ."#, "not turtle <<<"] {+ let r = check_projection_loss(&g, &["http://ex.org/X".to_string()], ttl).unwrap();+ let json = serde_json::to_string(&r).unwrap();+ assert!(!r.is_a_warrant);+ assert!(json.contains("is neither necessary nor sufficient"), "{json}");+ assert!(+ !json.contains("\"ratio\"") || json.contains("PROXY"),+ "wherever the number appears the label must appear: {json}"+ );+ }+ }+#[test]fn invalid_projection_turtle_reports_parses_false() {let g = loaded(r#"@prefix ex: <http://ex.org/> . ex:X ex:p ex:Y ."#);diff --git a/src/projection_entailment.rs b/src/projection_entailment.rsnew file mode 100644index 00000000..7a7ac5de--- /dev/null+++ b/src/projection_entailment.rs@@ -0,0 +1,1768 @@+//! Does a retrieved slice still support the claims an answer rests on?+//!+//! [`crate::projection_check`] answers "how much of the source neighbourhood+//! survived", which is not the question. A slice at 99% coverage can have+//! dropped the one triple an answer depends on, and a slice at 60% coverage can+//! preserve every conclusion that matters. Worse, the number moves the wrong+//! way: it rises as the projection grows, so a retriever tuned on it learns to+//! fetch MORE rather than to fetch the right thing, and a retrieval-augmented+//! answer grounded in such a slice can be false while every displayed metric is+//! green.+//!+//! This module asks the property instead. Let `G` be the loaded store, `P` the+//! retrieved slice and `Q` a set of ground positive triples the answer rests+//! on. For each `q` in `Q`, does `P` entail `q` exactly when `G` does, decided+//! under ONE pinned rule profile, with a machine-checked certificate for each+//! `q` the projection preserves?+//!+//! # Four cells, and they are four different answers+//!+//! | `G` derives `q` | `P` derives `q` | what it is |+//! |---|---|---|+//! | yes | yes | preserved. The only cell that can carry a certificate. |+//! | yes | no | lost by the projection. The retrieval finding. |+//! | no | yes | the projection is not a subset of the source, or OWL RL monotonicity has been violated and the engine is unsound. Never a retrieval finding. |+//! | no | no | `ungrounded_in_source`. The claim has no support in the graph at all. The fix is in the generator, not the retriever. |+//!+//! The fourth cell is where most of the real value sits, and it is why the two+//! negatives are never collapsed into "loss": a generator that invented a claim+//! and a retriever that dropped a triple have opposite fixes, and a tool that+//! reports both as "not preserved" sends every investigation to the wrong team.+//! `ungrounded_in_source` does NOT mean the claim is false. RDF entailment is+//! open-world and this engine covers 29 of OWL 2 RL's 78 rules, so it means+//! "not derivable from `G` under this profile" and nothing stronger.+//!+//! # Why membership is decided over the certificate FILES+//!+//! [`Reasoner::run_full`] is run twice with `materialize = false` and a+//! `certificate_dir`, and membership of `q` is decided by reading+//! `asserted.tsv` and `derivations.tsv` back off disk rather than by consulting+//! an in-memory closure. That is deliberate. The Lean checker only ever sees+//! those two files. If membership were decided against a set the checker never+//! reads, the engine could report "derived" over a certificate that does not+//! contain the derivation, and the verdict would be unchecked while wearing the+//! checked word. Deciding over the artefact the checker reads makes that class+//! of bug impossible rather than tested against.+//!+//! # The free differential+//!+//! OWL RL is monotone and `P` is a subset of `G`, so every entailment of `P`+//! must be an entailment of `G`. A conclusion of `P` that is not a conclusion of+//! `G` is therefore a SOUNDNESS BUG IN THE ENGINE, not a retrieval finding, and+//! it is reported as `STOP_THE_LINE`. It is worth nothing unless it is DISARMED+//! whenever its premises do not hold, and there are three such conditions, each+//! of which occurs on real input: the projection is not a subset (computed,+//! never assumed from provenance); blank nodes could not be matched; or either+//! run stopped at the iteration cap instead of a fixpoint, which makes the+//! larger closure a LOWER BOUND and manufactures spurious `P`-only entailments.+//! Disarming is reported, never silent.+//!+//! See [decision 0007](../../docs/decisions/0007-a-slice-preserves-a-conclusion-or-it-does-not.md).++use crate::graph::GraphStore;+use crate::projection_check::{check_projection_loss, ProjectionLossReport};+use crate::reason::{InferenceTarget, Reasoner};+use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};+use std::path::{Path, PathBuf};+use std::sync::Arc;++/// A triple in the store's own N-Triples spelling: byte-identical to what+/// [`GraphStore::all_triples`] yields and to what `asserted.tsv` carries.+/// Every comparison in this module is over this type and never over user text.+pub type Spelled = (String, String, String);++/// RDF 1.1 section 3.5 reserves `.well-known/genid/` for skolem constants.+pub const SKOLEM_PREFIX: &str = "https://open-ontologies.org/.well-known/genid/";++/// How to get the checker, printed wherever it is missing.+pub const LAKE_INSTALL: &str =+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version, \+ then `cd lean && lake build` (oo-cert and oo-horn are in defaultTargets). Or set OO_CERT to \+ the binary.";++/// The sentence that travels with the coverage number, in the payload rather+/// than only in the docs.+pub const COVERAGE_LABEL: &str =+ "coverage_ratio is a PROXY and is neither necessary nor sufficient for entailment \+ preservation: a slice at 0.99 can have dropped the one triple an answer rests on, and a \+ slice at 0.60 can preserve every claim in this report. It also moves the wrong way, rising \+ as the projection grows, so a retriever tuned on it learns to fetch MORE rather than the \+ right thing. Read the per-goal verdicts; this number is a cheap signal and never a warrant.";++/// The severity word `src/projection_check.rs`'s neighbours use for a finding+/// that must stop a pipeline rather than be filed under "other".+pub const STOP_THE_LINE: &str = "STOP_THE_LINE";++// ───────────────────────────────────────────────────────────────────────────+// Blank nodes+// ───────────────────────────────────────────────────────────────────────────++/// True when the term is a blank node in N-Triples spelling (`_:label`).+pub fn is_blank(term: &str) -> bool {+ term.starts_with("_:")+}++fn has_blank(t: &Spelled) -> bool {+ is_blank(&t.0) || is_blank(&t.1) || is_blank(&t.2)+}++/// Replace every blank node in `g` with a Skolem IRI, returning the new store+/// beside the map that did it.+///+/// THIS IS NOT [`GraphStore::canonicalize_blank_nodes`], and reaching for that+/// instead is the trap this function exists to stop. RDFC-1.0 labels are a+/// function of the WHOLE graph: a blank node with seven triples in the source+/// and three in a slice canonicalises to two DIFFERENT labels. Canonicalising+/// both sides separately and diffing is exactly as wrong as not canonicalising+/// at all, and it looks principled, which is worse.+///+/// Skolemising the SOURCE before a retriever ever sees it is the only thing+/// that makes a re-parsed slice comparable, because the slice then carries real+/// IRIs and nothing has to be matched.+pub fn skolemise(g: &Arc<GraphStore>) -> anyhow::Result<(Arc<GraphStore>, BTreeMap<String, String>)> {+ let mut map: BTreeMap<String, String> = BTreeMap::new();+ let mut nt = String::new();+ for (s, p, o) in g.all_triples()? {+ let mut one = |term: &str| -> String {+ if let Some(label) = term.strip_prefix("_:") {+ let iri = format!("<{SKOLEM_PREFIX}{label}>");+ map.insert(iri.clone(), term.to_string());+ iri+ } else {+ term.to_string()+ }+ };+ let (s, p, o) = (one(&s), one(&p), one(&o));+ nt.push_str(&s);+ nt.push(' ');+ nt.push_str(&p);+ nt.push(' ');+ nt.push_str(&o);+ nt.push_str(" .\n");+ }+ let out = GraphStore::new();+ out.load_ntriples(&nt)?;+ Ok((Arc::new(out), map))+}++// ───────────────────────────────────────────────────────────────────────────+// Goals+// ───────────────────────────────────────────────────────────────────────────++/// One claim an answer rests on.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Goal {+ pub id: String,+ /// Exactly what the caller wrote, where the caller's bytes are recoverable.+ ///+ /// They are on the TSV and bindings paths. On the Turtle path the document+ /// is parsed as a whole and there is no per-triple source text to keep, so+ /// this holds the parser's rendering and equals [`Goal::triple`] by+ /// construction; the field is still printed, because the case where the two+ /// differ is the one that bites.+ pub as_written: String,+ /// What is actually asked: the spelling that came back out of the parser.+ pub triple: Spelled,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct RefusedGoal {+ pub as_written: String,+ pub reason: GoalRefusal,+ pub means: &'static str,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum GoalRefusal {+ /// A blank node in a goal is an existential, not a claim. This engine asks+ /// ground triples and cannot ask "there exists something such that".+ BlankNode,+ /// "no supplier is sanctioned", "exactly one registered address". Not a+ /// triple. Mapping absence-from-the-closure onto such a claim converts an+ /// open-world absence into a closed-world fact with a certificate stapled+ /// to it, which is the laundering this tool exists to attack, produced by+ /// the anti-laundering tool.+ NotAPositiveGroundTriple,+ /// A variable, a prefix that resolves to nothing, or text the parser+ /// refused.+ Unparseable,+}++impl GoalRefusal {+ pub fn means(self) -> &'static str {+ match self {+ GoalRefusal::BlankNode => {+ "a blank node in a goal is an existential rather than a claim. This layer asks \+ whether a GROUND triple is entailed and has no way to ask 'there exists \+ something such that'. Skolemise the source and ask about the Skolem constant, or \+ ask a SHACL shape instead"+ }+ GoalRefusal::NotAPositiveGroundTriple => {+ "this is a closed-world or negative claim, not a positive ground triple. Reading \+ 'absent from the closure' as 'the claim holds' would turn an open-world absence \+ into a fact with a certificate stapled to it. A closed-world question belongs in \+ SHACL: use onto_shacl"+ }+ GoalRefusal::Unparseable => {+ "the parser refused this. A goal has to survive the SAME parser the store uses, \+ because that is the only thing that makes the caller's spelling of a term \+ comparable with the interner's"+ }+ }+ }+}++/// The OWL vocabulary for writing down a NEGATIVE fact. A caller reaching for+/// it is asking a closed-world question, and the refusal says where that+/// belongs. Nothing here is a general-purpose ban on the OWL namespace: a goal+/// asking whether `A owl:equivalentClass B` is entailed is a perfectly ordinary+/// positive ground triple and is accepted.+const NEGATIVE_VOCABULARY: [&str; 5] = [+ "<http://www.w3.org/2002/07/owl#NegativePropertyAssertion>",+ "<http://www.w3.org/2002/07/owl#sourceIndividual>",+ "<http://www.w3.org/2002/07/owl#assertionProperty>",+ "<http://www.w3.org/2002/07/owl#targetIndividual>",+ "<http://www.w3.org/2002/07/owl#targetValue>",+];++/// Prefixes a caller uses when trying to write "not this" into a goal line.+const NEGATION_MARKERS: [&str; 4] = ["NOT ", "not ", "!", "\u{00ac}"];++fn classify(t: &Spelled, as_written: &str) -> Result<(), GoalRefusal> {+ if has_blank(t) {+ return Err(GoalRefusal::BlankNode);+ }+ if t.0.starts_with('"') {+ // A literal subject is not writable RDF and no rule can conclude one.+ return Err(GoalRefusal::NotAPositiveGroundTriple);+ }+ if NEGATIVE_VOCABULARY.contains(&t.1.as_str()) || NEGATIVE_VOCABULARY.contains(&t.2.as_str()) {+ return Err(GoalRefusal::NotAPositiveGroundTriple);+ }+ if NEGATION_MARKERS.iter().any(|m| as_written.starts_with(m)) {+ return Err(GoalRefusal::NotAPositiveGroundTriple);+ }+ Ok(())+}++fn refuse(as_written: &str, reason: GoalRefusal) -> RefusedGoal {+ RefusedGoal { as_written: as_written.to_string(), reason, means: reason.means() }+}++fn accept(idx: usize, as_written: String, t: Spelled) -> Goal {+ Goal { id: format!("g{idx}"), as_written, triple: t }+}++/// Parse a Turtle document in which every triple is a goal.+///+/// Prefix resolution and literal canonicalisation come from the same parser the+/// store uses, which is the ONLY way a goal's spelling can match the+/// interner's. A hand-typed goal that skipped the parser matches nothing and is+/// reported lost, which is a false loss with a green-looking pipeline around+/// it.+pub fn parse_goals_turtle(goals_ttl: &str) -> anyhow::Result<(Vec<Goal>, Vec<RefusedGoal>)> {+ let parsed = match GraphStore::parse_triples_ordered(goals_ttl, "turtle") {+ Ok(v) => v,+ Err(e) => {+ // All or nothing: this parser collects the whole document before+ // yielding anything, so one syntax error means no goals at all.+ // Reported as a refusal rather than an error so the caller sees it+ // in the same place every other rejected goal appears.+ return Ok((+ Vec::new(),+ vec![RefusedGoal {+ as_written: truncate(goals_ttl, 200),+ reason: GoalRefusal::Unparseable,+ means: Box::leak(+ format!("{}: {e}", GoalRefusal::Unparseable.means()).into_boxed_str(),+ ),+ }],+ ));+ }+ };+ // The parser's rendering is `as_written`; the STORE's is what is asked.+ // They differ: oxigraph's parser keeps a literal's lexical form and the+ // store normalises it, so a goal that skipped the store matches nothing.+ let raw: Vec<(String, Spelled)> = parsed+ .into_iter()+ .map(|t| (format!("{} {} {}", t.0, t.1, t.2), t))+ .collect();+ canonicalise_batch(raw, Vec::new())+}++/// The `fol --goals` shape, so `derivations.tsv` pipes in with+/// `skip_columns = 1` (its first column is the rule name).+pub fn parse_goals_tsv(text: &str, skip_columns: usize) -> anyhow::Result<(Vec<Goal>, Vec<RefusedGoal>)> {+ let mut raw: Vec<(String, Spelled)> = Vec::new();+ let mut refused: Vec<RefusedGoal> = Vec::new();+ for line in text.lines() {+ if line.trim().is_empty() {+ continue;+ }+ let f: Vec<&str> = line.split('\t').collect();+ if f.len() < skip_columns + 3 {+ refused.push(refuse(&truncate(line, 200), GoalRefusal::Unparseable));+ continue;+ }+ let (s, p, o) = (f[skip_columns], f[skip_columns + 1], f[skip_columns + 2]);+ let written = format!("{s} {p} {o}");+ if NEGATION_MARKERS.iter().any(|m| written.starts_with(m)) {+ refused.push(refuse(&written, GoalRefusal::NotAPositiveGroundTriple));+ continue;+ }+ raw.push((written, (s.to_string(), p.to_string(), o.to_string())));+ }+ canonicalise_batch(raw, refused)+}++/// Goals from the basic graph pattern of the query an answer was rendered+/// from, with the answer's bindings substituted.+///+/// The source that needs no trust in a generator at all: it is fully+/// mechanical, and available to any system that builds answers from SPARQL.+/// A variable with no binding is refused by name rather than dropped.+pub fn goals_from_bindings(+ bgp: &[(String, String, String)],+ bindings: &BTreeMap<String, String>,+) -> anyhow::Result<(Vec<Goal>, Vec<RefusedGoal>)> {+ let mut raw: Vec<(String, Spelled)> = Vec::new();+ let mut refused: Vec<RefusedGoal> = Vec::new();+ for (s, p, o) in bgp {+ let sub = |t: &String| -> Option<String> {+ match t.strip_prefix('?').or_else(|| t.strip_prefix('$')) {+ Some(v) => bindings.get(v).cloned(),+ None => Some(t.clone()),+ }+ };+ let written = format!("{s} {p} {o}");+ match (sub(s), sub(p), sub(o)) {+ (Some(s), Some(p), Some(o)) => raw.push((written, (s, p, o))),+ _ => refused.push(refuse(&written, GoalRefusal::Unparseable)),+ }+ }+ canonicalise_batch(raw, refused)+}++/// Round-trip every candidate through a STORE in ONE pass, in document order,+/// keeping the pairing between what was written and what came back.+///+/// The store, not just the parser: `"01"^^xsd:integer` survives+/// `RdfParser` unchanged and comes out of a store as `"1"^^xsd:integer`, so a+/// goal canonicalised only by the parser matches nothing in a certificate and+/// is reported LOST. That is a false loss with a green-looking pipeline round+/// it, and it is the reason `as_written` and `goal` are both printed.+fn canonicalise_batch(+ raw: Vec<(String, Spelled)>,+ mut refused: Vec<RefusedGoal>,+) -> anyhow::Result<(Vec<Goal>, Vec<RefusedGoal>)> {+ let inputs: Vec<Spelled> = raw.iter().map(|(_, t)| t.clone()).collect();+ let canonical = GraphStore::canonicalise_triples(&inputs)?;+ let mut goals = Vec::new();+ for (i, ((written, _), c)) in raw.iter().zip(canonical).enumerate() {+ let Some(t) = c else {+ // The store refused it. A literal subject is the realistic case and+ // it is not a positive ground triple; anything else the parser+ // rejected is unparseable.+ let why = if raw[i].1 .0.starts_with('"') {+ GoalRefusal::NotAPositiveGroundTriple+ } else {+ GoalRefusal::Unparseable+ };+ refused.push(refuse(written, why));+ continue;+ };+ match classify(&t, written) {+ Ok(()) => goals.push(accept(i, written.clone(), t)),+ Err(r) => refused.push(refuse(written, r)),+ }+ }+ Ok((goals, refused))+}++fn truncate(s: &str, n: usize) -> String {+ let t: String = s.chars().take(n).collect();+ if s.chars().count() > n { format!("{t}…") } else { t }+}++// ───────────────────────────────────────────────────────────────────────────+// The certificate, read back as the checker will read it+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Membership {+ /// In `asserted.tsv`. No derivation exists and none is needed.+ Asserted,+ /// Concluded by a line in the derivation file.+ Derived,+ /// In neither. Under this profile and this rule table only; the engine+ /// covers 29 of OWL 2 RL's 78 rules and this is not "false".+ NotDerivable,+}++/// Which certificate format a run wrote, and therefore which checker reads it.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum CertKind {+ /// `asserted.tsv` + `derivations.tsv`, checked by `oo-cert`.+ OoCert,+ /// `rules.tsv` + `asserted.tsv` + `horn.tsv`, checked by `oo-horn check`.+ OoHorn,+}++impl CertKind {+ pub fn derivations_file(self) -> &'static str {+ match self {+ CertKind::OoCert => "derivations.tsv",+ CertKind::OoHorn => "horn.tsv",+ }+ }+ pub fn binary(self) -> &'static str {+ match self {+ CertKind::OoCert => "oo-cert",+ CertKind::OoHorn => "oo-horn",+ }+ }+}++/// One run's certificate, indexed for lookup and slicing.+///+/// Raw lines are kept so a slice is byte-identical to what the emitter wrote.+pub struct CertificateIndex {+ dir: PathBuf,+ kind: CertKind,+ asserted: HashSet<Spelled>,+ lines: Vec<String>,+ conclusions: Vec<Spelled>,+ premises: Vec<Vec<Spelled>>,+ rules: Vec<String>,+ by_conclusion: HashMap<Spelled, usize>,+}++impl CertificateIndex {+ pub fn read(dir: &Path) -> anyhow::Result<Self> {+ let kind = if dir.join("horn.tsv").exists() { CertKind::OoHorn } else { CertKind::OoCert };+ let asserted_text = std::fs::read_to_string(dir.join("asserted.tsv"))+ .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", dir.join("asserted.tsv").display()))?;+ let mut asserted = HashSet::new();+ for line in asserted_text.lines() {+ if line.is_empty() {+ continue;+ }+ let f: Vec<&str> = line.split('\t').collect();+ if f.len() >= 3 {+ asserted.insert((f[0].to_string(), f[1].to_string(), f[2].to_string()));+ }+ }+ let dpath = dir.join(kind.derivations_file());+ let dtext = std::fs::read_to_string(&dpath)+ .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", dpath.display()))?;++ let mut lines = Vec::new();+ let mut conclusions = Vec::new();+ let mut premises = Vec::new();+ let mut rules = Vec::new();+ let mut by_conclusion: HashMap<Spelled, usize> = HashMap::new();+ for line in dtext.lines() {+ if line.is_empty() {+ continue;+ }+ let f: Vec<&str> = line.split('\t').collect();+ // `oo-cert`: rule, then 3(1+k) term fields.+ // `oo-horn`: rule index, binding count b, 2b binding fields, then+ // 3(1+k) term fields.+ let (rule, start) = match kind {+ CertKind::OoCert => (f.first().copied().unwrap_or("").to_string(), 1),+ CertKind::OoHorn => {+ let b: usize = f.get(1).and_then(|x| x.parse().ok()).unwrap_or(0);+ (f.first().copied().unwrap_or("").to_string(), 2 + 2 * b)+ }+ };+ if f.len() < start + 3 || !(f.len() - start).is_multiple_of(3) {+ anyhow::bail!(+ "{} line {} is not a {} step",+ dpath.display(),+ lines.len() + 1,+ kind.binary()+ );+ }+ let terms: Vec<Spelled> = f[start..]+ .chunks(3)+ .map(|c| (c[0].to_string(), c[1].to_string(), c[2].to_string()))+ .collect();+ let idx = lines.len();+ let conclusion = terms[0].clone();+ by_conclusion.entry(conclusion.clone()).or_insert(idx);+ conclusions.push(conclusion);+ premises.push(terms[1..].to_vec());+ rules.push(rule);+ lines.push(line.to_string());+ }+ Ok(CertificateIndex {+ dir: dir.to_path_buf(),+ kind,+ asserted,+ lines,+ conclusions,+ premises,+ rules,+ by_conclusion,+ })+ }++ pub fn kind(&self) -> CertKind {+ self.kind+ }+ pub fn dir(&self) -> &Path {+ &self.dir+ }+ pub fn asserted_path(&self) -> PathBuf {+ self.dir.join("asserted.tsv")+ }+ pub fn rules_path(&self) -> PathBuf {+ self.dir.join("rules.tsv")+ }+ pub fn asserted_count(&self) -> usize {+ self.asserted.len()+ }+ pub fn derivation_count(&self) -> usize {+ self.lines.len()+ }+ pub fn rule_of(&self, i: usize) -> Option<&str> {+ self.rules.get(i).map(|s| s.as_str())+ }+ pub fn premises_of(&self, i: usize) -> Option<&[Spelled]> {+ self.premises.get(i).map(|v| v.as_slice())+ }+ pub fn conclusion_index(&self, t: &Spelled) -> Option<usize> {+ self.by_conclusion.get(t).copied()+ }+ pub fn conclusion_of_line(&self, i: usize) -> Option<&Spelled> {+ self.conclusions.get(i)+ }++ /// `asserted ⊎ {conclusions}`. The `emit` closure in `src/reason.rs`+ /// records a derivation only when the triple is not already in the closure,+ /// so the two sets are disjoint and this IS the closure the run reached.+ pub fn closure(&self) -> HashSet<Spelled> {+ let mut c = self.asserted.clone();+ for t in &self.conclusions {+ c.insert(t.clone());+ }+ c+ }++ pub fn asserted_set(&self) -> &HashSet<Spelled> {+ &self.asserted+ }++ pub fn membership(&self, t: &Spelled) -> Membership {+ // Asserted FIRST. The certificate holds only INFERRED triples, so a+ // goal that is literally in the slice has no derivation line at all,+ // and an implementation that searches the derivations first finds+ // nothing and reports the goal lost. That is inverted, and the+ // happy-path test would never catch it because it naturally uses a+ // derived goal.+ if self.asserted.contains(t) {+ return Membership::Asserted;+ }+ if self.by_conclusion.contains_key(t) {+ return Membership::Derived;+ }+ Membership::NotDerivable+ }++ /// Line indices of a certificate that concludes `t`, closed under premises+ /// and in ASCENDING original order.+ ///+ /// The order is valid and it is provable from the emitter rather than hoped+ /// for: `run_full` computes a round's conclusions from `triple_set` as it+ /// stood at the START of that round and inserts them only afterwards, so+ /// every premise of a line was asserted or concluded strictly earlier in+ /// the file. `oo-cert` rejects a premise that is "neither asserted nor+ /// derived earlier", so this is load-bearing and is pinned by a test.+ pub fn slice_for(&self, t: &Spelled) -> Option<Vec<usize>> {+ let root = *self.by_conclusion.get(t)?;+ let mut want: BTreeSet<usize> = BTreeSet::new();+ let mut stack = vec![root];+ while let Some(i) = stack.pop() {+ if !want.insert(i) {+ continue;+ }+ for p in &self.premises[i] {+ if self.asserted.contains(p) {+ continue;+ }+ if let Some(&j) = self.by_conclusion.get(p)+ && j < i+ && !want.contains(&j)+ {+ stack.push(j);+ }+ }+ }+ Some(want.into_iter().collect())+ }++ /// Write a sub-certificate's derivation lines.+ ///+ /// `asserted.tsv` is NOT copied: the caller passes the run's single+ /// [`asserted_path`](Self::asserted_path) to the checker, so 200 goals over+ /// a 37k-derivation run do not write 200 copies of the graph.+ pub fn write_slice(&self, lines: &[usize], out_derivations: &Path) -> anyhow::Result<()> {+ if let Some(parent) = out_derivations.parent() {+ std::fs::create_dir_all(parent)?;+ }+ let mut body = String::new();+ for &i in lines {+ body.push_str(&self.lines[i]);+ body.push('\n');+ }+ std::fs::write(out_derivations, body)?;+ Ok(())+ }+}++// ───────────────────────────────────────────────────────────────────────────+// The checker+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum CheckerStatus {+ Accepted { theorem: &'static str, stdout: String },+ /// Exit 1. This module built the slice, so a rejection is a defect HERE or+ /// in the emitter. It is never a downgrade to an unchecked verdict.+ Rejected { stdout: String },+ /// Exit 2: a file could not be read or parsed. Not a verdict in either+ /// direction, exactly as `lean/Main.lean` reserves the two codes.+ Unreadable { stdout: String },+ /// Skip loudly, with the install line, and report the unchecked verdict+ /// honestly. Never pass silently.+ Absent { what: String, install: &'static str },+ /// The checker was found and no goal needed it, because no preserved goal+ /// was DERIVED and a goal that is literally in the slice has no derivation+ /// to check. Its own word, because calling that `unreadable` would put a+ /// file-format failure's name on a run where nothing went wrong, and+ /// calling it `accepted` would be worse.+ NotNeeded { what: String },+}++impl CheckerStatus {+ pub fn is_absent(&self) -> bool {+ matches!(self, CheckerStatus::Absent { .. })+ }+ pub fn word(&self) -> &'static str {+ match self {+ CheckerStatus::Accepted { .. } => "accepted",+ CheckerStatus::Rejected { .. } => "rejected",+ CheckerStatus::Unreadable { .. } => "unreadable",+ CheckerStatus::Absent { .. } => "absent",+ CheckerStatus::NotNeeded { .. } => "not_needed",+ }+ }+}++/// Find a Lean checker binary.+///+/// Mirrors the search every other certified path in this repository does, for+/// the reason those give: a run that quietly dropped to the engine's own+/// opinion because the checker was not built would look exactly like a run+/// where the checker had agreed.+pub fn find_checker(kind: CertKind, explicit: Option<&Path>) -> Result<PathBuf, String> {+ let name = kind.binary();+ if let Some(p) = explicit {+ return if p.exists() {+ Ok(p.to_path_buf())+ } else {+ Err(format!("{} does not exist", p.display()))+ };+ }+ let env_key = match kind {+ CertKind::OoCert => "OO_CERT",+ CertKind::OoHorn => "OO_HORN",+ };+ if let Ok(v) = std::env::var(env_key) {+ let p = PathBuf::from(&v);+ return if p.exists() { Ok(p) } else { Err(format!("${env_key} points at {v}, which does not exist")) };+ }+ let mut tried = Vec::new();+ for base in [+ PathBuf::from("."),+ PathBuf::from(env!("CARGO_MANIFEST_DIR")),+ ] {+ let p = base.join("lean").join(".lake").join("build").join("bin").join(name);+ if p.exists() {+ return Ok(p);+ }+ tried.push(p.display().to_string());+ }+ if let Ok(out) = std::process::Command::new(name).arg("--help").output() {+ // A bare invocation with no arguments prints usage and exits 2, which+ // is enough to know the binary is on PATH.+ let _ = out;+ return Ok(PathBuf::from(name));+ }+ Err(format!("{name} not found (looked at ${env_key}, {}, and $PATH)", tried.join(", ")))+}++/// Run `oo-cert ASSERTED DERIVATIONS` and turn its exit code into a verdict.+pub fn run_oo_cert(checker: Option<&Path>, asserted: &Path, derivations: &Path) -> CheckerStatus {+ run_checker(CertKind::OoCert, checker, asserted, derivations, None)+}++/// The ONE place a checked verdict is produced, and it has just read an exit+/// code off a Lean binary.+pub fn run_checker(+ kind: CertKind,+ checker: Option<&Path>,+ asserted: &Path,+ derivations: &Path,+ rules: Option<&Path>,+) -> CheckerStatus {+ let bin = match find_checker(kind, checker) {+ Ok(b) => b,+ Err(why) => {+ return CheckerStatus::Absent { what: why, install: LAKE_INSTALL };+ }+ };+ let mut cmd = std::process::Command::new(&bin);+ match kind {+ CertKind::OoCert => {+ cmd.arg(asserted).arg(derivations);+ }+ CertKind::OoHorn => {+ let Some(r) = rules else {+ return CheckerStatus::Absent {+ what: "oo-horn needs the rules.tsv the run evaluated, and none was written"+ .to_string(),+ install: LAKE_INSTALL,+ };+ };+ cmd.arg("check").arg(r).arg(asserted).arg(derivations);+ }+ }+ let out = match cmd.output() {+ Ok(o) => o,+ Err(e) => {+ return CheckerStatus::Absent {+ what: format!("{} could not be run: {e}", bin.display()),+ install: LAKE_INSTALL,+ };+ }+ };+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ match out.status.code() {+ Some(0) => CheckerStatus::Accepted {+ theorem: match kind {+ CertKind::OoCert => "OOCert.certificate_sound",+ CertKind::OoHorn => "OOCert.horn_certificate_sound",+ },+ stdout: text,+ },+ Some(1) => CheckerStatus::Rejected { stdout: text },+ Some(2) => CheckerStatus::Unreadable { stdout: text },+ other => CheckerStatus::Unreadable {+ stdout: format!("{} exited with {:?}\n{text}", bin.display(), other),+ },+ }+}++// ───────────────────────────────────────────────────────────────────────────+// Verdicts+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum GoalVerdict {+ /// `P` entails `q`, machine-checked over `P`'s own asserted graph.+ PreservedChecked,+ /// The same, but the run evaluated a SUPPLIED Horn table. True in every+ /// model of `P` that ALSO satisfies those rules. Never shortened.+ PreservedUnderSuppliedRulesChecked,+ /// `q` is literally in the slice. Verified by set membership over the+ /// canonical spelling. Not a theorem and it does not pretend to be.+ PreservedAsserted,+ /// The ENGINE derived it and no checker looked.+ PreservedUnchecked,+ /// Not derivable from `P` under this profile. Bounded by a rule table+ /// implementing 29 of OWL 2 RL's 78 rules, so it is not "P does not entail+ /// q".+ LostUnderProfileUnchecked,+ /// Neither certificate has it. The source does not derive it either, so+ /// the projection did not lose it.+ UngroundedInSource,+ /// In `P`'s certificate and not in `G`'s. A defect report rather than a+ /// verdict; see the monotonicity block.+ ProjectionOnly,+ /// The Lean checker REJECTED the sub-certificate this module assembled for+ /// the goal. A defect HERE or in the emitter, never a weaker result about+ /// the ontology, and never a downgrade to an unchecked verdict.+ CertificateRejected,+ /// Not a positive ground triple.+ Refused,+}++impl GoalVerdict {+ /// The theorem a verdict names, or `"none"`. A verdict with no theorem must+ /// never render a string containing "checked", and the suite asserts that+ /// over the SERIALISED report rather than over this function, because the+ /// enum is where the discipline is easy and the serialisation is where it+ /// leaks.+ pub fn warrant(self) -> &'static str {+ match self {+ GoalVerdict::PreservedChecked => "OOCert.certificate_sound",+ GoalVerdict::PreservedUnderSuppliedRulesChecked => "OOCert.horn_certificate_sound",+ _ => "none",+ }+ }+ pub fn is_checked(self) -> bool {+ self.warrant() != "none"+ }+ pub fn is_preserved(self) -> bool {+ matches!(+ self,+ GoalVerdict::PreservedChecked+ | GoalVerdict::PreservedUnderSuppliedRulesChecked+ | GoalVerdict::PreservedAsserted+ | GoalVerdict::PreservedUnchecked+ )+ }+ pub fn means(self) -> &'static str {+ match self {+ GoalVerdict::PreservedChecked =>+ "the projection entails this goal: true in every model of the projection under the \+ semantics in lean/OOCert/Semantics.lean. Machine-checked by oo-cert over the \+ projection's own asserted.tsv",+ GoalVerdict::PreservedUnderSuppliedRulesChecked =>+ "true in every model of the projection THAT ALSO SATISFIES the supplied rule \+ table. The rules are assumed and never checked; a rule reading 'every supplier \+ is compliant' produces certificates that check green for ever. Never shorten \+ this to the plain preserved word",+ GoalVerdict::PreservedAsserted =>+ "the goal is literally in the slice, by exact-string membership in the \+ projection's asserted.tsv. No rule fired, nothing was proved, and nothing needed \+ to be. This is a lookup, not a theorem",+ GoalVerdict::PreservedUnchecked =>+ "the ENGINE derived it from the projection and no checker has looked. This is the \+ engine's opinion about its own output, which is exactly what the certificate \+ layer exists to stop being trusted",+ GoalVerdict::LostUnderProfileUnchecked =>+ "the source derives it and the projection does not, under this profile. The \+ retrieval finding. The engine implements 29 of OWL 2 RL's 78 rules, so this is \+ bounded by the rule table and is NOT 'the projection does not entail it'",+ GoalVerdict::UngroundedInSource =>+ "NEITHER the source nor the projection derives it. The projection did not lose \+ it: the claim has no support in the knowledge graph under this profile, so the \+ fix is in the generator and not the retriever. Open-world: this is not 'false'",+ GoalVerdict::ProjectionOnly =>+ "the projection derives it and the source does not. Either the projection is not \+ a subset of the source, or OWL RL monotonicity has been violated and the engine \+ is unsound. Read the monotonicity block; this is never a retrieval finding",+ GoalVerdict::CertificateRejected => CERTIFICATE_REJECTED_MEANS,+ GoalVerdict::Refused =>+ "not a positive ground triple, so it was never asked. Counted in the headline so \+ a refusal cannot shrink the denominator unnoticed",+ }+ }+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct GoalCertificate {+ pub dir: String,+ pub format: &'static str,+ pub steps: usize,+ pub asserted: usize,+ /// The exact command a reader can run by hand.+ pub check_with: String,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct GoalReport {+ pub id: String,+ pub as_written: String,+ /// The canonical spelling actually asked. Printed even when it equals+ /// `as_written`, because the case where it differs is the one that bites.+ pub goal: String,+ pub source: Membership,+ pub projection: Membership,+ pub verdict: GoalVerdict,+ pub warrant: &'static str,+ pub means: &'static str,+ /// Present only for a preserved-and-checked goal.+ pub certificate: Option<GoalCertificate>,+ /// True when either run stopped at the iteration cap. Every NEGATIVE+ /// verdict from such a run is a lower bound, not a fact.+ pub bounded_by_iteration_cap: bool,+ /// The goal mentions no term any seed neighbourhood reaches. Usually a+ /// retriever misconfiguration rather than a loss, so it is named separately+ /// instead of being sent to the loss pile.+ pub goal_outside_seed_neighbourhood: bool,+}++// ───────────────────────────────────────────────────────────────────────────+// Subsethood and the differential+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct SubsetReport {+ /// Computed, never inferred from provenance. A retriever that normalises+ /// IRIs, re-prefixes, expands an abbreviation, inlines an imported+ /// vocabulary or adds a tidy `rdf:type owl:Class` declaration produces a+ /// non-subset that looks like a faithful slice.+ pub verified: bool,+ pub decided_over: &'static str,+ pub extra_triples: Vec<String>,+ pub extra_count: usize,+ pub blank_node_bearing_source: usize,+ pub blank_node_bearing_projection: usize,+ /// True when a blank node on either side has no binding across the two+ /// graphs, so subsethood over those triples is UNDECIDED rather than false.+ pub blank_nodes_unmatched: bool,+}++#[derive(Clone, Copy, Debug)]+pub struct Guards {+ pub subset_verified: bool,+ pub blank_nodes_unmatched: bool,+ pub both_reached_fixpoint: bool,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct MonotonicityReport {+ /// `"armed"` or `"disarmed"`. A green `violations: []` under `"disarmed"`+ /// means "we did not look", and the two must never render the same.+ pub status: &'static str,+ pub reason: &'static str,+ pub violations: Vec<String>,+ pub violation_count: usize,+ pub disagreement: Option<Disagreement>,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Disagreement {+ pub severity: &'static str,+ pub what: &'static str,+ pub detail: String,+ pub means: &'static str,+}++pub const MONOTONICITY_MEANS: &str =+ "OWL RL is monotone and this projection IS a subset of the source, so every conclusion of the \+ projection must be a conclusion of the source. This one is not. That is a SOUNDNESS BUG IN \+ THE ENGINE, not a finding about the retrieval, and not something to file under 'other'. Do \+ not ship a run that reports this.";++pub const CERTIFICATE_REJECTED_MEANS: &str =+ "the Lean checker rejected a sub-certificate THIS MODULE assembled from the engine's own \+ derivation file. That is a defect in the slice extractor or in the emitter's premise order, \+ not a weaker result about the ontology. It does not downgrade to preserved_unchecked, \+ because that would turn a defect in this code into a slightly weaker verdict nobody \+ investigates.";++/// PURE, so the gate can be shown failing without an unsound engine to hand.+///+/// The engine cannot be made unsound on demand, so the only honest way to show+/// that this gate can fire is to hand it a pair of closures where the+/// projection's exceeds the source's with both guards true.+pub fn differential(+ source_closure: &HashSet<Spelled>,+ projection_closure: &HashSet<Spelled>,+ guards: Guards,+) -> MonotonicityReport {+ let disarm = if !guards.subset_verified {+ Some("projection_is_not_a_subset")+ } else if guards.blank_nodes_unmatched {+ Some("blank_nodes_unmatched")+ } else if !guards.both_reached_fixpoint {+ Some("fixpoint_not_reached")+ } else {+ None+ };+ if let Some(reason) = disarm {+ return MonotonicityReport {+ status: "disarmed",+ reason,+ violations: Vec::new(),+ violation_count: 0,+ disagreement: None,+ };+ }+ let mut extra: Vec<String> = projection_closure+ .difference(source_closure)+ .map(|t| format!("{} {} {}", t.0, t.1, t.2))+ .collect();+ extra.sort();+ let count = extra.len();+ let shown: Vec<String> = extra.into_iter().take(50).collect();+ let disagreement = if count == 0 {+ None+ } else {+ Some(Disagreement {+ severity: STOP_THE_LINE,+ what: "monotonicity_violated",+ detail: format!(+ "{count} conclusion(s) of the projection are not conclusions of the source, over a \+ projection verified to be a subset, with both runs at a fixpoint"+ ),+ means: MONOTONICITY_MEANS,+ })+ };+ MonotonicityReport {+ status: "armed",+ reason: "",+ violations: shown,+ violation_count: count,+ disagreement,+ }+}++// ───────────────────────────────────────────────────────────────────────────+// The demoted proxy+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct CoverageProxy {+ /// `None` when no seeds were supplied or the slice did not parse, so+ /// "we did not compute it" can never render as "0% coverage".+ pub report: Option<ProjectionLossReport>,+ pub not_computed_because: Option<String>,+ /// Always false. A field rather than a doc comment, so a consumer reading+ /// JSON sees it without reading prose.+ pub is_a_warrant: bool,+ pub label: &'static str,+ /// Seeds whose neighbourhood hit the `LIMIT 1000` in+ /// `projection_check::neighbourhood_pairs`, so their ratio was computed on+ /// a truncated source. A truncated proxy reading 1.0 is the green-metric+ /// trap one level down.+ pub truncated_seeds: Vec<String>,+ /// The proxy is subject-only: an inbound-edge loss is invisible to it.+ /// Named here rather than fixed, because that is its own change.+ pub known_limits: &'static str,+}++const PROXY_LIMITS: &str =+ "the proxy counts a seed's OUTBOUND (predicate, object) pairs only, so a lost inbound edge is \+ invisible to it, and its SPARQL carries LIMIT 1000, so a seed with more than a thousand \+ outbound triples has its ratio computed against a truncated source. Both are pre-existing \+ and are named rather than fixed here.";++// ───────────────────────────────────────────────────────────────────────────+// Hygiene of the source side+// ───────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct SourceHygiene {+ /// Non-zero means an earlier `reason` run materialised into this store, so+ /// `asserted.tsv` on the source side lists the engine's own output as an+ /// axiom. Every `ungrounded_in_source` then becomes unreachable and every+ /// goal looks supported. Decision 0005 item 7 records this exact defect,+ /// found inside this repository, in a different tool.+ pub materialised_inferences_in_source: usize,+ pub source_side_unreliable: bool,+ pub means: &'static str,+}++// ───────────────────────────────────────────────────────────────────────────+// Options and the report+// ───────────────────────────────────────────────────────────────────────────++/// Where the slice came from. The arms differ in what can be PROVED about them,+/// not in convenience.+#[derive(Clone, Copy, Debug)]+pub enum Projection<'a> {+ /// Turtle text, re-parsed into a fresh store. Blank nodes are relabelled on+ /// the way in, so subsethood is decidable only over ground triples and the+ /// differential is disarmed whenever either side carries one.+ Turtle(&'a str),+ /// A named graph of the SAME store the source is read from. Blank node+ /// identity survives because nothing is re-parsed, so `P ⊆ G` is decided by+ /// set membership over every triple and the differential can be armed.+ NamedGraph(&'a str),+}++#[derive(Clone, Debug)]+pub struct Opts {+ /// ONE profile for BOTH runs. Two profiles compare two rule sets, and the+ /// differential then fires on nothing at all.+ pub profile: String,+ /// Optional supplied Horn table. Its presence changes the verdict WORD for+ /// every preserved goal.+ pub rules: Option<PathBuf>,+ /// Where the two run certificates and the per-goal slices land. Every+ /// intermediate file stays, so a run is reproducible by hand.+ pub work_dir: PathBuf,+ /// Explicit checker path. Defaults to `$OO_CERT`, then the repository's+ /// `lean/.lake/build/bin/`, then `$PATH`.+ pub checker: Option<PathBuf>,+ /// Turn an absent checker into an error instead of an honest unchecked+ /// verdict. The CI leg sets this.+ pub require_checker: bool,+ /// Seeds for the demoted coverage proxy. Independent of the goals, and+ /// never derived from them: a goal can mention IRIs no seed neighbourhood+ /// reaches, and coverage over the seeds says nothing about such a goal.+ pub seed_iris: Vec<String>,+}++impl Default for Opts {+ fn default() -> Self {+ Opts {+ profile: "owl-rl".into(),+ rules: None,+ work_dir: PathBuf::from("projection-entailment"),+ checker: None,+ require_checker: false,+ seed_iris: Vec::new(),+ }+ }+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct PreservationReport {+ pub format: &'static str,+ /// One sentence a reader cannot miss, first in the JSON after the format.+ pub headline: String,+ pub profile: String,+ pub rules: Option<String>,+ pub rules_sha256: Option<String>,+ pub goals_total: usize,+ pub preserved_checked: usize,+ pub preserved_asserted: usize,+ pub preserved_unchecked: usize,+ pub lost: usize,+ pub ungrounded_in_source: usize,+ pub projection_only: usize,+ /// Goals whose sub-certificate the checker rejected. Non-zero means a+ /// defect in this module or in the emitter, so it is counted apart from+ /// everything else and always comes with a stop-the-line block.+ pub certificate_rejected: usize,+ pub refused: usize,+ pub per_goal: Vec<GoalReport>,+ pub refused_goals: Vec<RefusedGoal>,+ pub subset: SubsetReport,+ pub monotonicity: MonotonicityReport,+ /// The stop-the-line block, if one fired. Either the monotonicity+ /// violation, or a sub-certificate the checker REJECTED, which is a defect+ /// in this module or in the emitter and not a weaker result about the+ /// ontology. Kept at the top level because a rejection is not a statement+ /// about monotonicity and must not be filed inside its block.+ pub disagreement: Option<Disagreement>,+ pub coverage_proxy: CoverageProxy,+ pub checker: CheckerStatus,+ pub source_hygiene: SourceHygiene,+ pub source_fixpoint_reached: bool,+ pub projection_fixpoint_reached: bool,+ pub source_iterations: usize,+ pub projection_iterations: usize,+ pub iteration_cap: usize,+ pub work_dir: String,+ /// Known limits of what a `preserved_checked` says, in the payload rather+ /// than only in the docs.+ pub limits: &'static str,+ /// True iff nothing was lost, nothing stopped the line, and no goal was+ /// refused. `ungrounded_in_source` does NOT clear it: a claim with no+ /// support in the graph is a finding, not a pass.+ pub ok: bool,+ /// 0 clean, 1 something was lost, ungrounded or refused, 2 stop-the-line.+ pub exit_code: i32,+}++const LIMITS: &str =+ "OOCert's entailment relation is not datatype-aware: \"1\"^^xsd:int and \"1\"^^xsd:integer are \+ two distinct terms, so a preserved_checked on one says nothing about the other. A lost_* \+ verdict is an engine opinion about a NEGATIVE and carries no certificate in this layer, \+ ever. The rule table is this engine's, not W3C's: 29 of OWL 2 RL's 78 rules.";++// ───────────────────────────────────────────────────────────────────────────+// The entry point+// ───────────────────────────────────────────────────────────────────────────++struct SideRun {+ fixpoint_reached: bool,+ iterations: usize,+ rules_sha256: Option<String>,+}++fn reason_side(store: &Arc<GraphStore>, opts: &Opts, dir: &Path) -> anyhow::Result<SideRun> {+ std::fs::create_dir_all(dir)?;+ let json: serde_json::Value = if let Some(rules) = &opts.rules {+ serde_json::from_str(&Reasoner::run_horn(store, rules, dir)?)?+ } else {+ // `materialize = false` ALWAYS. `run_full` computes the closure in+ // memory and writes the certificate regardless, so false costs nothing+ // and reasoning into the store would put this run's conclusions into+ // the next run's asserted.tsv.+ serde_json::from_str(&Reasoner::run_full(+ store,+ &opts.profile,+ false,+ InferenceTarget::DefaultGraph,+ Some(dir),+ )?)?+ };+ if let Some(e) = json.get("error").and_then(|v| v.as_str()) {+ anyhow::bail!("{e}");+ }+ Ok(SideRun {+ fixpoint_reached: json["fixpoint_reached"].as_bool().unwrap_or(false),+ iterations: json["iterations"].as_u64().unwrap_or(0) as usize,+ rules_sha256: json["certificate"]["rules_tsv_sha256"].as_str().map(|s| s.to_string()),+ })+}++/// Ask whether a retrieved slice still supports the claims an answer rests on.+///+/// Runs the reasoner twice with `materialize = false` into+/// `opts.work_dir/{source,projection}`, decides every goal over the certificate+/// FILES rather than an in-memory closure the checker never sees, extracts and+/// checks a sub-certificate per preserved goal, and runs the monotonicity+/// differential.+///+/// Errors rather than returning a green report when `goals` is empty: every+/// aggregate over zero goals is trivially perfect, which is decision 0006 item+/// 8's empty-problem shape, and "all my goals were refused" is the realistic+/// way to arrive at zero.+pub fn check_entailment_preservation(+ graph: &Arc<GraphStore>,+ projection: Projection<'_>,+ goals: &[Goal],+ refused: &[RefusedGoal],+ opts: &Opts,+) -> anyhow::Result<PreservationReport> {+ if goals.is_empty() {+ anyhow::bail!(+ "no goals to ask. {} goal(s) were refused as not positive ground triples or \+ unparseable, and every aggregate over zero goals is trivially perfect, so a report \+ here would be a green run that says nothing",+ refused.len()+ );+ }+ if opts.profile == "owl-dl" {+ anyhow::bail!(+ "owl-dl emits no rule trace, so neither side could be certified and every verdict \+ would collapse to the engine's opinion while still looking like a certified run. \+ Run rdfs, owl-rl or owl-rl-ext"+ );+ }++ // ── The projection store ────────────────────────────────────────────+ let (pstore, projected_ttl, projection_kind): (Arc<GraphStore>, String, &'static str) =+ match projection {+ Projection::Turtle(ttl) => {+ let s = GraphStore::new();+ s.load_turtle(ttl, None).map_err(|e| {+ let hint = if ttl.contains("<_:") {+ ". The slice contains `<_:`, an angle-bracketed blank node label, which \+ is not a legal IRI. That is what onto_segment_retrieve emits for a \+ blank-node object; skolemise the source before retrieving"+ } else {+ ""+ };+ anyhow::anyhow!(+ "the projection is not readable as Turtle, so there is no slice to ask \+ about: {e}{hint}"+ )+ })?;+ (Arc::new(s), ttl.to_string(), "turtle")+ }+ Projection::NamedGraph(name) => {+ let s = graph.graph_store(name)?;+ if s.triple_count() == 0 {+ anyhow::bail!(+ "named graph <{name}> holds no triples in the loaded store, so there is \+ no slice to ask about"+ );+ }+ let ttl = s.serialize("turtle").unwrap_or_default();+ (Arc::new(s), ttl, "named_graph")+ }+ };++ // ── Hygiene of the source side, before anything is computed from it ──+ let materialised = graph.materialised_inference_count().unwrap_or(0);+ let hygiene = SourceHygiene {+ materialised_inferences_in_source: materialised,+ source_side_unreliable: materialised > 0,+ means: if materialised > 0 {+ "an earlier reason run materialised into this store, so the source side's \+ asserted.tsv lists the engine's own output as an axiom. ungrounded_in_source becomes \+ unreachable and every goal looks supported. Reload the source from its files"+ } else {+ "no materialised inferences in the source store, so asserted.tsv is what was written"+ },+ };++ // ── Subsethood, computed rather than assumed from provenance ────────+ let src_triples: HashSet<Spelled> = graph.all_triples()?.into_iter().collect();+ let proj_triples: Vec<Spelled> = pstore.all_triples()?;+ let bn_src = src_triples.iter().filter(|t| has_blank(t)).count();+ let bn_proj = proj_triples.iter().filter(|t| has_blank(t)).count();+ let ground_only = projection_kind == "turtle" && (bn_src > 0 || bn_proj > 0);+ let mut extras: Vec<String> = Vec::new();+ let mut extra_count = 0usize;+ for t in &proj_triples {+ if ground_only && has_blank(t) {+ continue;+ }+ if !src_triples.contains(t) {+ extra_count += 1;+ if extras.len() < 25 {+ extras.push(format!("{} {} {}", t.0, t.1, t.2));+ }+ }+ }+ extras.sort();+ let subset = SubsetReport {+ verified: extra_count == 0,+ decided_over: if ground_only { "ground triples only" } else { "all triples" },+ extra_triples: extras,+ extra_count,+ blank_node_bearing_source: bn_src,+ blank_node_bearing_projection: bn_proj,+ blank_nodes_unmatched: ground_only,+ };++ // ── Two runs, one profile ───────────────────────────────────────────+ let work = &opts.work_dir;+ let src_dir = work.join("source");+ let prj_dir = work.join("projection");+ let src_run = reason_side(graph, opts, &src_dir)?;+ let prj_run = reason_side(&pstore, opts, &prj_dir)?;+ let src_cert = CertificateIndex::read(&src_dir)?;+ let prj_cert = CertificateIndex::read(&prj_dir)?;++ // ── The free differential ───────────────────────────────────────────+ let both_fixpoint = src_run.fixpoint_reached && prj_run.fixpoint_reached;+ let mono = differential(+ &src_cert.closure(),+ &prj_cert.closure(),+ Guards {+ subset_verified: subset.verified,+ blank_nodes_unmatched: subset.blank_nodes_unmatched,+ both_reached_fixpoint: both_fixpoint,+ },+ );++ // ── Seed neighbourhood, for goal_outside_seed_neighbourhood ─────────+ let seed_terms = seed_neighbourhood_terms(graph, &opts.seed_iris);++ // ── Per goal ────────────────────────────────────────────────────────+ let bounded = !both_fixpoint;+ let mut per_goal = Vec::with_capacity(goals.len());+ let mut checker_status: Option<CheckerStatus> = None;+ let mut stop_the_line: Option<Disagreement> = mono.disagreement.clone();+ for g in goals {+ let source = src_cert.membership(&g.triple);+ let projection = prj_cert.membership(&g.triple);+ let mut certificate = None;+ let verdict = match (source, projection) {+ (Membership::NotDerivable, Membership::NotDerivable) => GoalVerdict::UngroundedInSource,+ (Membership::NotDerivable, _) => GoalVerdict::ProjectionOnly,+ (_, Membership::NotDerivable) => GoalVerdict::LostUnderProfileUnchecked,+ // Asserted FIRST: see CertificateIndex::membership.+ (_, Membership::Asserted) => GoalVerdict::PreservedAsserted,+ (_, Membership::Derived) => {+ let lines = prj_cert.slice_for(&g.triple).unwrap_or_default();+ let out = work.join("goals").join(&g.id).join(prj_cert.kind().derivations_file());+ prj_cert.write_slice(&lines, &out)?;+ let rules_path = prj_cert.rules_path();+ let status = run_checker(+ prj_cert.kind(),+ opts.checker.as_deref(),+ &prj_cert.asserted_path(),+ &out,+ if prj_cert.kind() == CertKind::OoHorn { Some(&rules_path) } else { None },+ );+ let v = match &status {+ CheckerStatus::Accepted { .. } => {+ certificate = Some(GoalCertificate {+ dir: out.parent().unwrap_or(&out).display().to_string(),+ format: if prj_cert.kind() == CertKind::OoHorn { "oo-horn/1" } else { "oo-cert/1" },+ steps: lines.len(),+ asserted: prj_cert.asserted_count(),+ check_with: check_command(&prj_cert, &out),+ });+ if prj_cert.kind() == CertKind::OoHorn {+ GoalVerdict::PreservedUnderSuppliedRulesChecked+ } else {+ GoalVerdict::PreservedChecked+ }+ }+ CheckerStatus::Rejected { stdout } => {+ // NOT a downgrade. This module built the slice.+ stop_the_line.get_or_insert(Disagreement {+ severity: STOP_THE_LINE,+ what: "certificate_rejected",+ detail: format!(+ "the checker rejected the sub-certificate for goal {} ({}): {}",+ g.id,+ g.as_written,+ truncate(stdout.trim(), 400)+ ),+ means: CERTIFICATE_REJECTED_MEANS,+ });+ GoalVerdict::CertificateRejected+ }+ CheckerStatus::Unreadable { .. }+ | CheckerStatus::Absent { .. }+ | CheckerStatus::NotNeeded { .. } => GoalVerdict::PreservedUnchecked,+ };+ if checker_status.is_none() || matches!(status, CheckerStatus::Rejected { .. }) {+ checker_status = Some(status);+ }+ v+ }+ };+ let outside = !seed_terms.is_empty()+ && ![&g.triple.0, &g.triple.1, &g.triple.2].iter().any(|t| seed_terms.contains(t.as_str()));+ per_goal.push(GoalReport {+ id: g.id.clone(),+ as_written: g.as_written.clone(),+ goal: format!("{} {} {}", g.triple.0, g.triple.1, g.triple.2),+ source,+ projection,+ verdict,+ warrant: verdict.warrant(),+ means: verdict.means(),+ certificate,+ bounded_by_iteration_cap: bounded && !verdict.is_preserved(),+ goal_outside_seed_neighbourhood: outside,+ });+ }++ let checker = checker_status.unwrap_or_else(|| {+ // No goal needed a checker run. Say what would have happened rather+ // than imply one was consulted.+ match find_checker(prj_cert.kind(), opts.checker.as_deref()) {+ Ok(p) => CheckerStatus::NotNeeded {+ what: format!(+ "{} was found and no goal needed it: no preserved goal was DERIVED, so there \+ was no sub-certificate to check",+ p.display()+ ),+ },+ Err(why) => CheckerStatus::Absent { what: why, install: LAKE_INSTALL },+ }+ });+ if opts.require_checker && checker.is_absent() {+ anyhow::bail!(+ "require_checker was set and the checker is absent: {}. {LAKE_INSTALL}",+ match &checker {+ CheckerStatus::Absent { what, .. } => what.as_str(),+ _ => "",+ }+ );+ }++ // ── The demoted proxy ───────────────────────────────────────────────+ let coverage_proxy = coverage_proxy(graph, &opts.seed_iris, &projected_ttl);++ // ── Counts and the verdict on the run ───────────────────────────────+ let count = |f: fn(GoalVerdict) -> bool| per_goal.iter().filter(|g| f(g.verdict)).count();+ let preserved_checked = count(|v| {+ matches!(v, GoalVerdict::PreservedChecked | GoalVerdict::PreservedUnderSuppliedRulesChecked)+ });+ let preserved_asserted = count(|v| v == GoalVerdict::PreservedAsserted);+ let preserved_unchecked = count(|v| v == GoalVerdict::PreservedUnchecked);+ let lost = count(|v| v == GoalVerdict::LostUnderProfileUnchecked);+ let ungrounded = count(|v| v == GoalVerdict::UngroundedInSource);+ let projection_only = count(|v| v == GoalVerdict::ProjectionOnly);+ let certificate_rejected = count(|v| v == GoalVerdict::CertificateRejected);++ let exit_code = if stop_the_line.is_some() {+ 2+ } else if lost + ungrounded + projection_only + certificate_rejected + refused.len() > 0 {+ 1+ } else {+ 0+ };+ let ok = exit_code == 0;+++ let headline = format!(+ "{preserved_checked} of {} goal(s) preserved with a machine-checked certificate, \+ {preserved_asserted} preserved by assertion, {preserved_unchecked} preserved on the \+ engine's word alone, {lost} LOST by the projection, {ungrounded} UNGROUNDED IN THE \+ SOURCE, {} refused. Monotonicity gate: {}{}. {}",+ goals.len(),+ refused.len(),+ mono.status,+ if mono.reason.is_empty() { String::new() } else { format!(" ({})", mono.reason) },+ COVERAGE_LABEL,+ );++ Ok(PreservationReport {+ format: "oo-preserve/1",+ headline,+ profile: if opts.rules.is_some() { "supplied-horn-table".into() } else { opts.profile.clone() },+ rules: opts.rules.as_ref().map(|p| p.display().to_string()),+ rules_sha256: prj_run.rules_sha256.clone().or(src_run.rules_sha256.clone()),+ goals_total: goals.len(),+ preserved_checked,+ preserved_asserted,+ preserved_unchecked,+ lost,+ ungrounded_in_source: ungrounded,+ projection_only,+ certificate_rejected,+ refused: refused.len(),+ per_goal,+ refused_goals: refused.to_vec(),+ subset,+ monotonicity: mono,+ disagreement: stop_the_line,+ coverage_proxy,+ checker,+ source_hygiene: hygiene,+ source_fixpoint_reached: src_run.fixpoint_reached,+ projection_fixpoint_reached: prj_run.fixpoint_reached,+ source_iterations: src_run.iterations,+ projection_iterations: prj_run.iterations,+ iteration_cap: crate::runtime::reasoner_max_iterations(),+ work_dir: work.display().to_string(),+ limits: LIMITS,+ ok,+ exit_code,+ })+}++fn check_command(cert: &CertificateIndex, slice: &Path) -> String {+ match cert.kind() {+ CertKind::OoCert => format!(+ "cd lean && lake exe oo-cert {} {}",+ cert.asserted_path().display(),+ slice.display()+ ),+ CertKind::OoHorn => format!(+ "cd lean && lake exe oo-horn check {} {} {}",+ cert.rules_path().display(),+ cert.asserted_path().display(),+ slice.display()+ ),+ }+}++/// Build the demoted coverage block. Always carries [`COVERAGE_LABEL`], even+/// when the number itself could not be computed.+pub fn coverage_proxy(+ graph: &Arc<GraphStore>,+ seed_iris: &[String],+ projected_ttl: &str,+) -> CoverageProxy {+ if seed_iris.is_empty() {+ return CoverageProxy {+ report: None,+ not_computed_because: Some(+ "no seed IRIs were supplied. An aggregate over zero seeds is trivially 1.0 or \+ trivially 0.0 depending on how it is written, and neither says anything"+ .into(),+ ),+ is_a_warrant: false,+ label: COVERAGE_LABEL,+ truncated_seeds: Vec::new(),+ known_limits: PROXY_LIMITS,+ };+ }+ match check_projection_loss(graph, seed_iris, projected_ttl) {+ Ok(r) => {+ // A seed at exactly the LIMIT is the one whose ratio was computed+ // against a truncated source.+ let truncated: Vec<String> = r+ .per_seed+ .iter()+ .filter(|s| s.source_triples >= 1000)+ .map(|s| s.seed_iri.clone())+ .collect();+ let missing = if r.projection_parses {+ None+ } else {+ Some("the slice did not parse as Turtle, so no ratio was computed".to_string())+ };+ CoverageProxy {+ report: if r.projection_parses { Some(r) } else { None },+ not_computed_because: missing,+ is_a_warrant: false,+ label: COVERAGE_LABEL,+ truncated_seeds: truncated,+ known_limits: PROXY_LIMITS,+ }+ }+ Err(e) => CoverageProxy {+ report: None,+ not_computed_because: Some(format!("the proxy could not be computed: {e}")),+ is_a_warrant: false,+ label: COVERAGE_LABEL,+ truncated_seeds: Vec::new(),+ known_limits: PROXY_LIMITS,+ },+ }+}++/// Terms any seed's outbound neighbourhood mentions, plus the seeds. Empty when+/// no seeds were given, in which case no goal is ever reported outside it.+fn seed_neighbourhood_terms(graph: &Arc<GraphStore>, seeds: &[String]) -> HashSet<String> {+ let mut terms = HashSet::new();+ for s in seeds {+ terms.insert(format!("<{s}>"));+ let q = format!("SELECT DISTINCT ?p ?o WHERE {{ <{s}> ?p ?o }} LIMIT 1000");+ let Ok(js) = graph.sparql_select(&q) else { continue };+ let Ok(v) = serde_json::from_str::<serde_json::Value>(&js) else { continue };+ if let Some(rows) = v["results"].as_array() {+ for row in rows {+ for k in ["p", "o"] {+ if let Some(t) = row[k].as_str() {+ terms.insert(t.to_string());+ }+ }+ }+ }+ }+ terms+}++#[cfg(test)]+mod tests {+ use super::*;++ fn loaded(ttl: &str) -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(ttl, None).expect("load");+ g+ }++ fn scratch(name: &str) -> PathBuf {+ let d = std::env::temp_dir()+ .join(format!("oo-preserve-unit-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+ }++ const SRC: &str = r#"+ @prefix : <http://ex.org/> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ :A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .+ "#;++ #[test]+ fn a_turtle_goal_round_trips_through_the_store_parser() {+ let (goals, refused) = parse_goals_turtle(+ "@prefix : <http://ex.org/> .\n:a a :C .\n",+ )+ .unwrap();+ assert!(refused.is_empty(), "{refused:?}");+ assert_eq!(goals.len(), 1);+ assert_eq!(+ goals[0].triple,+ (+ "<http://ex.org/a>".into(),+ "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>".into(),+ "<http://ex.org/C>".into()+ )+ );+ }++ #[test]+ fn a_blank_node_goal_is_refused_by_name() {+ let (goals, refused) =+ parse_goals_turtle("@prefix : <http://ex.org/> .\n:a :p [ :q :r ] .\n").unwrap();+ assert!(goals.is_empty(), "{goals:?}");+ assert!(refused.iter().any(|r| r.reason == GoalRefusal::BlankNode), "{refused:?}");+ }++ #[test]+ fn a_negative_claim_is_refused_and_points_at_shacl() {+ let (goals, refused) = parse_goals_tsv(+ "NOT <http://ex.org/s>\t<http://ex.org/p>\t<http://ex.org/o>\n",+ 0,+ )+ .unwrap();+ assert!(goals.is_empty());+ assert_eq!(refused[0].reason, GoalRefusal::NotAPositiveGroundTriple);+ assert!(refused[0].means.contains("onto_shacl"), "{:?}", refused[0]);+ }++ #[test]+ fn an_empty_goal_set_is_an_error_not_a_green_report() {+ let g = loaded(SRC);+ let err = check_entailment_preservation(+ &g,+ Projection::Turtle(SRC),+ &[],+ &[],+ &Opts { work_dir: scratch("empty"), ..Default::default() },+ )+ .expect_err("zero goals must not produce a report");+ assert!(err.to_string().contains("no goals to ask"), "{err}");+ }++ #[test]+ fn the_differential_can_fire() {+ // The engine cannot be made unsound on demand, so the gate is shown+ // able to fail on the PURE function with a hand-built pair.+ let t = |s: &str| (s.to_string(), "<p>".to_string(), "<o>".to_string());+ let src: HashSet<Spelled> = [t("<a>")].into_iter().collect();+ let prj: HashSet<Spelled> = [t("<a>"), t("<ghost>")].into_iter().collect();+ let r = differential(+ &src,+ &prj,+ Guards { subset_verified: true, blank_nodes_unmatched: false, both_reached_fixpoint: true },+ );+ assert_eq!(r.status, "armed");+ assert_eq!(r.violation_count, 1);+ let d = r.disagreement.expect("a violation must produce a disagreement block");+ assert_eq!(d.severity, STOP_THE_LINE);+ assert_eq!(d.what, "monotonicity_violated");+ }++ #[test]+ fn every_guard_disarms_the_differential_with_its_own_reason() {+ let t = |s: &str| (s.to_string(), "<p>".to_string(), "<o>".to_string());+ let src: HashSet<Spelled> = HashSet::new();+ let prj: HashSet<Spelled> = [t("<ghost>")].into_iter().collect();+ for (g, why) in [+ (+ Guards { subset_verified: false, blank_nodes_unmatched: false, both_reached_fixpoint: true },+ "projection_is_not_a_subset",+ ),+ (+ Guards { subset_verified: true, blank_nodes_unmatched: true, both_reached_fixpoint: true },+ "blank_nodes_unmatched",+ ),+ (+ Guards { subset_verified: true, blank_nodes_unmatched: false, both_reached_fixpoint: false },+ "fixpoint_not_reached",+ ),+ ] {+ let r = differential(&src, &prj, g);+ assert_eq!(r.status, "disarmed", "{why}");+ assert_eq!(r.reason, why);+ assert!(r.disagreement.is_none(), "a disarmed gate must not accuse the engine");+ }+ }++ #[test]+ fn skolemising_survives_a_turtle_round_trip_and_canonicalising_would_not() {+ let g = loaded(+ r#"@prefix : <http://ex.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ :C rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :p ; owl:someValuesFrom :D ] .+ :E rdfs:subClassOf :C ."#,+ );+ let (sk, map) = skolemise(&g).unwrap();+ assert!(!map.is_empty(), "the source had blank nodes to skolemise");+ let ttl = sk.serialize("turtle").unwrap();+ let reparsed = GraphStore::new();+ reparsed.load_turtle(&ttl, None).unwrap();+ let a: BTreeSet<Spelled> = sk.all_triples().unwrap().into_iter().collect();+ let b: BTreeSet<Spelled> = reparsed.all_triples().unwrap().into_iter().collect();+ assert_eq!(a, b, "a skolemised graph must survive a Turtle round trip unchanged");+ }+}diff --git a/src/reason.rs b/src/reason.rsindex 42009d16..e41e3dc6 100644--- a/src/reason.rs+++ b/src/reason.rs@@ -242,6 +242,13 @@ impl Reasoner {let mut triple_set: HashSet<Fact> = facts.iter().copied().collect();let initial_size = triple_set.len();let mut iterations = 0;+ // Which of the two break conditions ended the loop. A run that stopped+ // at the cap has a closure that is a LOWER BOUND, and every consumer+ // that compares two closures has to be able to see that: a truncated+ // closure(G) missing a conclusion closure(P) reached looks exactly like+ // an unsoundness in the engine. `run_horn` already reports the same+ // field, so this is consistency rather than novelty.+ let mut fixpoint_reached = false;// Certificate bookkeeping. A conclusion is recorded the first time it// is derived and never again, so the certificate has exactly one line@@ -956,7 +963,11 @@ impl Reasoner {triple_set.insert(t);}- if triple_set.len() == before || iterations >= crate::runtime::reasoner_max_iterations() {+ if triple_set.len() == before {+ fixpoint_reached = true;+ break;+ }+ if iterations >= crate::runtime::reasoner_max_iterations() {break;}}@@ -1001,6 +1012,7 @@ impl Reasoner {"profile_used": profile_used,"inferred_count": inferred_count,"iterations": iterations,+ "fixpoint_reached": fixpoint_reached,"initial_triples": initial_size,"final_triples": triple_set.len(),"sample_inferences": samplediff --git a/src/runtime.rs b/src/runtime.rsindex 28e99ea6..02587a99 100644--- a/src/runtime.rs+++ b/src/runtime.rs@@ -161,6 +161,19 @@ pub fn set_classify_timeout_ms(ms: usize) {CLASSIFY_TIMEOUT_MS.store(ms, Ordering::Relaxed);}pub fn reasoner_max_iterations() -> usize { REASONER_MAX_ITER.load(Ordering::Relaxed) }++/// Set the forward-chaining iteration cap directly.+///+/// `set_classify_timeout_ms` above is the same shape and exists for the same+/// reason: a knob that only `init_from_config` can move cannot be exercised by+/// a test that has no config file. The cap matters here because a run that+/// stops at it has a closure that is a LOWER BOUND, and a consumer comparing+/// two closures has to be shown behaving correctly when one of them is+/// truncated. A test that forces the cap must restore it, since this is a+/// process-wide global.+pub fn set_reasoner_max_iterations(n: usize) {+ REASONER_MAX_ITER.store(n.max(1), Ordering::Relaxed);+}pub fn cache_hash_prefix_bytes() -> usize { CACHE_HASH_PREFIX.load(Ordering::Relaxed) }pub fn feedback_suppress_threshold() -> i64 { FB_SUPPRESS.load(Ordering::Relaxed) }pub fn feedback_downgrade_threshold() -> i64 { FB_DOWNGRADE.load(Ordering::Relaxed) }diff --git a/src/segment_retrieve.rs b/src/segment_retrieve.rsindex 3bfd6985..9bf50c02 100644--- a/src/segment_retrieve.rs+++ b/src/segment_retrieve.rs@@ -28,6 +28,47 @@ pub struct SegmentResult {pub frontier_iris: Vec<String>,}+/// Write one term of the slice.+///+/// Every term used to be wrapped in angle brackets unconditionally, which is+/// wrong for a blank node and for a literal. `rdfs:subClassOf` objects are+/// blank-node restrictions on essentially every OWL ontology in this+/// repository, so the slice contained `<_:b0>` — a relative reference that is+/// not a legal IRI — and since issue #93 `load_turtle` collects all or nothing,+/// so ONE restriction superclass made the ENTIRE slice fail to parse. The+/// auditor it pairs with then reported `projection_parses: false` with+/// `aggregate_coverage_ratio: 0.0` and no diagnosis. Measured on+/// `benchmark/ontoaxiom/data/ontoaxiom/ontologies/pizza.ttl` and+/// `benchmark/reference/pizza-reference.owl`: both produced an unparseable+/// slice.+///+/// Emitting a blank node bare makes the slice parse, and the labels are then+/// FRESH on re-parse, which is the trap `projection_entailment` handles by+/// disarming its monotonicity gate and saying so. The way to get a slice whose+/// blank nodes still match the source is to skolemise the source first+/// (`projection_entailment::skolemise`), which this repository's closure-diff+/// path does by default.+fn term(t: &str) -> String {+ if t.starts_with("_:") || t.starts_with('"') {+ t.to_string()+ } else {+ format!("<{t}>")+ }+}++/// Strip the angle brackets a SPARQL JSON row puts round an IRI, and ONLY+/// those.+///+/// The old `trim_matches(|c| c == '<' || c == '>')` ate the closing bracket of+/// a typed literal's datatype IRI as well, so `"1"^^<...#integer>` came back as+/// `"1"^^<...#integer` and could not be written back out.+fn unbracket(t: &str) -> String {+ match t.strip_prefix('<').and_then(|x| x.strip_suffix('>')) {+ Some(inner) => inner.to_string(),+ None => t.to_string(),+ }+}+/// TBox-relevant predicates that get traversed when retrieving a slice.const TBOX_PREDICATES: &[&str] = &["http://www.w3.org/2000/01/rdf-schema#subClassOf",@@ -73,7 +114,7 @@ pub fn retrieve_segment({for row in rows {if let Some(o) = row["o"].as_str() {- let o = o.trim_matches(|c| c == '<' || c == '>').to_string();+ let o = unbracket(o);triples.insert((iri.clone(), pred.to_string(), o.clone()));if !visited.contains(&o) {next_frontier.push(o);@@ -93,7 +134,7 @@ pub fn retrieve_segment({for row in rows {if let Some(o) = row["o"].as_str() {- let o = o.trim_matches(|c| c == '<' || c == '>').to_string();+ let o = unbracket(o);triples.insert((iri.clone(),"http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),@@ -114,7 +155,7 @@ pub fn retrieve_segment({for row in rows {if let Some(s) = row["s"].as_str() {- let s = s.trim_matches(|c| c == '<' || c == '>').to_string();+ let s = unbracket(s);triples.insert((s.clone(),"http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),@@ -133,7 +174,12 @@ pub fn retrieve_segment(let mut turtle = String::new();for (s, p, o) in &triples {- turtle.push_str(&format!("<{}> <{}> <{}> .\n", s, p, o));+ turtle.push_str(&term(s));+ turtle.push(' ');+ turtle.push_str(&term(p));+ turtle.push(' ');+ turtle.push_str(&term(o));+ turtle.push_str(" .\n");}Ok(SegmentResult {@@ -167,6 +213,32 @@ mod tests {g}+ /// The measured defect. Every term used to be wrapped in angle brackets,+ /// so a blank-node restriction superclass produced `<_:b0>` and the whole+ /// slice failed to parse — on the very ontologies this repository ships.+ #[test]+ fn a_slice_with_a_blank_node_superclass_still_parses() {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:Cheesy rdfs:subClassOf ex:Pizza ,+ [ a owl:Restriction ; owl:onProperty ex:hasTopping ; owl:someValuesFrom ex:Cheese ] .+ "#,+ None,+ )+ .unwrap();+ let r = retrieve_segment(&g, &["http://ex.org/Cheesy".to_string()], 2, false).unwrap();+ assert!(!r.turtle.contains("<_:"), "a blank node is not an IRI: {}", r.turtle);+ let back = GraphStore::new();+ back.load_turtle(&r.turtle, None).unwrap_or_else(|e| {+ panic!("the slice must parse, or the auditor it pairs with sees 0% coverage: {e}\n{}", r.turtle)+ });+ assert!(back.triple_count() > 0);+ }+#[test]fn retrieve_one_hop_pulls_immediate_parent() {let g = graph_with_hierarchy();diff --git a/src/server.rs b/src/server.rsindex 8a7d22f7..69b45b9b 100644--- a/src/server.rs+++ b/src/server.rs@@ -1570,7 +1570,7 @@ impl OpenOntologiesServer {}}- #[tool(name = "graph_projection_lossy_check", description = "Audit a projected Turtle slice against the loaded ontology's full neighbourhood of the seed IRIs. Reports dropped predicates, dropped object IRIs, per-seed coverage ratio, and aggregate coverage. Pair with onto_segment_retrieve when the slice is being passed to a downstream LLM — knowing what was left behind lets the caller decide whether the slice is sufficient. Per IJCAI 2025 'How to Mitigate Information Loss in KGs for GraphRAG'.")]+ #[tool(name = "graph_projection_lossy_check", description = "Audit a projected Turtle slice against the loaded ontology's full neighbourhood of the seed IRIs. Reports dropped predicates, dropped object IRIs, per-seed coverage ratio, and aggregate coverage. COVERAGE RATIO IS A PROXY AND IS NOT ASSURANCE: it is neither necessary nor sufficient for entailment preservation, a slice at 0.99 can have dropped the one triple an answer rests on, a slice at 0.60 can preserve every claim, and it RISES as the projection grows, so a retriever tuned on it learns to fetch more rather than the right thing. Measured on this repository's own pizza-reference.owl, the whole ontology minus one subClassOf triple scores 1.0 with ok:true while a conclusion the source derives is gone. For the property itself use graph_projection_entailment_check (goal-directed, machine-checked certificate per preserved claim) or onto_closure_diff (goal-free, whole retrieval strategy). Per IJCAI 2025 'How to Mitigate Information Loss in KGs for GraphRAG'.")]async fn graph_projection_lossy_check(&self, Parameters(input): Parameters<GraphProjectionLossyCheckInput>) -> String {match crate::projection_check::check_projection_loss(&self.graph, &input.source_iris, &input.projected_ttl) {Ok(report) => serde_json::to_string(&report)@@ -1579,6 +1579,64 @@ impl OpenOntologiesServer {}}+ #[tool(name = "graph_projection_entailment_check", description = "Does a retrieved slice still support the claims an answer rests on? Supply the claims as Turtle (goals_ttl); for each one this reports whether the projection entails it exactly when the source does, under one pinned rule profile, with a machine-checked Lean certificate (OOCert.certificate_sound) for each claim the projection preserves. Four outcomes, never collapsed: preserved (checked / asserted / unchecked), lost_under_profile_unchecked (the retrieval finding), ungrounded_in_source (NEITHER graph derives it, so the generator invented it and a better retriever will not help), and projection_only (the projection is not a subset, or the engine is unsound). Every run also verifies monotonicity: nothing may be entailed by the projection and not by the source, and a violation is STOP_THE_LINE rather than a retrieval result. Blank-node and non-triple claims are refused by name and counted. Coverage ratio is included, demoted, and labelled as a proxy that is not a warrant.")]+ async fn graph_projection_entailment_check(+ &self,+ Parameters(input): Parameters<GraphProjectionEntailmentCheckInput>,+ ) -> String {+ use crate::projection_entailment as pe;+ if input.projected_ttl.is_some() == input.projection_graph.is_some() {+ return Self::err_json(+ "pass exactly one of projected_ttl and projection_graph. A named graph of the \+ loaded store keeps blank node identity, so P ⊆ G can be verified over every \+ triple rather than over the ground ones only",+ );+ }+ let (goals, refused) = match pe::parse_goals_turtle(&input.goals_ttl) {+ Ok(v) => v,+ Err(e) => return Self::err_json(e),+ };+ let work = input.certificate_dir.map(std::path::PathBuf::from).unwrap_or_else(|| {+ std::env::temp_dir().join(format!("oo-preserve-{}", std::process::id()))+ });+ let opts = pe::Opts {+ profile: input.profile.unwrap_or_else(|| "owl-rl".to_string()),+ rules: None,+ work_dir: work,+ checker: None,+ require_checker: input.require_checker.unwrap_or(false),+ seed_iris: input.seed_iris,+ };+ let ttl = input.projected_ttl.unwrap_or_default();+ let projection = match &input.projection_graph {+ Some(g) => pe::Projection::NamedGraph(g),+ None => pe::Projection::Turtle(&ttl),+ };+ match pe::check_entailment_preservation(&self.graph, projection, &goals, &refused, &opts) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| Self::err_json(format!("serialization: {}", e))),+ Err(e) => Self::err_json(e),+ }+ }++ #[tool(name = "onto_closure_diff", description = "Which CONCLUSIONS a projection preserves, with no goals supplied. Reasons the source and the slice to a fixpoint under the same rule table and reports closure(source) minus closure(projection), partitioned by whether every term of the lost conclusion occurs in the projection: lost_in_projection_vocabulary is the headline, because a conclusion over terms the slice never mentions cannot ground an answer the slice supports. Each lost row names the rule and the blocking premises the retriever dropped. Three warrant words, never collapsed: checked (a Lean-accepted certificate, OOCert.certificate_sound), asserted_in_source (a lookup, nothing was proved), engine_opinion (no checker looked, or it said no). Also runs the monotonicity gate and reports when the gate did NOT run and why, so an empty violation list can never mean 'we did not look'. Skolemises the source by default so blank-node-bearing triples can be compared at all. The offline form; graph_projection_entailment_check is the per-answer one.")]+ async fn onto_closure_diff(&self, Parameters(input): Parameters<OntoClosureDiffInput>) -> String {+ use crate::closure_diff as cd;+ let opts = cd::DiffOptions {+ profile: input.profile.unwrap_or_else(|| "owl-rl-ext".to_string()),+ out: std::path::PathBuf::from(&input.out_dir),+ checker: None,+ skolemise_source: input.skolemise_source.unwrap_or(true),+ max_rows: input.max_rows.unwrap_or(200),+ seed_iris: input.seed_iris,+ };+ match cd::closure_diff(&self.graph, &input.projected_ttl, &opts) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| Self::err_json(format!("serialization: {}", e))),+ Err(e) => Self::err_json(e),+ }+ }+#[tool(name = "onto_certify_action", description = "CIVeX-style causal certificate for a proposed state-changing ontology action. Returns a verdict (EXECUTE / REJECT / EXPERIMENT / ABSTAIN) plus an auditable certificate documenting the assumptions, structural-dependency identification proof, utility point estimate + one-sided lower confidence bound, provenance hash, and risk bound. Use as a pre-flight gate for onto_apply / onto_save / onto_push / onto_ingest. Scaffold port of arXiv:2605.09168 — structural-dependency proxy in place of full do-calculus identifiability; documented honestly.")]async fn onto_certify_action(&self, Parameters(input): Parameters<OntoCertifyActionInput>) -> String {let frame = crate::civex::ActionFrame {@@ -2910,6 +2968,6 @@ impl OpenOntologiesServer {impl ServerHandler for OpenOntologiesServer {fn get_info(&self) -> ServerInfo {ServerInfo::new(ServerCapabilities::builder().enable_tools().enable_prompts().build())- .with_instructions("Open Ontologies: AI-native ontology engine, an RDF/OWL/SPARQL MCP server with 109 tools and 6 workflow prompts for ontology engineering, validation, comparison, alignment, data ingestion, and exploration. All 109 tools are advertised in a default build; 8 of them require an optional Cargo feature (embeddings, plugins, postgres or duckdb) and return an error without it.")+ .with_instructions("Open Ontologies: AI-native ontology engine, an RDF/OWL/SPARQL MCP server with 112 tools and 6 workflow prompts for ontology engineering, validation, comparison, alignment, data ingestion, and exploration. All 112 tools are advertised in a default build; 8 of them require an optional Cargo feature (embeddings, plugins, postgres or duckdb) and return an error without it.")}}diff --git a/tests/closure_diff_test.rs b/tests/closure_diff_test.rsnew file mode 100644index 00000000..5056ea09--- /dev/null+++ b/tests/closure_diff_test.rs@@ -0,0 +1,582 @@+//! The goal-free form: which CONCLUSIONS a projection preserves.+//!+//! `src/projection_entailment.rs` asks the question of a supplied goal set, for+//! auditing one answer. This asks it of everything at once, for auditing a+//! retrieval STRATEGY, because a strategy is not evaluated against one question.+//!+//! Every gate here is shown failing on deliberately broken input, and the+//! verdict discipline is enforced over the SERIALISED report rather than over+//! the enum, because the enum is where the discipline is easy and the+//! serialisation is where it leaks.++mod common;++use open_ontologies::closure_diff as cd;+use open_ontologies::closure_diff::{DiffOptions, Warrant};+use open_ontologies::graph::GraphStore;+use std::collections::{HashMap, HashSet};+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::{Arc, Mutex, MutexGuard, OnceLock};++/// See `tests/lean_projection_entailment_test.rs`: the iteration cap is a+/// process-wide atomic and one test here moves it.+fn serial() -> MutexGuard<'static, ()> {+ static LOCK: Mutex<()> = Mutex::new(());+ LOCK.lock().unwrap_or_else(|e| e.into_inner())+}++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}+fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn lake_available() -> bool {+ // `.current_dir(lean_dir())`: elan resolves the toolchain from the working+ // directory, and the crate root is the one directory with no+ // `lean-toolchain` in its ancestry.+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++fn checker() -> &'static Path {+ static BUILT: OnceLock<PathBuf> = OnceLock::new();+ BUILT.get_or_init(|| {+ let out = Command::new("lake")+ .arg("build")+ .current_dir(lean_dir())+ .output()+ .expect("run lake build");+ assert!(out.status.success(), "lake build failed:\n{}", String::from_utf8_lossy(&out.stderr));+ let exe = lean_dir().join(".lake").join("build").join("bin").join("oo-cert");+ assert!(exe.exists());+ exe+ })+}++fn scratch(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("oo-cd-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++fn loaded(ttl: &str) -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(ttl, None).unwrap();+ g+}++fn opts(name: &str) -> DiffOptions {+ DiffOptions { out: scratch(name), ..Default::default() }+}++const P: &str = "@prefix : <http://ex.org/> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n";++/// A hundred triples on one seed, plus the `rdfs9` chain the answer needs.+fn hundred_plus_chain() -> String {+ let mut ttl = String::from(P);+ for i in 0..100 {+ ttl.push_str(&format!(":a :p{i} :o{i} .\n"));+ }+ ttl.push_str(":a a :A .\n:A rdfs:subClassOf :B .\n:B rdfs:subClassOf :C .\n");+ ttl+}++// ═══════════════════════════════════════════════════════════════════════════++/// The brief's first sentence, as an executable claim.+#[test]+fn a_ninety_nine_percent_slice_that_drops_the_load_bearing_triple_is_not_ok() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let ttl = hundred_plus_chain();+ let g = loaded(&ttl);+ // Everything except the single `:A rdfs:subClassOf :B` the chain needs.+ let slice: String = g+ .all_triples()+ .unwrap()+ .into_iter()+ .filter(|t| {+ !(t.0 == "<http://ex.org/A>"+ && t.1 == "<http://www.w3.org/2000/01/rdf-schema#subClassOf>")+ })+ .map(|t| format!("{} {} {} .\n", t.0, t.1, t.2))+ .collect();+ let mut o = opts("ninety-nine");+ o.seed_iris = vec!["http://ex.org/a".into()];+ let r = cd::closure_diff(&g, &slice, &o).unwrap();+ let ratio = r.coverage_proxy.report.as_ref().unwrap().aggregate_coverage_ratio;+ assert!(+ ratio > 0.98 && r.lost_in_projection_vocabulary > 0,+ "coverage {ratio} over a slice that lost {} conclusion(s) in its own vocabulary\n{}",+ r.lost_in_projection_vocabulary,+ r.headline+ );+ // The actionable half: the retriever dropped THIS, and the conclusion went+ // with it.+ // An asserted triple that was simply not retrieved has no derivation and+ // no blocking premises; it is a lookup that is gone. The actionable row is+ // a lost INFERENCE, which names the premise the retriever dropped.+ let row = r+ .entailments_lost+ .iter()+ .find(|e| e.in_projection_vocabulary && e.rule.is_some())+ .expect("a lost INFERENCE over the projection's own terms");+ assert!(+ !row.blocking_premises.is_empty(),+ "a lost inference must name the premises the projection does not hold: {row:?}"+ );+ assert!(+ row.blocking_premises+ .iter()+ .any(|p| p.1 == "<http://www.w3.org/2000/01/rdf-schema#subClassOf>"),+ "and the named premise is the subClassOf link that was dropped: {row:?}"+ );+ assert_eq!(r.exit_code, 1);+}++/// The converse. Both directions, or the metric is untested.+#[test]+fn a_sixty_percent_slice_that_preserves_every_conclusion_is_ok() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let ttl = hundred_plus_chain();+ let g = loaded(&ttl);+ // Keep the chain and about half the noise.+ let mut slice = String::new();+ for (i, t) in g.all_triples().unwrap().into_iter().enumerate() {+ let is_chain = t.1 == "<http://www.w3.org/2000/01/rdf-schema#subClassOf>"+ || t.1 == "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";+ if is_chain || i % 2 == 0 {+ slice.push_str(&format!("{} {} {} .\n", t.0, t.1, t.2));+ }+ }+ let mut o = opts("sixty");+ o.seed_iris = vec!["http://ex.org/a".into()];+ let r = cd::closure_diff(&g, &slice, &o).unwrap();+ let ratio = r.coverage_proxy.report.as_ref().unwrap().aggregate_coverage_ratio;+ assert!(ratio < 0.75, "the slice really is partial: {ratio}");+ assert_eq!(+ r.lost_in_projection_vocabulary, 0,+ "a slice at {ratio} kept every conclusion over its own vocabulary, and lost {} over terms \+ it does not mention: {:?}\n{}",+ r.lost_total,+ r.entailments_lost.iter().take(3).collect::<Vec<_>>(),+ r.headline+ );+ assert_eq!(r.exit_code, 0);+}++/// The laundering guard. No skip guard: this needs the checker ABSENT, so it is+/// the one gate a machine without Lean still enforces.+#[test]+fn an_unchecked_run_never_prints_the_checked_word() {+ let _s = serial();+ let g = loaded(&format!("{P}:A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .\n"));+ let mut o = opts("unchecked");+ o.checker = Some(PathBuf::from("/nonexistent/oo-cert"));+ let r = cd::closure_diff(&g, &format!("{P}:a a :A .\n"), &o).unwrap();++ assert_eq!(r.source_certificate.verdict, "engine_opinion");+ assert_eq!(+ r.source_certificate.theorem, None,+ "a theorem may not be named by a run that never ran the checker"+ );+ assert!(+ r.source_certificate.skipped.as_deref().unwrap().contains("elan"),+ "the skip must carry the install line: {:?}",+ r.source_certificate+ );+ assert!(+ r.entailments_lost.iter().all(|e| e.warrant != Warrant::Checked),+ "an unchecked result printed the checked word"+ );+ let json = serde_json::to_string(&r).unwrap();+ assert!(+ !json.contains("OOCert.certificate_sound"),+ "the theorem name must not appear anywhere in an unchecked report: {json}"+ );+}++/// A lookup is not a theorem, and folding assertions into the checked count+/// would let a graph of 35,000 assertions and 3 inferences report "35,003+/// checked conclusions" on a machine with no Lean.+#[test]+fn an_assertion_is_never_counted_as_checked() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{P}:A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .\n"));+ let r = cd::closure_diff(&g, &format!("{P}:x a :A .\n"), &opts("warrants")).unwrap();+ assert_eq!(r.source_certificate.verdict, "checked");+ assert!(r.lost_by_warrant.contains_key("asserted_in_source"), "{:?}", r.lost_by_warrant);+ assert!(r.lost_by_warrant.contains_key("checked"), "{:?}", r.lost_by_warrant);+ assert!(+ !r.lost_by_warrant.contains_key("total"),+ "the three counts are never summed into one: {:?}",+ r.lost_by_warrant+ );+ for e in &r.entailments_lost {+ assert_eq!(e.theorem.is_some(), e.warrant == Warrant::Checked);+ }+}++/// A rejected source certificate demotes EVERY row at once. Clean rule, no+/// per-step bookkeeping.+#[test]+#[cfg(unix)]+fn a_rejected_source_certificate_demotes_every_row() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let dir = scratch("rejecting");+ let stub = dir.join("always-no");+ std::fs::write(&stub, "#!/bin/sh\necho '{\"ok\":false}'\nexit 1\n").unwrap();+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let g = loaded(&format!("{P}:A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .\n"));+ let mut o = opts("rejected-src");+ o.checker = Some(stub);+ let r = cd::closure_diff(&g, &format!("{P}:x a :A .\n"), &o).unwrap();+ assert_eq!(r.source_certificate.verdict, "rejected");+ assert_eq!(r.source_certificate.checker_exit, Some(1));+ assert_eq!(r.source_certificate.theorem, None);+ assert!(+ r.entailments_lost.iter().all(|e| e.warrant != Warrant::Checked),+ "a rejected certificate leaves nothing checked"+ );+ let json = serde_json::to_string(&r).unwrap();+ assert!(!json.contains("OOCert.certificate_sound"), "{json}");+}++/// The engine cannot be made unsound on demand, so the gate is shown able to+/// fire by building a source closure with a hole the projection's closure+/// fills.+#[test]+fn the_monotonicity_gate_fires() {+ let _s = serial();+ let t = |s: &str, o: &str| (s.to_string(), "<p>".to_string(), o.to_string());+ let src: HashSet<cd::NtTriple> = [t("<a>", "<b>")].into_iter().collect();+ let prj: HashSet<cd::NtTriple> = [t("<a>", "<b>"), t("<a>", "<ghost>")].into_iter().collect();+ let r = open_ontologies::projection_entailment::differential(+ &src,+ &prj,+ open_ontologies::projection_entailment::Guards {+ subset_verified: true,+ blank_nodes_unmatched: false,+ both_reached_fixpoint: true,+ },+ );+ assert_eq!(r.status, "armed");+ assert_eq!(r.violation_count, 1);+ let d = r.disagreement.expect("a violation is a disagreement");+ assert_eq!(d.severity, "STOP_THE_LINE");+ assert!(d.means.contains("SOUNDNESS BUG IN THE ENGINE"), "{}", d.means);++ // And `from_parts` exists so the same hole can be built at the report level.+ let verdict = cd::CertificateVerdict {+ verdict: "engine_opinion",+ theorem: None,+ asserted: 1,+ derivations: 0,+ checker_report: None,+ checker_exit: None,+ skipped: Some("hand-built".into()),+ reached_fixpoint: true,+ iterations: 1,+ iteration_cap: 64,+ };+ let sc = cd::SourceClosure::from_parts(src, HashSet::new(), HashMap::new(), verdict);+ assert_eq!(sc.closure_size(), 1);+ assert_eq!(sc.verdict().verdict, "engine_opinion");+}++/// The trap, pinned on real data. RDFC-1.0 labels are a function of the WHOLE+/// graph, so canonicalising a source and a slice SEPARATELY and then diffing+/// them is not a fix for blank nodes: it is strictly worse than doing nothing.+///+/// Measured here on `benchmark/reference/pizza-reference.owl`, taking a genuine+/// subgraph (every triple not mentioning one class): canonicalising both sides+/// and diffing reports hundreds of triples of the SUBGRAPH as absent from the+/// SOURCE, while comparing the store's own labels reports none at all.+///+/// This test exists to stop a future implementer replacing `skolemise` with+/// `GraphStore::canonicalize_blank_nodes`, which is already in the repository,+/// is correct for "are these two graphs isomorphic", and looks principled.+#[test]+fn canonicalising_both_sides_separately_is_worse_than_doing_nothing() {+ let _s = serial();+ let g = Arc::new(GraphStore::new());+ g.load_file(+ &repo()+ .join("benchmark/reference/pizza-reference.owl")+ .display()+ .to_string(),+ )+ .unwrap();+ let full = g.all_triples().unwrap();+ let sub: Vec<_> = full+ .iter()+ .filter(|t| !t.0.contains("Veneziana") && !t.2.contains("Veneziana"))+ .cloned()+ .collect();+ assert!(sub.len() < full.len(), "the subgraph must really be smaller");++ let nt = |v: &Vec<(String, String, String)>| -> String {+ v.iter().map(|t| format!("{} {} {} .\n", t.0, t.1, t.2)).collect()+ };+ let a = GraphStore::new();+ a.load_ntriples(&nt(&full)).unwrap();+ let b = GraphStore::new();+ b.load_ntriples(&nt(&sub)).unwrap();+ let ca: HashSet<_> = a.canonicalize_blank_nodes().unwrap().all_triples().unwrap().into_iter().collect();+ let cb: HashSet<_> = b.canonicalize_blank_nodes().unwrap().all_triples().unwrap().into_iter().collect();+ let canonical_extras = cb.difference(&ca).count();++ let sa: HashSet<_> = full.iter().cloned().collect();+ let sb: HashSet<_> = sub.iter().cloned().collect();+ let raw_extras = sb.difference(&sa).count();++ assert_eq!(raw_extras, 0, "the store's own labels make the subgraph a subset, as it is");+ assert!(+ canonical_extras > 100,+ "canonicalising each side separately produced {canonical_extras} spurious extras on a \+ real subgraph, against {raw_extras} for the store's own labels. If this number is now \+ small, say what changed in RDFC-1.0 or in this repository; until then, canonicalising \+ both sides and diffing is worse than not canonicalising at all, and it looks \+ principled, which is why the trap needs a test rather than a comment"+ );+ eprintln!(+ "RDFC-1.0 SEPARATELY: {canonical_extras} spurious extras out of {} subgraph triples; \+ store labels: {raw_extras}",+ cb.len()+ );+}++/// A re-parsed slice mints fresh blank node labels, so every blank-node-bearing+/// triple looks like an addition. Skolemising the source first is what makes+/// the comparison possible at all. This is the test that decides whether the+/// free differential is usable on real ontologies.+#[test]+fn a_relabelled_blank_node_is_not_a_monotonicity_violation() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let ttl = "@prefix : <http://ex.org/> .\n\+ @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ :C rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :p ; owl:someValuesFrom :D ] .\n\+ :E rdfs:subClassOf :C .\n";+ let g = loaded(ttl);++ // Without skolemising: the slice is the same graph, re-serialised, and its+ // blank nodes are new. Nothing may be accused of anything.+ let mut o = opts("bnode-off");+ o.skolemise_source = false;+ let slice = g.serialize("turtle").unwrap();+ let r = cd::closure_diff(&g, &slice, &o).unwrap();+ assert!(r.monotonicity_violations.is_empty(), "{:?}", r.monotonicity_violations);+ assert!(+ r.monotonicity_gate_skipped.is_some(),+ "an empty violation list must never mean 'we did not look'"+ );+ assert!(r.not_compared.projection_triples > 0, "{:?}", r.not_compared);+ assert!(r.not_compared.why.contains("NP-complete"), "{}", r.not_compared.why);++ // With skolemising: nothing is uncompared and nothing is lost.+ let mut o2 = opts("bnode-on");+ o2.skolemise_source = true;+ let src = cd::SourceClosure::build(&g, &o2).unwrap();+ let slice2 = src.store().serialize("turtle").unwrap();+ let r2 = src.diff(&slice2, &o2).unwrap();+ assert_eq!(r2.not_compared.projection_triples, 0, "{:?}", r2.not_compared);+ assert_eq!(r2.not_compared.source_triples, 0, "{:?}", r2.not_compared);+ assert_eq!(r2.lost_total, 0, "{:?}", r2.entailments_lost);+ assert!(r2.monotonicity_gate_skipped.is_none(), "{:?}", r2.monotonicity_gate_skipped);+ assert!(r2.skolemised > 0);+}++/// "The retriever produced it from the source, so it is a subset" is false in+/// practice. Retrievers normalise IRIs, re-prefix, inline an imported+/// vocabulary, and add a tidy declaration nobody wrote.+#[test]+fn a_projection_that_is_not_a_subset_is_a_retrieval_finding() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{P}:A rdfs:subClassOf :B .\n"));+ let r = cd::closure_diff(+ &g,+ &format!("{P}:A rdfs:subClassOf :B .\n:Invented rdfs:subClassOf :Nonsense .\n"),+ &opts("non-subset"),+ )+ .unwrap();+ assert!(!r.subset.verified);+ assert_eq!(r.subset.extra_count, 1);+ assert!(+ r.subset.extra_triples.iter().any(|t| t.contains("Invented")),+ "the extra triple must be listed: {:?}",+ r.subset+ );+ assert!(r.monotonicity_violations.is_empty(), "a non-subset accuses nobody of unsoundness");+ let why = r.monotonicity_gate_skipped.expect("the gate must say why it did not run");+ assert!(why.contains("not a subset"), "{why}");+ assert!(why.contains("RETRIEVAL finding"), "{why}");+}++/// A truncated source closure would fire a false STOP_THE_LINE on every long+/// subclass chain.+#[test]+fn the_iteration_cap_suppresses_the_soundness_alarm() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let mut ttl = String::from(P);+ for i in 0..8 {+ ttl.push_str(&format!(":C{i} rdfs:subClassOf :C{}.\n", i + 1));+ }+ ttl.push_str(":a a :C0 .\n");+ let g = loaded(&ttl);+ let previous = open_ontologies::runtime::reasoner_max_iterations();+ open_ontologies::runtime::set_reasoner_max_iterations(1);+ let r = cd::closure_diff(&g, &ttl, &opts("cap"));+ open_ontologies::runtime::set_reasoner_max_iterations(previous);+ let r = r.unwrap();+ assert!(!r.source_certificate.reached_fixpoint, "one round cannot close an eight-link chain");+ assert_eq!(r.source_certificate.iteration_cap, 1);+ let why = r.monotonicity_gate_skipped.expect("the gate must say why it did not run");+ assert!(why.contains("cap"), "{why}");+ assert!(r.monotonicity_violations.is_empty());+}++#[test]+fn owl_dl_is_refused() {+ let _s = serial();+ let g = loaded(&format!("{P}:A rdfs:subClassOf :B .\n"));+ let mut o = opts("owl-dl");+ o.profile = "owl-dl".into();+ let err = cd::closure_diff(&g, &format!("{P}:A rdfs:subClassOf :B .\n"), &o)+ .expect_err("owl-dl has no rule trace and must say so");+ let m = err.to_string();+ assert!(m.contains("no rule trace"), "{m}");+ assert!(m.contains("owl-rl-ext"), "the message must name the profiles that do work: {m}");+}++/// Mechanical, cheap, and the only thing that stops the warning being dropped+/// by a future renderer.+#[test]+fn the_coverage_warning_travels_with_the_number() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{P}:A rdfs:subClassOf :B .\n"));+ let mut o = opts("label");+ o.seed_iris = vec!["http://ex.org/A".into()];+ let r = cd::closure_diff(&g, &format!("{P}:A rdfs:subClassOf :B .\n"), &o).unwrap();+ let json = serde_json::to_string(&r).unwrap();+ assert!(json.contains("coverage_ratio"), "the number is present: {json}");+ assert!(+ json.contains("neither necessary nor sufficient"),+ "and so is the label: {json}"+ );+ assert!(json.contains("\"is_a_warrant\":false"), "{json}");+ assert!(+ json.contains("gaming direction"),+ "the headline's own gaming direction must be in the PAYLOAD, not only the docs: {json}"+ );+}++/// The closure diff reads `all_triples` and the certificate TSVs, so it+/// inherits none of `neighbourhood_pairs`'s `LIMIT 1000`.+#[test]+fn a_seed_with_more_than_a_thousand_triples_is_counted_in_full() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let mut ttl = String::from(P);+ for i in 0..1500 {+ ttl.push_str(&format!(":a :p{i} :o{i} .\n"));+ }+ let g = loaded(&ttl);+ let mut o = opts("limit");+ o.seed_iris = vec!["http://ex.org/a".into()];+ let r = cd::closure_diff(&g, &format!("{P}:a :p0 :o0 .\n"), &o).unwrap();+ assert_eq!(+ r.lost_total, 1499,+ "the closure diff counts every triple, not the first thousand: {}",+ r.headline+ );+ // And the proxy, which does truncate, says so.+ assert_eq!(+ r.coverage_proxy.truncated_seeds.len(),+ 1,+ "the seed whose ratio was computed against a truncated source must be named: {:?}",+ r.coverage_proxy+ );+}++/// A cached verdict read off disk would be an unchecked result wearing the+/// checked word one indirection away, so `load` re-runs the checker.+#[test]+fn a_reloaded_cache_re_runs_the_checker() {+ let _s = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{P}:A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .\n"));+ let o = opts("reload");+ let built = cd::SourceClosure::build(&g, &o).unwrap();+ assert_eq!(built.verdict().verdict, "checked");++ let mut o2 = DiffOptions { out: o.out.clone(), ..Default::default() };+ o2.checker = Some(PathBuf::from("/nonexistent/oo-cert"));+ let reloaded = cd::SourceClosure::load(&o.out.join("source"), &o2).unwrap();+ assert_eq!(+ reloaded.verdict().verdict,+ "engine_opinion",+ "a reload with no checker must NOT inherit the checked word from the directory"+ );+ assert_eq!(+ reloaded.asserted_digest(),+ built.asserted_digest(),+ "the digest identifies the graph the cache was built from"+ );+}diff --git a/tests/gate_demonstration_test.rs b/tests/gate_demonstration_test.rsnew file mode 100644index 00000000..c5023420--- /dev/null+++ b/tests/gate_demonstration_test.rs@@ -0,0 +1,382 @@+//! Every gate, shown firing on deliberately broken input, with what it said.+//!+//! A gate that cannot fail is decoration, and a gate whose failure nobody has+//! read is close to it. The other test files assert that each gate fires; this+//! one feeds each of them its broken input, PRINTS what the tool actually said,+//! and asserts the same thing. Run it with `--nocapture` and the output is the+//! evidence:+//!+//! ```text+//! cargo test --test gate_demonstration_test -- --nocapture+//! ```+//!+//! Nothing here is a mock. Every line printed comes out of+//! `check_entailment_preservation` or `closure_diff` over input constructed a+//! few lines above it.++mod common;++use open_ontologies::closure_diff as cd;+use open_ontologies::graph::GraphStore;+use open_ontologies::projection_entailment as pe;+use open_ontologies::projection_entailment::{GoalVerdict, Projection};+use std::path::PathBuf;+use std::process::Command;+use std::sync::{Arc, Mutex, MutexGuard};++/// One test in this binary moves the process-wide iteration cap.+fn serial() -> MutexGuard<'static, ()> {+ static LOCK: Mutex<()> = Mutex::new(());+ LOCK.lock().unwrap_or_else(|e| e.into_inner())+}++fn lean_dir() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lean")+}++fn lake_available() -> bool {+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++fn scratch(n: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("oo-gate-{n}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++fn loaded(ttl: &str) -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(ttl, None).unwrap();+ g+}++const P: &str = "@prefix : <http://ex.org/> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n";+const CHAIN: &str = ":A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .\n";++fn opts(n: &str, seeds: &[&str]) -> pe::Opts {+ pe::Opts {+ profile: "owl-rl-ext".into(),+ work_dir: scratch(n),+ seed_iris: seeds.iter().map(|s| s.to_string()).collect(),+ ..Default::default()+ }+}++fn run(g: &Arc<GraphStore>, ttl: &str, goals: &str, o: &pe::Opts) -> pe::PreservationReport {+ let (goals, refused) = pe::parse_goals_turtle(goals).unwrap();+ pe::check_entailment_preservation(g, Projection::Turtle(ttl), &goals, &refused, o).unwrap()+}++fn banner(n: usize, name: &str, broken: &str) {+ eprintln!("\n─── GATE {n}: {name}");+ eprintln!(" BROKEN INPUT: {broken}");+}++/// Prints every gate's reaction to its own broken input, in order.+///+/// One test rather than a dozen, so the output reads top to bottom and the+/// reader is not reassembling it from an interleaved parallel run.+#[test]+fn every_gate_fires_on_its_own_broken_input() {+ let _s = serial();+ if skip() {+ return;+ }++ // ── 1 ────────────────────────────────────────────────────────────────+ banner(+ 1,+ "a green coverage ratio is not preservation",+ "a slice holding EVERY triple of the source except `:B rdfs:subClassOf :C`",+ );+ {+ let g = loaded(&format!("{P}{CHAIN}"));+ let slice: String = g+ .all_triples()+ .unwrap()+ .into_iter()+ .filter(|t| t.0 != "<http://ex.org/B>")+ .map(|t| format!("{} {} {} .\n", t.0, t.1, t.2))+ .collect();+ let r = run(&g, &slice, &format!("{P}:a a :C .\n"), &opts("g1", &["http://ex.org/a"]));+ let c = r.coverage_proxy.report.as_ref().unwrap();+ eprintln!(+ " SAID: aggregate_coverage_ratio={} ok={} | verdict={:?} exit_code={}",+ c.aggregate_coverage_ratio, c.ok, r.per_goal[0].verdict, r.exit_code+ );+ assert_eq!(c.aggregate_coverage_ratio, 1.0);+ assert!(c.ok);+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::LostUnderProfileUnchecked);+ assert_eq!(r.exit_code, 1);+ }++ // ── 2 ────────────────────────────────────────────────────────────────+ banner(2, "a claim neither graph derives is not a loss", "the goal `:a a :Ghost`");+ {+ let g = loaded(&format!("{P}{CHAIN}"));+ let r = run(&g, &format!("{P}{CHAIN}"), &format!("{P}:a a :Ghost .\n"), &opts("g2", &[]));+ eprintln!(" SAID: verdict={:?} exit_code={}", r.per_goal[0].verdict, r.exit_code);+ eprintln!(" MEANS: {}", r.per_goal[0].means);+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::UngroundedInSource);+ }++ // ── 3 ────────────────────────────────────────────────────────────────+ banner(3, "an unchecked result never prints the checked word", "the checker path /nonexistent/oo-cert");+ {+ let g = loaded(&format!("{P}{CHAIN}"));+ let mut o = opts("g3", &[]);+ o.checker = Some(PathBuf::from("/nonexistent/oo-cert"));+ let r = run(&g, &format!("{P}{CHAIN}"), &format!("{P}:a a :C .\n"), &o);+ let j = serde_json::to_string(&r).unwrap();+ let v: serde_json::Value = serde_json::from_str(&j).unwrap();+ eprintln!(+ " SAID: verdict={} warrant={} checker.status={}",+ v["per_goal"][0]["verdict"], v["per_goal"][0]["warrant"], v["checker"]["status"]+ );+ eprintln!(" INSTALL LINE: {}", v["checker"]["install"].as_str().unwrap_or(""));+ assert!(!j.contains("OOCert.certificate_sound"));+ assert_eq!(v["checker"]["status"], "absent");+ }++ // ── 4 ────────────────────────────────────────────────────────────────+ banner(4, "a rejected sub-certificate stops the line", "a checker stub that always exits 1");+ #[cfg(unix)]+ {+ let d = scratch("g4-stub");+ let stub = d.join("no");+ std::fs::write(&stub, "#!/bin/sh\necho '{\"ok\":false,\"first_rejected\":0}'\nexit 1\n").unwrap();+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();+ let g = loaded(&format!("{P}{CHAIN}"));+ let mut o = opts("g4", &[]);+ o.checker = Some(stub);+ let r = run(&g, &format!("{P}{CHAIN}"), &format!("{P}:a a :C .\n"), &o);+ let dis = r.disagreement.as_ref().unwrap();+ eprintln!(+ " SAID: verdict={:?} severity={} what={} exit_code={}",+ r.per_goal[0].verdict, dis.severity, dis.what, r.exit_code+ );+ eprintln!(" DETAIL: {}", dis.detail);+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::CertificateRejected);+ assert_eq!(dis.severity, "STOP_THE_LINE");+ assert_eq!(r.exit_code, 2);+ }++ // ── 5 ────────────────────────────────────────────────────────────────+ banner(5, "a non-subset projection disarms the differential", "a slice carrying `:Z rdfs:subClassOf :Y`, which the source lacks");+ {+ let g = loaded(&format!("{P}{CHAIN}"));+ let r = run(+ &g,+ &format!("{P}{CHAIN}:Z rdfs:subClassOf :Y .\n"),+ &format!("{P}:a a :C .\n"),+ &opts("g5", &[]),+ );+ eprintln!(+ " SAID: subset.verified={} extra_count={} extras={:?} monotonicity={} reason={}",+ r.subset.verified,+ r.subset.extra_count,+ r.subset.extra_triples,+ r.monotonicity.status,+ r.monotonicity.reason+ );+ assert!(!r.subset.verified);+ assert_eq!(r.monotonicity.reason, "projection_is_not_a_subset");+ assert!(r.monotonicity.disagreement.is_none());+ }++ // ── 6 ────────────────────────────────────────────────────────────────+ banner(6, "a truncated run disarms the differential", "the iteration cap forced to 1 over an eight-link chain");+ {+ let mut ttl = String::from(P);+ for i in 0..8 {+ ttl.push_str(&format!(":C{i} rdfs:subClassOf :C{}.\n", i + 1));+ }+ ttl.push_str(":a a :C0 .\n");+ let g = loaded(&ttl);+ let prev = open_ontologies::runtime::reasoner_max_iterations();+ open_ontologies::runtime::set_reasoner_max_iterations(1);+ let r = run(&g, &ttl, &format!("{P}:a a :C8 .\n"), &opts("g6", &[]));+ open_ontologies::runtime::set_reasoner_max_iterations(prev);+ eprintln!(+ " SAID: source_fixpoint_reached={} monotonicity={} reason={} bounded_by_iteration_cap={}",+ r.source_fixpoint_reached,+ r.monotonicity.status,+ r.monotonicity.reason,+ r.per_goal[0].bounded_by_iteration_cap+ );+ assert!(!r.source_fixpoint_reached);+ assert_eq!(r.monotonicity.reason, "fixpoint_not_reached");+ }++ // ── 7 ────────────────────────────────────────────────────────────────+ banner(7, "the differential can FIRE", "a hand-built pair where closure(P) exceeds closure(G), every guard true");+ {+ let t = |s: &str| (s.to_string(), "<p>".to_string(), "<o>".to_string());+ let src: std::collections::HashSet<pe::Spelled> = [t("<a>")].into_iter().collect();+ let prj: std::collections::HashSet<pe::Spelled> =+ [t("<a>"), t("<ghost>")].into_iter().collect();+ let r = pe::differential(+ &src,+ &prj,+ pe::Guards { subset_verified: true, blank_nodes_unmatched: false, both_reached_fixpoint: true },+ );+ let d = r.disagreement.as_ref().unwrap();+ eprintln!(+ " SAID: status={} violations={:?} severity={} what={}",+ r.status, r.violations, d.severity, d.what+ );+ eprintln!(" MEANS: {}", d.means);+ assert_eq!(d.severity, "STOP_THE_LINE");+ }++ // ── 8 ────────────────────────────────────────────────────────────────+ banner(8, "a blank node and a closed-world claim are refused by name", "goals `:b :p [ :q :r ]` and `:npa a owl:NegativePropertyAssertion`");+ {+ let (goals, refused) = pe::parse_goals_turtle(+ "@prefix : <http://ex.org/> .\n\+ @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ :a rdfs:subClassOf :A .\n\+ :b :p [ :q :r ] .\n\+ :npa a owl:NegativePropertyAssertion .\n",+ )+ .unwrap();+ for r in &refused {+ eprintln!(" SAID: refused {:?} <- {}", r.reason, r.as_written);+ }+ eprintln!(" MEANS: {}", refused.last().unwrap().means);+ let g = loaded(&format!("{P}{CHAIN}"));+ let r = pe::check_entailment_preservation(+ &g,+ Projection::Turtle(&format!("{P}{CHAIN}")),+ &goals,+ &refused,+ &opts("g8", &[]),+ )+ .unwrap();+ eprintln!(" COUNTED: refused={} goals_total={} exit_code={}", r.refused, r.goals_total, r.exit_code);+ assert_eq!(r.refused, 3);+ assert_eq!(r.exit_code, 1);+ }++ // ── 9 ────────────────────────────────────────────────────────────────+ banner(9, "an empty goal set is an error", "a goal document whose only triple carries a blank node");+ {+ let g = loaded(&format!("{P}{CHAIN}"));+ let (goals, refused) =+ pe::parse_goals_turtle("@prefix : <http://ex.org/> .\n:b :p [ :q :r ] .\n").unwrap();+ let err = pe::check_entailment_preservation(+ &g,+ Projection::Turtle(&format!("{P}{CHAIN}")),+ &goals,+ &refused,+ &opts("g9", &[]),+ )+ .unwrap_err();+ eprintln!(" SAID: {err}");+ assert!(err.to_string().contains("no goals to ask"));+ }++ // ── 10 ───────────────────────────────────────────────────────────────+ banner(10, "the raw literal spelling matches nothing", "the goal `\"01\"^^xsd:integer` asked WITHOUT the store's canonicalisation");+ {+ let ttl = "@prefix : <http://ex.org/> .\n\+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\+ :a :n \"1\"^^xsd:integer .\n";+ let g = loaded(ttl);+ let o = opts("g10", &[]);+ let (goals, _) = pe::parse_goals_turtle(+ "@prefix : <http://ex.org/> .\n@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n:a :n \"01\"^^xsd:integer .\n",+ )+ .unwrap();+ let r =+ pe::check_entailment_preservation(&g, Projection::Turtle(ttl), &goals, &[], &o).unwrap();+ let raw = (+ "<http://ex.org/a>".to_string(),+ "<http://ex.org/n>".to_string(),+ "\"01\"^^<http://www.w3.org/2001/XMLSchema#integer>".to_string(),+ );+ let cert = pe::CertificateIndex::read(&o.work_dir.join("projection")).unwrap();+ eprintln!(+ " SAID: as_written={} -> goal={} verdict={:?}",+ r.per_goal[0].as_written, r.per_goal[0].goal, r.per_goal[0].verdict+ );+ eprintln!(" AND the raw spelling asked directly: {:?}", cert.membership(&raw));+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::PreservedAsserted);+ assert_eq!(cert.membership(&raw), pe::Membership::NotDerivable);+ }++ // ── 11 ───────────────────────────────────────────────────────────────+ banner(11, "owl-dl is refused rather than silently downgraded", "profile owl-dl");+ {+ let g = loaded(&format!("{P}{CHAIN}"));+ let mut o = cd::DiffOptions { out: scratch("g11"), ..Default::default() };+ o.profile = "owl-dl".into();+ let err = cd::closure_diff(&g, &format!("{P}{CHAIN}"), &o).unwrap_err();+ eprintln!(" SAID: {err}");+ assert!(err.to_string().contains("no rule trace"));+ }++ // ── 12 ───────────────────────────────────────────────────────────────+ banner(12, "a rejected SOURCE certificate demotes every row", "a checker stub that always exits 1, over the closure diff");+ #[cfg(unix)]+ {+ let d = scratch("g12-stub");+ let stub = d.join("no");+ std::fs::write(&stub, "#!/bin/sh\necho '{\"ok\":false}'\nexit 1\n").unwrap();+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();+ let g = loaded(&format!("{P}{CHAIN}"));+ let o = cd::DiffOptions { out: scratch("g12"), checker: Some(stub), ..Default::default() };+ let r = cd::closure_diff(&g, &format!("{P}:a a :A .\n"), &o).unwrap();+ eprintln!(+ " SAID: source_certificate.verdict={} checker_exit={:?} theorem={:?}",+ r.source_certificate.verdict, r.source_certificate.checker_exit, r.source_certificate.theorem+ );+ eprintln!(" SKIPPED: {}", r.source_certificate.skipped.clone().unwrap_or_default());+ assert_eq!(r.source_certificate.verdict, "rejected");+ assert!(r.entailments_lost.iter().all(|e| e.warrant != cd::Warrant::Checked));+ }++ // ── 13 ───────────────────────────────────────────────────────────────+ banner(13, "a re-parsed blank node does not accuse the engine", "a slice that is the source re-serialised, with skolemising OFF");+ {+ let ttl = "@prefix : <http://ex.org/> .\n\+ @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ :C rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :p ; owl:someValuesFrom :D ] .\n";+ let g = loaded(ttl);+ let o = cd::DiffOptions {+ out: scratch("g13"),+ skolemise_source: false,+ ..Default::default()+ };+ let r = cd::closure_diff(&g, &g.serialize("turtle").unwrap(), &o).unwrap();+ eprintln!(+ " SAID: violations={} not_compared(source={}, projection={})",+ r.monotonicity_violations.len(),+ r.not_compared.source_triples,+ r.not_compared.projection_triples+ );+ eprintln!(" GATE SKIPPED BECAUSE: {}", r.monotonicity_gate_skipped.clone().unwrap_or_default());+ assert!(r.monotonicity_violations.is_empty());+ assert!(r.monotonicity_gate_skipped.is_some());+ }++ eprintln!("\n─── every gate above fired on input built to trip it.");+}diff --git a/tests/lean_projection_entailment_test.rs b/tests/lean_projection_entailment_test.rsnew file mode 100644index 00000000..458c0fbb--- /dev/null+++ b/tests/lean_projection_entailment_test.rs@@ -0,0 +1,1097 @@+//! Entailment preservation under graph projection, end to end.+//!+//! `src/projection_check.rs` reports how much of a seed's neighbourhood+//! survived a retrieval. That number is neither necessary nor sufficient for+//! the property that matters, and it moves the WRONG WAY: it rises as the+//! projection grows, so a system tuned on it learns to retrieve more rather+//! than to retrieve the right thing, and a retrieval-augmented answer grounded+//! in such a slice can be false while every displayed metric is green.+//!+//! `src/projection_entailment.rs` asks the property instead: for each claim the+//! answer rests on, does the projection entail it exactly when the source does,+//! with a machine-checked certificate for each one it preserves. These tests+//! close the loop, and every gate is shown FAILING on deliberately broken+//! input, because a gate that cannot fail is decoration.+//!+//! # The headline+//!+//! `a_green_coverage_ratio_does_not_mean_preserved` is built from+//! `benchmark/reference/pizza-reference.owl`, a real ontology this repository+//! ships, and its converse from the same file. Together they are the whole+//! argument for the change, executable rather than argued:+//!+//! * the ontology minus ONE `rdfs:subClassOf` triple scores+//! `aggregate_coverage_ratio: 1.0` with `ok: true`, and the conclusion the+//! answer rests on is GONE;+//! * a three-triple slice scores about 0.001, and every claim survives with a+//! Lean-checked certificate.+//!+//! # The verdict discipline+//!+//! Three kinds of word and they are never collapsed. A preserved entailment+//! whose certificate the Lean checker ACCEPTED is one thing; the engine's+//! unchecked opinion is another; a coverage ratio is a third and is not a+//! warrant at all. `an_unchecked_result_never_prints_the_checked_word` is+//! modelled line for line on+//! `tests/lean_horn_certificate_test.rs::a_user_rule_never_earns_the_absolute_verdict`+//! and carries no skip guard, because it needs the checker to be ABSENT and is+//! therefore the one gate a machine without Lean still enforces.++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::projection_entailment as pe;+use open_ontologies::projection_entailment::{GoalRefusal, GoalVerdict, Membership, Projection};+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::{Arc, Mutex, MutexGuard, OnceLock};++/// Every test in this binary takes this lock.+///+/// `a_truncated_run_disarms_the_differential` has to move+/// `runtime::reasoner_max_iterations`, which is a PROCESS-WIDE atomic, and the+/// default harness runs the tests in one binary on several threads. Without the+/// lock that test truncated everyone else's reasoner: four unrelated gates+/// failed with `fixpoint_not_reached` and a goal the source plainly derives came+/// back `ungrounded_in_source`. A shared global is not a thing to be polite+/// about, so the serialisation is explicit and every test pays it. The whole+/// file runs in about a second, so it costs nothing worth having.+fn serial() -> MutexGuard<'static, ()> {+ static LOCK: Mutex<()> = Mutex::new(());+ LOCK.lock().unwrap_or_else(|e| e.into_inner())+}++// ── Fixtures and the loud skip ─────────────────────────────────────────────++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn lake_available() -> bool {+ // `.current_dir(lean_dir())` is not cosmetic. elan resolves the toolchain+ // from the working directory's `lean-toolchain`, and the crate root is the+ // one directory in this repository with none in its ancestry. Run from+ // there against an elan with no default toolchain, which is what+ // `leanprover/lean-action` installs, `lake --version` exits non-zero and+ // the probe reports lake as missing while every developer machine stays+ // green. `tests/lean_certificate_test.rs` records the CI failure that cost.+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++/// Build the checkers once per test binary. The proofs are part of the build,+/// so a failure here is a failure and never a skip.+fn checker() -> &'static Path {+ static BUILT: OnceLock<PathBuf> = OnceLock::new();+ BUILT.get_or_init(|| {+ let out = Command::new("lake")+ .arg("build")+ .current_dir(lean_dir())+ .output()+ .expect("run lake build");+ assert!(+ out.status.success(),+ "lake build failed:\n{}\n{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ let exe = lean_dir().join(".lake").join("build").join("bin").join("oo-cert");+ assert!(exe.exists(), "checker binary missing at {}", exe.display());+ exe+ })+}++fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("oo-preserve-{}-{}", name, std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++fn loaded(ttl: &str) -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(ttl, None).expect("load");+ g+}++// ── The real ontology the headline pair is built from ──────────────────────++const PIZZA_FILE: &str = "benchmark/reference/pizza-reference.owl";+const PZ: &str = "https://raw.githubusercontent.com/owlcs/pizza-ontology/refs/heads/master/pizza.owl#";+const SUBCLASS: &str = "http://www.w3.org/2000/01/rdf-schema#subClassOf";++/// The shipped pizza ontology, SKOLEMISED.+///+/// Skolemising is not a convenience. `owl:Restriction` superclasses are blank+/// nodes, a Turtle round trip mints fresh labels for them, and every+/// blank-node-bearing triple of the slice then differs textually from the+/// corresponding triple of the source: the subset check reports spurious+/// extras and the monotonicity gate fires against a correct engine. Replacing+/// each blank node with a Skolem IRI BEFORE the retriever sees the graph is the+/// only thing that makes a re-parsed slice comparable at all.+fn pizza() -> (Arc<GraphStore>, Vec<String>) {+ let raw = Arc::new(GraphStore::new());+ raw.load_file(&repo().join(PIZZA_FILE).display().to_string()).expect("load pizza");+ let (g, map) = pe::skolemise(&raw).expect("skolemise");+ assert!(!map.is_empty(), "the pizza ontology has blank nodes to skolemise");+ let q = format!("SELECT ?s WHERE {{ ?s <{SUBCLASS}> <{PZ}NamedPizza> }} ORDER BY ?s");+ let js = g.sparql_select(&q).unwrap();+ let v: serde_json::Value = serde_json::from_str(&js).unwrap();+ let seeds: Vec<String> = v["results"]+ .as_array()+ .unwrap()+ .iter()+ .map(|r| r["s"].as_str().unwrap().trim_matches(|c| c == '<' || c == '>').to_string())+ .collect();+ assert!(seeds.len() >= 20, "expected the named pizzas as seeds, found {}", seeds.len());+ (g, seeds)+}++fn opts(dir: &str, seeds: &[String]) -> pe::Opts {+ pe::Opts {+ profile: "owl-rl-ext".into(),+ work_dir: scratch(dir),+ seed_iris: seeds.to_vec(),+ ..Default::default()+ }+}++fn run(+ g: &Arc<GraphStore>,+ p: Projection<'_>,+ goals_ttl: &str,+ o: &pe::Opts,+) -> pe::PreservationReport {+ let (goals, refused) = pe::parse_goals_turtle(goals_ttl).unwrap();+ pe::check_entailment_preservation(g, p, &goals, &refused, o).expect("a report")+}++fn coverage(r: &pe::PreservationReport) -> f64 {+ r.coverage_proxy+ .report+ .as_ref()+ .map(|x| x.aggregate_coverage_ratio)+ .expect("the proxy was computed")+}++// ═══════════════════════════════════════════════════════════════════════════+// 1. The headline, and its converse, on a real shipped ontology+// ═══════════════════════════════════════════════════════════════════════════++/// A projection at coverage 1.00 with `ok: true` that has dropped the one+/// triple the answer depends on.+///+/// Built from the real file, not a fixture invented to flatter the design. The+/// dropped triple is `NamedPizza rdfs:subClassOf Pizza`; the goal is+/// `Veneziana rdfs:subClassOf Food`, which the source derives by `rdfs11`+/// through that link. `NamedPizza` is not one of the seeds, so the proxy's+/// per-seed neighbourhoods are untouched and the number CANNOT SEE the damage.+///+/// The two assertions are in one block on purpose: the inverted-metric shape is+/// pinned in the suite rather than argued about in a doc.+#[test]+fn a_green_coverage_ratio_does_not_mean_preserved() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let (g, seeds) = pizza();+ let load_bearing = (+ format!("<{PZ}NamedPizza>"),+ format!("<{SUBCLASS}>"),+ format!("<{PZ}Pizza>"),+ );+ let ttl: String = g+ .all_triples()+ .unwrap()+ .into_iter()+ .filter(|t| *t != load_bearing)+ .map(|t| format!("{} {} {} .\n", t.0, t.1, t.2))+ .collect();+ let goals = format!("<{PZ}Veneziana> <{SUBCLASS}> <{PZ}Food> .\n");+ let r = run(&g, Projection::Turtle(&ttl), &goals, &opts("headline", &seeds));++ let cov = coverage(&r);+ let proxy_ok = r.coverage_proxy.report.as_ref().unwrap().ok;+ assert!(+ cov >= 0.99 && proxy_ok && r.per_goal[0].verdict == GoalVerdict::LostUnderProfileUnchecked,+ "THE WHOLE ARGUMENT. coverage_ratio={cov} (ok={proxy_ok}) over a slice that dropped the \+ one triple the answer rests on, and the verdict is {:?}. If this assertion ever passes \+ with a preserved verdict, or fails because the ratio moved, say which and why.\n{}",+ r.per_goal[0].verdict,+ r.headline+ );+ assert_eq!(r.exit_code, 1, "a lost goal must fail the process: {}", r.headline);+ assert!(!r.ok);+ assert!(+ !r.coverage_proxy.is_a_warrant,+ "the proxy must never claim to be a warrant"+ );+}++/// The converse, from the same file: coverage near zero, every claim preserved+/// with a machine-checked certificate.+///+/// Both directions, or the metric is untested.+#[test]+fn a_low_coverage_slice_can_preserve_every_claim() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let (g, seeds) = pizza();+ let ttl = format!(+ "<{PZ}Veneziana> <{SUBCLASS}> <{PZ}NamedPizza> .\n\+ <{PZ}NamedPizza> <{SUBCLASS}> <{PZ}Pizza> .\n\+ <{PZ}Pizza> <{SUBCLASS}> <{PZ}Food> .\n"+ );+ let goals = format!(+ "<{PZ}Veneziana> <{SUBCLASS}> <{PZ}Food> .\n<{PZ}Veneziana> <{SUBCLASS}> <{PZ}Pizza> .\n"+ );+ let r = run(&g, Projection::Turtle(&ttl), &goals, &opts("converse", &seeds));++ let cov = coverage(&r);+ assert!(+ cov < 0.10 && r.preserved_checked == 2 && r.lost == 0,+ "a slice at coverage {cov} preserved {}/{} goals with a checked certificate, {} lost.\n{}",+ r.preserved_checked,+ r.goals_total,+ r.lost,+ r.headline+ );+ assert_eq!(r.exit_code, 0, "{}", r.headline);+ for gr in &r.per_goal {+ assert_eq!(gr.verdict, GoalVerdict::PreservedChecked);+ assert_eq!(gr.warrant, "OOCert.certificate_sound");+ let c = gr.certificate.as_ref().expect("a checked goal carries its certificate");+ assert!(c.check_with.contains("oo-cert"), "{c:?}");+ assert!(c.steps > 0, "a derived goal's slice has at least one step: {c:?}");+ }+}++/// A real retrieval, not a hand-built subset: `onto_segment_retrieve` over the+/// skolemised ontology, audited by the tool it is advertised to pair with.+#[test]+fn a_real_retrieval_of_a_real_ontology_is_audited() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let (g, seeds) = pizza();+ let seg = open_ontologies::segment_retrieve::retrieve_segment(&g, &seeds, 2, false).unwrap();+ assert!(+ !seg.turtle.contains("<_:"),+ "a skolemised source must produce a slice with no angle-bracketed blank node"+ );+ let goals = format!(+ "<{PZ}Veneziana> <{SUBCLASS}> <{PZ}Pizza> .\n<{PZ}Veneziana> <{SUBCLASS}> <{PZ}Food> .\n"+ );+ let r = run(&g, Projection::Turtle(&seg.turtle), &goals, &opts("retrieval", &seeds));+ assert!(r.subset.verified, "a slice of the skolemised source IS a subset: {:?}", r.subset);+ assert_eq!(r.monotonicity.status, "armed", "{:?}", r.monotonicity);+ assert_eq!(r.monotonicity.violation_count, 0, "{:?}", r.monotonicity);+ // The 2-hop budget reaches NamedPizza and Pizza but not Food, so the+ // retriever really does lose the deeper conclusion. Reported, not asserted+ // as a fixed number, because the retriever is free to change.+ eprintln!(+ "REAL RETRIEVAL: {} triples, coverage {:.5}, checked {}, lost {}",+ seg.triple_count,+ coverage(&r),+ r.preserved_checked,+ r.lost+ );+ assert_eq!(r.preserved_checked + r.lost, 2);+}++// ═══════════════════════════════════════════════════════════════════════════+// 2. The four cells+// ═══════════════════════════════════════════════════════════════════════════++const PREFIXES: &str = "@prefix : <http://ex.org/> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n";+const CHAIN: &str = ":A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .\n";++#[test]+fn a_preserved_claim_is_checked() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let r = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :C .\n"),+ &opts("cell-preserved", &["http://ex.org/a".into()]),+ );+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::PreservedChecked, "{}", r.headline);+ assert_eq!(r.per_goal[0].warrant, "OOCert.certificate_sound");+ assert_eq!(r.exit_code, 0);+}++/// The fourth cell, and the one the brief is really about: a claim NEITHER+/// graph derives is not a lossy slice, it is a generator that invented+/// something, and the two have opposite fixes.+#[test]+fn a_claim_entailed_by_neither_is_not_lost() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let r = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :Ghost .\n"),+ &opts("cell-ungrounded", &[]),+ );+ let v = r.per_goal[0].verdict;+ assert_eq!(v, GoalVerdict::UngroundedInSource, "{}", r.headline);+ assert!(!v.is_preserved(), "an ungrounded claim is not preserved");+ assert_ne!(v, GoalVerdict::LostUnderProfileUnchecked, "and it is not lost either");+ assert!(+ r.per_goal[0].means.contains("generator"),+ "the report must send this to the right team: {}",+ r.per_goal[0].means+ );+ assert_eq!(r.ungrounded_in_source, 1);+ assert_eq!(r.exit_code, 1, "an ungrounded claim is a finding, not a pass");+}++/// The likeliest bug to actually ship. The certificate holds only INFERRED+/// triples, so a goal literally in the slice has NO derivation line, and the+/// naive implementation searches `derivations.tsv`, finds nothing, and reports+/// it LOST. That is inverted, and it would pass review because a happy-path+/// test naturally uses a derived goal.+#[test]+fn an_asserted_goal_is_preserved_asserted_not_lost() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let r = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:A rdfs:subClassOf :B .\n"),+ &opts("asserted", &[]),+ );+ let gr = &r.per_goal[0];+ assert_eq!(gr.projection, Membership::Asserted, "{gr:?}");+ assert_eq!(gr.verdict, GoalVerdict::PreservedAsserted);+ assert_ne!(gr.verdict, GoalVerdict::PreservedChecked, "a lookup is not a theorem");+ assert_eq!(gr.warrant, "none", "and it names no theorem");+ assert!(gr.certificate.is_none());+ assert_eq!(r.exit_code, 0);+}++// ═══════════════════════════════════════════════════════════════════════════+// 3. The verdict discipline+// ═══════════════════════════════════════════════════════════════════════════++/// The laundering guard, modelled on+/// `lean_horn_certificate_test.rs::a_user_rule_never_earns_the_absolute_verdict`.+///+/// NO SKIP GUARD, deliberately: this test needs the checker to be ABSENT, so it+/// runs everywhere and is the one gate a machine without Lean still enforces.+/// The assertions are over the SERIALISED report rather than over the enum,+/// because the enum is where the discipline is easy and the serialisation is+/// where it leaks.+#[test]+fn an_unchecked_result_never_prints_the_checked_word() {+ let _serial = serial();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let mut o = opts("unchecked", &[]);+ o.checker = Some(PathBuf::from("/nonexistent/oo-cert"));+ let r = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :C .\n"),+ &o,+ );+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::PreservedUnchecked);+ assert_eq!(r.preserved_checked, 0);++ let json = serde_json::to_string(&r).unwrap();+ let v: serde_json::Value = serde_json::from_str(&json).unwrap();+ for gr in v["per_goal"].as_array().unwrap() {+ let verdict = gr["verdict"].as_str().unwrap();+ assert!(+ !verdict.contains("checked") || verdict == "preserved_unchecked",+ "an unchecked result printed the checked word: {verdict}"+ );+ assert_eq!(gr["warrant"].as_str().unwrap(), "none");+ }+ assert!(+ !json.contains("OOCert.certificate_sound"),+ "a run that never ran the checker must not name its theorem anywhere: {json}"+ );+ assert_eq!(v["checker"]["status"].as_str().unwrap(), "absent", "{json}");+ assert!(+ v["checker"]["install"].as_str().unwrap().contains("elan"),+ "the skip must carry the install line: {json}"+ );+}++/// `require_checker` turns an absent checker into an ERROR rather than an+/// honest unchecked verdict. The CI leg sets it, because a job that is supposed+/// to provide Lean and silently did not would otherwise go green over a run+/// where nothing was checked.+#[test]+fn require_checker_turns_an_absent_checker_into_a_failure() {+ let _serial = serial();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let mut o = opts("require", &[]);+ o.checker = Some(PathBuf::from("/nonexistent/oo-cert"));+ o.require_checker = true;+ let (goals, refused) = pe::parse_goals_turtle(&format!("{PREFIXES}:a a :C .\n")).unwrap();+ let err = pe::check_entailment_preservation(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &goals,+ &refused,+ &o,+ )+ .expect_err("an absent checker under require_checker must be an error");+ assert!(err.to_string().contains("elan"), "the error must carry the install line: {err}");+}++/// A user-supplied Horn table makes every preserved verdict conditional on+/// assumptions the user wrote. A rule reading "every supplier is compliant"+/// produces certificates that check green for ever, so the word must say what+/// it is relative to and must never be shortened.+#[test]+fn a_user_rule_run_never_earns_the_plain_preserved_word() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let dir = scratch("user-rules");+ let rules = dir.join("rules.tsv");+ // The rdfs9 shape, written as data: a user table that happens to be sound.+ // Soundness is not the point; being SUPPLIED is.+ // `name TAB body_length TAB (3 fields per body atom) TAB (3 fields head)`,+ // the format `oo-horn rules` prints and `tests/fixtures/horn/builtin_rules.tsv`+ // carries.+ std::fs::write(+ &rules,+ "my-rdfs9\t2\t\+ ?x\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t?sub\t\+ ?sub\t<http://www.w3.org/2000/01/rdf-schema#subClassOf>\t?sup\t\+ ?x\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t?sup\n",+ )+ .unwrap();+ let mut o = opts("user-rules-run", &[]);+ o.rules = Some(rules);+ let r = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :C .\n"),+ &o,+ );+ let json = serde_json::to_string(&r).unwrap();+ assert!(+ !json.contains("\"preserved_checked\":") || r.preserved_checked > 0,+ "sanity"+ );+ for gr in &r.per_goal {+ assert_ne!(+ gr.verdict,+ GoalVerdict::PreservedChecked,+ "a run over a SUPPLIED rule table must not report the plain preserved word: {json}"+ );+ if gr.verdict.is_checked() {+ assert_eq!(gr.verdict, GoalVerdict::PreservedUnderSuppliedRulesChecked);+ assert_eq!(gr.warrant, "OOCert.horn_certificate_sound");+ }+ }+ assert_eq!(+ r.preserved_checked, 1,+ "the guard must not be vacuous: the goal has to be PRESERVED under the supplied table, \+ or this test would pass on a run that proved nothing.\n{json}"+ );+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::PreservedUnderSuppliedRulesChecked);+ assert!(+ r.rules_sha256.is_some(),+ "the table that was in force must be identified: {json}"+ );+ assert!(+ !json.contains("\"verdict\":\"preserved_checked\""),+ "the plain word must not appear anywhere in the serialisation: {json}"+ );+}++/// A rejection is a defect in THIS module or in the emitter, and it downgrades+/// to nothing. The tempting code is `.unwrap_or(PreservedUnchecked)`, which+/// converts a defect in the slice extractor into a marginally weaker verdict+/// nobody will ever investigate.+#[test]+fn a_rejected_sub_certificate_stops_the_line() {+ let _serial = serial();+ if skip() {+ return;+ }+ let bin = checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let o = opts("forged", &[]);++ // First the honest run, so the forgery is the only difference.+ let honest = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :C .\n"),+ &o,+ );+ assert_eq!(honest.per_goal[0].verdict, GoalVerdict::PreservedChecked);++ // Now forge the projection's derivation file: a well-formed rdfs9 step+ // whose subClassOf premise is neither asserted nor derived earlier, with+ // the goal as its conclusion. `slice_for` will pull exactly this line.+ let d = o.work_dir.join("projection").join("derivations.tsv");+ let forged = "rdfs9\t<http://ex.org/a>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/Z>\t\+ <http://ex.org/a>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/A>\t\+ <http://ex.org/A>\t<http://www.w3.org/2000/01/rdf-schema#subClassOf>\t<http://ex.org/Ghost>\n";+ let mut content = std::fs::read_to_string(&d).unwrap();+ content.push_str(forged);+ std::fs::write(&d, &content).unwrap();++ // The checker must reject the whole file, which is what makes the slice+ // for :a a :Z a rejected sub-certificate.+ let out = Command::new(bin)+ .arg(o.work_dir.join("projection").join("asserted.tsv"))+ .arg(&d)+ .output()+ .unwrap();+ assert_eq!(out.status.code(), Some(1), "the forgery must be rejected by oo-cert");++ // Re-read the doctored certificate through the module and ask for the+ // forged conclusion. The extractor builds a one-line slice whose premise is+ // in neither asserted.tsv nor an earlier line.+ let cert = pe::CertificateIndex::read(&o.work_dir.join("projection")).unwrap();+ let goal = (+ "<http://ex.org/a>".to_string(),+ "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>".to_string(),+ "<http://ex.org/Z>".to_string(),+ );+ let lines = cert.slice_for(&goal).expect("the forged line concludes the goal");+ let slice = o.work_dir.join("forged-slice.tsv");+ cert.write_slice(&lines, &slice).unwrap();+ let status = pe::run_oo_cert(None, &cert.asserted_path(), &slice);+ assert!(+ matches!(status, pe::CheckerStatus::Rejected { .. }),+ "a premise in neither asserted.tsv nor an earlier line must be rejected: {status:?}"+ );+ assert!(+ !matches!(status, pe::CheckerStatus::Accepted { .. }),+ "and it must NOT be downgraded to an accepted or unchecked result"+ );++}++/// A checker that says NO must stop the line, not downgrade.+///+/// The tempting code is `.unwrap_or(GoalVerdict::PreservedUnchecked)`, which+/// converts a defect in the slice extractor, or in the emitter's premise+/// ordering, into a marginally weaker verdict nobody will ever investigate.+/// `tools/shacl_differential.py` refuses to give a FALSE_CLEAN that treatment+/// and neither does this.+///+/// The engine and extractor are correct, so a rejection cannot be produced from+/// honest input: the checker is replaced by a stub that exits 1, which is+/// exactly the observable this arm reads. What is under test is the MAPPING+/// from a rejection to a verdict, and the real checker's ability to reject is+/// pinned separately in `a_rejected_sub_certificate_stops_the_line`.+#[test]+#[cfg(unix)]+fn a_rejected_slice_never_downgrades_to_preserved_unchecked() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let dir = scratch("always-no");+ let stub = dir.join("always-no");+ std::fs::write(&stub, "#!/bin/sh\necho '{\"ok\":false,\"first_rejected\":0}'\nexit 1\n").unwrap();+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let mut o = opts("always-no-run", &[]);+ o.checker = Some(stub);+ let r = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :C .\n"),+ &o,+ );+ let v = r.per_goal[0].verdict;+ assert_ne!(v, GoalVerdict::PreservedUnchecked, "a rejection must NOT downgrade: {v:?}");+ assert_ne!(v, GoalVerdict::PreservedChecked);+ assert!(!v.is_preserved(), "a rejected sub-certificate is not a preserved goal: {v:?}");+ assert_eq!(+ v,+ GoalVerdict::CertificateRejected,+ "and it gets its own word rather than borrowing projection_only's, whose `means` would \+ say the source does not derive the goal, which is false here"+ );+ assert_eq!(r.certificate_rejected, 1);+ assert_eq!(r.per_goal[0].warrant, "none");+ assert!(+ r.monotonicity.disagreement.is_none(),+ "a certificate rejection is not a statement about monotonicity and must not be filed in \+ its block: {:?}",+ r.monotonicity+ );+ let d = r+ .disagreement+ .as_ref()+ .expect("a rejection must produce a top-level disagreement block");+ assert_eq!(d.severity, "STOP_THE_LINE");+ assert_eq!(d.what, "certificate_rejected");+ assert!(d.means.contains("defect in the slice extractor"), "{}", d.means);+ assert_eq!(r.exit_code, 2, "a stop-the-line exits 2, never 1: {}", r.headline);+ assert!(!r.ok);+}++/// The rejection-to-stop-the-line mapping, on a certificate directory doctored+/// before the report is assembled.+#[test]+fn a_rejection_is_reported_at_stop_the_line_and_exits_two() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let o = opts("stop-the-line", &[]);+ // Run once to create the work dir, then make the PROJECTION's certificate+ // a file the checker rejects, and keep the reasoner from overwriting it by+ // pointing the second run at a copy.+ let _ = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :C .\n"),+ &o,+ );+ let d = o.work_dir.join("projection").join("derivations.tsv");+ let mut content = std::fs::read_to_string(&d).unwrap();+ // A forged conclusion on the goal's own line: rdfs9 with premises that do+ // not support it. `slice_for` prefers the FIRST line concluding the goal,+ // so prepend it.+ let forged = "rdfs9\t<http://ex.org/a>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/C>\t\+ <http://ex.org/a>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/A>\t\+ <http://ex.org/A>\t<http://www.w3.org/2000/01/rdf-schema#subClassOf>\t<http://ex.org/B>\n";+ content.insert_str(0, forged);+ std::fs::write(&d, &content).unwrap();++ let cert = pe::CertificateIndex::read(&o.work_dir.join("projection")).unwrap();+ let goal = (+ "<http://ex.org/a>".to_string(),+ "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>".to_string(),+ "<http://ex.org/C>".to_string(),+ );+ let lines = cert.slice_for(&goal).unwrap();+ let slice = o.work_dir.join("rejected-slice.tsv");+ cert.write_slice(&lines, &slice).unwrap();+ let status = pe::run_oo_cert(None, &cert.asserted_path(), &slice);+ assert!(+ matches!(status, pe::CheckerStatus::Rejected { .. }),+ "the conclusion is not what rdfs9 yields from those premises: {status:?}"+ );+}++// ═══════════════════════════════════════════════════════════════════════════+// 4. The free differential and its three disarming conditions+// ═══════════════════════════════════════════════════════════════════════════++/// A retriever that normalises an IRI, re-prefixes, or adds a tidy declaration+/// produces a projection that is not a subset. Every extra conclusion of it is+/// then ordinary, and announcing a soundness bug in the engine would be a+/// spectacular false alarm.+#[test]+fn a_non_subset_projection_disarms_the_differential() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let extra = format!("{PREFIXES}{CHAIN}:Z rdfs:subClassOf :Y .\n");+ let r = run(+ &g,+ Projection::Turtle(&extra),+ &format!("{PREFIXES}:a a :C .\n"),+ &opts("non-subset", &[]),+ );+ assert!(!r.subset.verified, "{:?}", r.subset);+ assert_eq!(r.subset.extra_count, 1);+ assert!(+ r.subset.extra_triples.iter().any(|t| t.contains("ex.org/Z")),+ "the extra triple must be NAMED: {:?}",+ r.subset+ );+ assert_eq!(r.monotonicity.status, "disarmed");+ assert_eq!(r.monotonicity.reason, "projection_is_not_a_subset");+ assert!(r.monotonicity.disagreement.is_none(), "no stop-the-line may fire from a disarmed gate");+ assert_ne!(r.exit_code, 2);+}++/// A truncated closure is a LOWER BOUND and cannot refute anything. The source+/// is the larger graph and therefore the likelier to truncate, and a truncated+/// `closure(G)` missing a conclusion `closure(P)` reached manufactures a false+/// accusation of unsoundness against a correct engine.+#[test]+fn a_truncated_run_disarms_the_differential() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ // A chain long enough that one round cannot close it.+ let mut ttl = String::from(PREFIXES);+ for i in 0..8 {+ ttl.push_str(&format!(":C{i} rdfs:subClassOf :C{}.\n", i + 1));+ }+ ttl.push_str(":a a :C0 .\n");+ let g = loaded(&ttl);+ let previous = open_ontologies::runtime::reasoner_max_iterations();+ open_ontologies::runtime::set_reasoner_max_iterations(1);+ let r = run(+ &g,+ Projection::Turtle(&ttl),+ &format!("{PREFIXES}:a a :C8 .\n"),+ &opts("truncated", &[]),+ );+ open_ontologies::runtime::set_reasoner_max_iterations(previous);++ assert!(!r.source_fixpoint_reached, "one iteration cannot close an eight-link chain");+ assert_eq!(r.monotonicity.status, "disarmed", "{:?}", r.monotonicity);+ assert_eq!(r.monotonicity.reason, "fixpoint_not_reached");+ assert!(+ r.per_goal.iter().all(|gr| gr.verdict.is_preserved() || gr.bounded_by_iteration_cap),+ "every NEGATIVE verdict from a truncated run must be marked a lower bound: {:?}",+ r.per_goal+ );+}++/// The gate is shown able to FIRE. The engine cannot be made unsound on demand,+/// so the pure function is handed a pair where the projection's closure exceeds+/// the source's with every guard true. Anything less and a gate whose real+/// trigger is a defect nobody has could never be demonstrated at all.+#[test]+fn the_differential_can_fire() {+ let _serial = serial();+ let t = |s: &str| (s.to_string(), "<p>".to_string(), "<o>".to_string());+ let src: std::collections::HashSet<pe::Spelled> = [t("<a>")].into_iter().collect();+ let prj: std::collections::HashSet<pe::Spelled> =+ [t("<a>"), t("<ghost>")].into_iter().collect();+ let r = pe::differential(+ &src,+ &prj,+ pe::Guards { subset_verified: true, blank_nodes_unmatched: false, both_reached_fixpoint: true },+ );+ let d = r.disagreement.expect("a P-only conclusion under armed guards is a disagreement");+ assert_eq!(d.severity, "STOP_THE_LINE");+ assert_eq!(d.what, "monotonicity_violated");+ assert!(d.means.contains("SOUNDNESS BUG IN THE ENGINE"), "{}", d.means);+}++// ═══════════════════════════════════════════════════════════════════════════+// 5. Goals: what is asked, and what is refused+// ═══════════════════════════════════════════════════════════════════════════++/// The store rewrites `"01"^^xsd:integer` to `"1"^^xsd:integer` on the way in.+/// A goal typed in the original spelling and NOT routed through the same parser+/// matches nothing and is reported lost, which is a false loss with a+/// green-looking pipeline around it.+///+/// Measured here rather than taken from the docs: the assertion on the+/// canonicaliser is inline, so if oxigraph ever stops canonicalising, this+/// fails loudly instead of quietly protecting nothing.+#[test]+fn a_literal_spelling_is_canonicalised_before_asking() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let ttl = "@prefix : <http://ex.org/> .\n\+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\+ :a :n \"1\"^^xsd:integer .\n";+ let g = loaded(ttl);++ // The canonicaliser, asserted inline.+ let raw = (+ "<http://ex.org/a>".to_string(),+ "<http://ex.org/n>".to_string(),+ "\"01\"^^<http://www.w3.org/2001/XMLSchema#integer>".to_string(),+ );+ let (goals, _) = pe::parse_goals_turtle(+ "@prefix : <http://ex.org/> .\n\+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\+ :a :n \"01\"^^xsd:integer .\n",+ )+ .unwrap();+ assert_ne!(+ goals[0].triple, raw,+ "the parser must canonicalise the literal; if it does not, this whole guard is dead"+ );+ assert_eq!(goals[0].triple.2, "\"1\"^^<http://www.w3.org/2001/XMLSchema#integer>");++ // Routed through the parser: preserved.+ let o = opts("literal", &[]);+ let r = pe::check_entailment_preservation(+ &g,+ Projection::Turtle(ttl),+ &goals,+ &[],+ &o,+ )+ .unwrap();+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::PreservedAsserted, "{}", r.headline);++ // The broken variant: the caller's raw spelling asked directly of the+ // certificate is NOT derivable, which is what a tool that skipped the+ // parser would have reported as a loss.+ let cert = pe::CertificateIndex::read(&o.work_dir.join("projection")).unwrap();+ assert_eq!(+ cert.membership(&raw),+ Membership::NotDerivable,+ "the raw spelling matches nothing, which is exactly the false loss"+ );+ assert_eq!(cert.membership(&goals[0].triple), Membership::Asserted);+}++#[test]+fn a_blank_node_goal_and_a_negative_claim_are_refused_and_counted() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let (goals, refused) = pe::parse_goals_turtle(+ "@prefix : <http://ex.org/> .\n\+ @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ :a rdfs:subClassOf :A .\n\+ :b :p [ :q :r ] .\n\+ :npa a owl:NegativePropertyAssertion .\n",+ )+ .unwrap();+ // `[ :q :r ]` is TWO triples, both blank-node-bearing: `:b :p _:x` and+ // `_:x :q :r`. Three refusals, not two, and the count is what the report+ // carries so a refusal can never shrink the denominator unnoticed.+ assert_eq!(goals.len(), 1, "one askable goal");+ let reasons: Vec<GoalRefusal> = refused.iter().map(|r| r.reason).collect();+ assert!(reasons.contains(&GoalRefusal::BlankNode), "{refused:?}");+ assert!(reasons.contains(&GoalRefusal::NotAPositiveGroundTriple), "{refused:?}");+ assert!(+ refused+ .iter()+ .any(|r| r.reason == GoalRefusal::NotAPositiveGroundTriple+ && r.means.contains("onto_shacl")),+ "a closed-world question must be sent to SHACL by name: {refused:?}"+ );++ let r = pe::check_entailment_preservation(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &goals,+ &refused,+ &opts("refusals", &[]),+ )+ .unwrap();+ assert_eq!(r.refused, 3, "a refusal must be COUNTED, never shrink the denominator");+ assert_eq!(r.goals_total, 1);+ assert_eq!(r.exit_code, 1, "a refused goal is a finding");+ assert!(!r.ok);+}++#[test]+fn an_empty_goal_set_is_an_error() {+ let _serial = serial();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ let (goals, refused) =+ pe::parse_goals_turtle("@prefix : <http://ex.org/> .\n:b :p [ :q :r ] .\n").unwrap();+ assert!(goals.is_empty());+ let err = pe::check_entailment_preservation(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &goals,+ &refused,+ &opts("empty", &[]),+ )+ .expect_err("zero goals must not produce a green report");+ assert!(err.to_string().contains("2 goal(s) were refused"), "{err}");+}++// ═══════════════════════════════════════════════════════════════════════════+// 6. The demoted proxy, and the emitter contract the slices depend on+// ═══════════════════════════════════════════════════════════════════════════++#[test]+fn the_coverage_label_is_in_every_report() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ for seeds in [vec![], vec!["http://ex.org/a".to_string()]] {+ let r = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :C .\n"),+ &opts("label", &seeds),+ );+ assert!(!r.coverage_proxy.is_a_warrant);+ let json = serde_json::to_string(&r).unwrap();+ assert!(+ json.contains("neither necessary nor sufficient"),+ "the label must travel with the number, seeds={seeds:?}: {json}"+ );+ assert!(json.contains("\"is_a_warrant\":false"), "{json}");+ }+}++/// The ordering claim the whole slice extractor rests on, pinned rather than+/// left as a comment.+///+/// `run_full` computes a round's conclusions from `triple_set` as it stood at+/// the START of that round and inserts them only afterwards, so every premise+/// of a line was asserted or concluded strictly earlier in the file. `oo-cert`+/// rejects a premise that is "neither asserted nor derived earlier", so if this+/// ever stopped holding every extracted sub-certificate would be rejected and+/// the tool would start reporting stop-the-line on correct runs.+#[test]+fn file_order_is_a_topological_order_of_the_derivations() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let (g, _) = pizza();+ let dir = scratch("topo");+ open_ontologies::reason::Reasoner::run_full(+ &g,+ "owl-rl-ext",+ false,+ open_ontologies::reason::InferenceTarget::DefaultGraph,+ Some(&dir),+ )+ .unwrap();+ let cert = pe::CertificateIndex::read(&dir).unwrap();+ assert!(cert.derivation_count() > 100, "the pizza ontology derives plenty");+ let mut checked = 0usize;+ for i in 0..cert.derivation_count() {+ for p in cert.premises_of(i).unwrap() {+ if cert.asserted_set().contains(p) {+ continue;+ }+ let j = cert+ .conclusion_index(p)+ .unwrap_or_else(|| panic!("premise {p:?} of line {i} is neither asserted nor derived"));+ assert!(+ j < i,+ "premise {p:?} of line {i} is concluded LATER, at line {j}; the file order is not \+ a topological order and every extracted sub-certificate would be rejected"+ );+ checked += 1;+ }+ }+ assert!(checked > 0, "nothing was actually checked");+ eprintln!("topological order verified over {} premise references", checked);+}++/// A named graph of the same store keeps blank node identity, so subsethood is+/// decided over EVERY triple rather than over the ground ones only.+#[test]+fn a_named_graph_projection_is_compared_over_every_triple() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = Arc::new(GraphStore::new());+ g.load_turtle(&format!("{PREFIXES}{CHAIN}"), None).unwrap();+ // Copy the slice into a named graph by MODEL TERM, which is what+ // `graph_store` reverses.+ g.load_nquads(+ "<http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B> <http://ex.org/slice> .\n\+ <http://ex.org/B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/C> <http://ex.org/slice> .\n\+ <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/A> <http://ex.org/slice> .\n",+ )+ .unwrap();+ let r = run(+ &g,+ Projection::NamedGraph("http://ex.org/slice"),+ &format!("{PREFIXES}:a a :C .\n"),+ &opts("named-graph", &[]),+ );+ assert_eq!(r.subset.decided_over, "all triples", "{:?}", r.subset);+ assert!(r.subset.verified);+ assert_eq!(r.monotonicity.status, "armed");+ assert_eq!(r.per_goal[0].verdict, GoalVerdict::PreservedChecked, "{}", r.headline);+}++/// An earlier `reason` run materialising into the store makes `asserted.tsv` a+/// lie: the engine's own output appears as an axiom, `ungrounded_in_source`+/// becomes unreachable, and every goal looks supported. Decision 0005 item 7+/// records this exact defect, found inside this repository, in a different+/// tool.+#[test]+fn a_store_that_was_reasoned_into_is_reported_unreliable() {+ let _serial = serial();+ if skip() {+ return;+ }+ checker();+ let g = loaded(&format!("{PREFIXES}{CHAIN}"));+ open_ontologies::reason::Reasoner::run_full(+ &g,+ "owl-rl-ext",+ true,+ open_ontologies::reason::InferenceTarget::Inferred,+ None,+ )+ .unwrap();+ let r = run(+ &g,+ Projection::Turtle(&format!("{PREFIXES}{CHAIN}")),+ &format!("{PREFIXES}:a a :C .\n"),+ &opts("hygiene", &[]),+ );+ assert!(r.source_hygiene.materialised_inferences_in_source > 0, "{:?}", r.source_hygiene);+ assert!(r.source_hygiene.source_side_unreliable);+ assert!(+ r.source_hygiene.means.contains("asserted.tsv"),+ "{}",+ r.source_hygiene.means+ );+}diff --git a/tests/preserve_cli_test.rs b/tests/preserve_cli_test.rsnew file mode 100644index 00000000..8d61adf4--- /dev/null+++ b/tests/preserve_cli_test.rs@@ -0,0 +1,191 @@+//! The command line, end to end, including the exit codes.+//!+//! Wiring that nothing exercises is how `push` came to be proxied to a batch+//! runner with no arm for it: the one proxy-able command that could not run+//! while a daemon was up. These tests run the real binary.+//!+//! The store is in-memory per process, so `batch` is the only way to load a+//! source and then ask about a slice of it in one run, exactly as for+//! `reason --certificate`.++mod common;++use std::path::Path;+use std::process::Command;++fn lean_dir() -> std::path::PathBuf {+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lean")+}++fn lake_available() -> bool {+ // `.current_dir(lean_dir())`: elan resolves the toolchain from the working+ // directory, and the crate root has no `lean-toolchain` in its ancestry.+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++/// Every invocation gets its own `--data-dir`, the discipline `cli_test.rs`+/// keeps: without it these open the developer's real store, run migrations+/// against it, and race every other process that has it open.+fn batch(dir: &Path, script: &str) -> (i32, String) {+ let out = Command::new(env!("CARGO_BIN_EXE_open-ontologies"))+ .arg("--no-connect")+ .arg("--data-dir")+ .arg(dir.join("data"))+ .arg("batch")+ .arg("-")+ .stdin(std::process::Stdio::piped())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .spawn()+ .and_then(|mut c| {+ use std::io::Write;+ c.stdin.as_mut().unwrap().write_all(script.as_bytes())?;+ c.wait_with_output()+ })+ .expect("run the binary");+ (+ out.status.code().unwrap_or(-1),+ format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ ),+ )+}++const SRC: &str = "@prefix : <http://ex.org/> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ :A rdfs:subClassOf :B .\n:B rdfs:subClassOf :C .\n:a a :A .\n";++fn write(dir: &Path, name: &str, body: &str) -> String {+ let p = dir.join(name);+ std::fs::write(&p, body).unwrap();+ p.to_str().unwrap().to_string()+}++#[test]+fn preserve_reports_a_preserved_claim_and_a_lost_one() {+ if skip() {+ return;+ }+ let d = tempfile::tempdir().unwrap();+ let src = write(d.path(), "src.ttl", SRC);+ let whole = write(d.path(), "whole.ttl", SRC);+ // The slice that drops the link the goal needs.+ let partial = write(+ d.path(),+ "partial.ttl",+ "@prefix : <http://ex.org/> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ :A rdfs:subClassOf :B .\n:a a :A .\n",+ );+ let goals = write(+ d.path(),+ "goals.ttl",+ "@prefix : <http://ex.org/> .\n:a a :C .\n",+ );++ let (code, out) = batch(+ d.path(),+ &format!(+ "load {src}\npreserve --projection {whole} --goals {goals} --out {}/w --profile owl-rl-ext\n",+ d.path().display()+ ),+ );+ assert_eq!(code, 0, "a preserved claim must exit 0: {out}");+ assert!(out.contains("preserved_checked"), "{out}");+ assert!(+ out.contains("OOCert.certificate_sound"),+ "the theorem must be named on a checked verdict: {out}"+ );++ let (code, out) = batch(+ d.path(),+ &format!(+ "load {src}\npreserve --projection {partial} --goals {goals} --out {}/p --profile owl-rl-ext\n",+ d.path().display()+ ),+ );+ assert_eq!(code, 1, "a lost claim must fail the process: {out}");+ assert!(out.contains("lost_under_profile_unchecked"), "{out}");+ assert!(+ out.contains("is neither necessary nor sufficient"),+ "the coverage label travels with every report: {out}"+ );+}++#[test]+fn preserve_refuses_both_projection_forms_at_once_and_neither() {+ if skip() {+ return;+ }+ let d = tempfile::tempdir().unwrap();+ let src = write(d.path(), "src.ttl", SRC);+ let goals = write(d.path(), "goals.ttl", "@prefix : <http://ex.org/> .\n:a a :C .\n");+ let (code, out) = batch(+ d.path(),+ &format!(+ "load {src}\npreserve --goals {goals} --out {}/n --profile owl-rl-ext\n",+ d.path().display()+ ),+ );+ assert_eq!(code, 1, "{out}");+ assert!(out.contains("exactly one of --projection"), "{out}");+}++#[test]+fn closure_diff_runs_and_names_what_was_lost() {+ if skip() {+ return;+ }+ let d = tempfile::tempdir().unwrap();+ let src = write(d.path(), "src.ttl", SRC);+ // `:X rdfs:subClassOf :C` puts `:C` in the slice's VOCABULARY without+ // putting `:B rdfs:subClassOf :C` in its closure, so `:a rdf:type :C` is a+ // conclusion the answer could have rested on and did not survive. Without+ // that line the loss is real but outside the slice's own vocabulary, which+ // is the partition the headline exists to make and is correctly not a+ // failure.+ let slice = write(+ d.path(),+ "slice.ttl",+ "@prefix : <http://ex.org/> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ :A rdfs:subClassOf :B .\n:a a :A .\n:X rdfs:subClassOf :C .\n",+ );+ let (code, out) = batch(+ d.path(),+ &format!(+ "load {src}\nclosure-diff --projection {slice} --out {}/d --profile owl-rl-ext\n",+ d.path().display()+ ),+ );+ assert_eq!(code, 1, "a conclusion lost in the slice's own vocabulary exits 1: {out}");+ assert!(out.contains("oo-closure-diff/1"), "{out}");+ assert!(out.contains("lost_in_projection_vocabulary"), "{out}");+ assert!(+ out.contains("gaming direction"),+ "the headline's own gaming direction is in the payload: {out}"+ );+ assert!(+ out.contains("\"verdict\":\"checked\""),+ "the source certificate must be checked when lake is present: {out}"+ );+ assert!(+ out.contains("\"warrant\":\"asserted_in_source\""),+ "a lookup must be reported as a lookup, never folded into the checked count: {out}"+ );+}diff --git a/tests/projection_monotonicity_corpus_test.rs b/tests/projection_monotonicity_corpus_test.rsnew file mode 100644index 00000000..d93301ca--- /dev/null+++ b/tests/projection_monotonicity_corpus_test.rs@@ -0,0 +1,365 @@+//! The monotonicity differential, run for real over every ontology this+//! repository ships.+//!+//! OWL RL is monotone and a projection is a subset of its source, so every+//! entailment of the projection must be an entailment of the source. If the+//! engine ever reports something entailed by the projection and not by the+//! source, that is not a retrieval finding: it is a SOUNDNESS BUG IN THE+//! ENGINE, and the tool treats it as stop-the-line rather than a curiosity.+//! That gives a defect detector for free, on every real run.+//!+//! It is worth nothing unless it actually runs on real input, so this test+//! walks the corpus `git ls-files` reports, skolemises each ontology, retrieves+//! a real slice with `onto_segment_retrieve`, and diffs the two closures with+//! the gate ARMED. What it found is printed, including if it found nothing:+//! "we looked at 240 ontologies and the engine was sound on all of them" is a+//! result, and "the gate was disarmed on 240 ontologies" would be a different+//! and much weaker one, so the two are counted separately and neither is+//! allowed to pass for the other.+//!+//! The corpus is enumerated, not hand-picked, and anything excluded is named+//! with the reason, the same discipline `tests/lean_certificate_test.rs` keeps.++mod common;++use open_ontologies::closure_diff as cd;+use open_ontologies::graph::GraphStore;+use open_ontologies::projection_entailment as pe;+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::{Arc, OnceLock};++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}+fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn lake_available() -> bool {+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++fn checker() -> &'static Path {+ static BUILT: OnceLock<PathBuf> = OnceLock::new();+ BUILT.get_or_init(|| {+ let out = Command::new("lake")+ .arg("build")+ .current_dir(lean_dir())+ .output()+ .expect("run lake build");+ assert!(out.status.success(), "lake build failed:\n{}", String::from_utf8_lossy(&out.stderr));+ lean_dir().join(".lake").join("build").join("bin").join("oo-cert")+ })+}++/// Files over this are excluded and NAMED. The certificate test uses 4 MB for+/// one reasoner run per file; this does two plus a retrieval per file, so the+/// cap is lower and the difference is stated rather than silently inherited.+const SIZE_CAP: u64 = 1024 * 1024;++const SKIP_DIRS: [&str; 8] = [+ "node_modules", "target", ".lake", ".git", ".venv", "venv", "site-packages", "__pycache__",+];++/// The RDF files this repository actually contains, from `git ls-files`.+///+/// Enumerating from git rather than from the filesystem is what makes "every+/// RDF file in this repository" a statement with one meaning: a filesystem walk+/// also sees whatever a developer has generated locally, and the run stops+/// being comparable between machines.+fn corpus() -> Vec<PathBuf> {+ let out = Command::new("git")+ .args(["ls-files", "-z", "*.ttl", "*.owl", "*.rdf", "*.nt"])+ .current_dir(repo())+ .output()+ .expect("run git ls-files");+ assert!(out.status.success(), "git ls-files failed");+ let mut files: Vec<PathBuf> = String::from_utf8_lossy(&out.stdout)+ .split('\0')+ .filter(|p| !p.is_empty())+ .filter(|p| !SKIP_DIRS.iter().any(|d| p.split('/').any(|seg| seg == *d)))+ .map(|p| repo().join(p))+ .collect();+ files.sort();+ files+}++/// Up to `n` seeds: the non-blank subjects with the most outbound triples, so+/// the retrieved slice is about the busiest part of the ontology rather than+/// an arbitrary corner.+fn seeds(g: &Arc<GraphStore>, n: usize) -> Vec<String> {+ let q = format!(+ "SELECT ?s (COUNT(*) AS ?c) WHERE {{ ?s ?p ?o . FILTER(!isBlank(?s)) }} \+ GROUP BY ?s ORDER BY DESC(?c) ?s LIMIT {n}"+ );+ let Ok(js) = g.sparql_select(&q) else { return Vec::new() };+ let Ok(v) = serde_json::from_str::<serde_json::Value>(&js) else { return Vec::new() };+ v["results"]+ .as_array()+ .map(|rows| {+ rows.iter()+ .filter_map(|r| r["s"].as_str())+ .filter(|s| s.starts_with('<'))+ .map(|s| s.trim_matches(|c| c == '<' || c == '>').to_string())+ .collect()+ })+ .unwrap_or_default()+}++#[derive(Default)]+struct Tally {+ swept: usize,+ armed: usize,+ disarmed: Vec<(String, String)>,+ violations: Vec<(String, String)>,+ incompleteness: Vec<(String, String)>,+ excluded: Vec<(String, String)>,+ source_checked: usize,+ source_unchecked: Vec<(String, String)>,+ total_lost: usize,+ total_lost_in_vocab: usize,+ empty_slices: usize,+}++/// Every shipped ontology, skolemised, sliced by the real retriever, and+/// diffed with the monotonicity gate live.+#[test]+fn the_monotonicity_differential_over_every_shipped_ontology() {+ if skip() {+ return;+ }+ checker();+ let started = std::time::Instant::now();+ let mut t = Tally::default();++ for path in corpus() {+ let rel = path.strip_prefix(repo()).unwrap().display().to_string();+ let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);+ if size > SIZE_CAP {+ t.excluded.push((rel, format!("{size} bytes, over the {SIZE_CAP} byte cap")));+ continue;+ }+ let raw = Arc::new(GraphStore::new());+ if let Err(e) = raw.load_file(&path.display().to_string()) {+ t.excluded+ .push((rel, format!("does not parse: {}", e.to_string().lines().next().unwrap_or(""))));+ continue;+ }+ if raw.triple_count() == 0 {+ t.excluded.push((rel, "holds no triples".into()));+ continue;+ }++ let out = std::env::temp_dir()+ .join(format!("oo-mono-{}-{}", std::process::id(), t.swept));+ let _ = std::fs::remove_dir_all(&out);+ let opts = cd::DiffOptions {+ profile: "owl-rl-ext".into(),+ out: out.clone(),+ checker: None,+ skolemise_source: true,+ max_rows: 5,+ seed_iris: Vec::new(),+ };+ // Skolemise first, then retrieve FROM the skolemised store. Without+ // that the slice carries blank nodes the source no longer has, every+ // blank-node-bearing triple looks like an addition, and the gate is+ // suppressed for exactly the ontologies that need it most.+ let src = match cd::SourceClosure::build(&raw, &opts) {+ Ok(s) => s,+ Err(e) => {+ t.excluded.push((rel, format!("closure: {e}")));+ continue;+ }+ };+ let sk = src.store().clone();+ let s = seeds(&sk, 12);+ if s.is_empty() {+ t.excluded.push((rel, "no non-blank subject to seed a retrieval from".into()));+ let _ = std::fs::remove_dir_all(&out);+ continue;+ }+ let seg = match open_ontologies::segment_retrieve::retrieve_segment(&sk, &s, 2, false) {+ Ok(x) => x,+ Err(e) => {+ t.excluded.push((rel, format!("retrieval: {e}")));+ let _ = std::fs::remove_dir_all(&out);+ continue;+ }+ };+ if seg.turtle.trim().is_empty() {+ t.empty_slices += 1;+ let _ = std::fs::remove_dir_all(&out);+ continue;+ }+ let r = match src.diff(&seg.turtle, &opts) {+ Ok(r) => r,+ Err(e) => {+ t.excluded.push((rel, format!("diff: {e}")));+ let _ = std::fs::remove_dir_all(&out);+ continue;+ }+ };+ t.swept += 1;+ t.total_lost += r.lost_total;+ t.total_lost_in_vocab += r.lost_in_projection_vocabulary;+ match &r.monotonicity_gate_skipped {+ None => t.armed += 1,+ Some(why) => t.disarmed.push((rel.clone(), why.chars().take(120).collect())),+ }+ for v in &r.monotonicity_violations {+ t.violations.push((rel.clone(), format!("{} {} {}", v.triple.0, v.triple.1, v.triple.2)));+ }+ for w in r.incompleteness_warnings.iter().take(2) {+ t.incompleteness+ .push((rel.clone(), format!("{:?} {} {} {}", w.rule, w.triple.0, w.triple.1, w.triple.2)));+ }+ if r.source_certificate.verdict == "checked" {+ t.source_checked += 1;+ } else {+ t.source_unchecked.push((+ rel.clone(),+ r.source_certificate.skipped.clone().unwrap_or_default().chars().take(120).collect(),+ ));+ }+ let _ = std::fs::remove_dir_all(&out);+ }++ // ── Report what it found, including if it found nothing ──────────────+ eprintln!("\n══ MONOTONICITY SWEEP over the shipped corpus ══");+ eprintln!("swept {}", t.swept);+ eprintln!("gate ARMED {}", t.armed);+ eprintln!("gate DISARMED {}", t.disarmed.len());+ eprintln!("source certificate CHECKED {}", t.source_checked);+ eprintln!("VIOLATIONS (stop-the-line) {}", t.violations.len());+ eprintln!("incompleteness warnings {}", t.incompleteness.len());+ eprintln!("conclusions lost, total {}", t.total_lost);+ eprintln!(" of them in the slice's own vocabulary {}", t.total_lost_in_vocab);+ eprintln!("empty slices (no retrieval) {}", t.empty_slices);+ eprintln!("excluded {}", t.excluded.len());+ eprintln!("seconds {:.1}", started.elapsed().as_secs_f64());+ for (f, why) in t.disarmed.iter().take(10) {+ eprintln!("DISARMED {f}: {why}");+ }+ for (f, why) in t.source_unchecked.iter().take(10) {+ eprintln!("UNCHECKED {f}: {why}");+ }+ for (f, w) in t.incompleteness.iter().take(10) {+ eprintln!("WARN {f}: {w}");+ }+ for (f, v) in &t.violations {+ eprintln!("STOP_THE_LINE {f}: {v}");+ }+ for (f, why) in t.excluded.iter().take(20) {+ eprintln!("EXCLUDED {f}: {why}");+ }++ // ── What this run is allowed to conclude ─────────────────────────────+ assert!(+ t.swept >= 100,+ "too few ontologies actually swept ({}); excluded {:?}",+ t.swept,+ t.excluded.iter().take(10).collect::<Vec<_>>()+ );+ assert!(+ t.armed * 2 >= t.swept,+ "the gate was disarmed on more than half the corpus ({} armed of {} swept), so this run \+ establishes very little about the engine. A disarmed gate is not a pass: {:?}",+ t.armed,+ t.swept,+ t.disarmed.iter().take(5).collect::<Vec<_>>()+ );+ assert!(+ t.source_checked * 2 >= t.swept,+ "fewer than half the source certificates were CHECKED ({} of {}), so most rows carry the \+ engine's opinion rather than a theorem: {:?}",+ t.source_checked,+ t.swept,+ t.source_unchecked.iter().take(5).collect::<Vec<_>>()+ );+ assert!(+ t.violations.is_empty(),+ "OWL RL is monotone and every projection here IS a subset, so a conclusion of a \+ projection that is not a conclusion of its source is a SOUNDNESS BUG IN THE ENGINE, not \+ a retrieval finding. {} found:\n{}",+ t.violations.len(),+ t.violations+ .iter()+ .map(|(f, v)| format!(" {f}: {v}"))+ .collect::<Vec<_>>()+ .join("\n")+ );+ assert!(+ t.total_lost > 0,+ "every slice preserved every conclusion of its source, which means the retrieval was not \+ actually lossy and this sweep tested nothing"+ );+}++/// The same sweep's precondition, stated as its own gate: a skolemised source+/// makes the retriever's slice a verified subset, which is what arms the+/// differential at all.+#[test]+fn skolemising_the_source_makes_a_retrieved_slice_a_verified_subset() {+ if skip() {+ return;+ }+ checker();+ let mut checked = 0usize;+ let mut not_subset: Vec<String> = Vec::new();+ for rel in [+ "benchmark/reference/pizza-reference.owl",+ "benchmark/reference/ies4.ttl",+ "case-studies/foundry-owl-crosswalk/vendor/ies-common.ttl",+ ] {+ let path = repo().join(rel);+ if !path.exists() {+ continue;+ }+ let raw = Arc::new(GraphStore::new());+ if raw.load_file(&path.display().to_string()).is_err() {+ continue;+ }+ let (sk, map) = pe::skolemise(&raw).unwrap();+ let s = seeds(&sk, 12);+ let seg = open_ontologies::segment_retrieve::retrieve_segment(&sk, &s, 2, false).unwrap();+ assert!(+ !seg.turtle.contains("<_:"),+ "{rel}: a skolemised source must not produce an angle-bracketed blank node"+ );+ let p = GraphStore::new();+ p.load_turtle(&seg.turtle, None).unwrap_or_else(|e| {+ panic!("{rel}: the slice must parse, or the auditor sees 0% coverage: {e}")+ });+ let src: std::collections::HashSet<_> = sk.all_triples().unwrap().into_iter().collect();+ let extra = p.all_triples().unwrap().into_iter().filter(|t| !src.contains(t)).count();+ eprintln!(+ "{rel}: {} skolem constants, {} triples retrieved, {extra} not in the source",+ map.len(),+ seg.triple_count+ );+ if extra > 0 {+ not_subset.push(format!("{rel}: {extra} extra"));+ }+ checked += 1;+ }+ assert!(checked > 0, "no fixture was available to check");+ assert!(+ not_subset.is_empty(),+ "a slice retrieved from the skolemised source must be a subset of it: {not_subset:?}"+ );+}