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
Each step of a claimed reasoning trace is labelled entailed, not entailed, or outside the fragment (#264)
Fabio Rovaiec16b1a5d465
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6b3ad5ba..87e86645 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -550,6 +550,17 @@ 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: Label a reasoning trace step by step, and check a user rule cannot earn the absolute word there either+ # The per-step form of the leg above. Every label a step can carry comes+ # out of an exit code this job's binaries produced, so without them the+ # file skips and reports `ok`, which is exactly what+ # OO_REQUIRE_FIXTURES=1 is here to stop. Two of its gates are the ones+ # this job exists for: a step licensed by a rule the user wrote reaches+ # `entailed_under_supplied_rules_checked` and nothing stronger, asserted+ # over the SERIALISED report; and a step whose own reasoning is sound+ # over premises the store does not hold is reported as exactly that+ # rather than as entailed.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test trace_label_test -- --nocapture- name: Run the README's own example and check it says what the README says# Issue #162. "Try the checker itself" prints three commands and the# JSON each returned, and until now nothing re-ran them, so the pagediff --git a/CLAUDE.md b/CLAUDE.mdindex 9aeaf53f..bc557ac5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -19,6 +19,7 @@ When building or modifying ontologies, follow this workflow. Claude decides whic6. Call `onto_defects` FIRST. A reasoner amplifies whatever the declarations say, so a self-contradicting ontology makes every inference suspect. Fix what it reports before materializing anything7. Call `onto_dlp_boundary` SECOND, and read it before trusting anything `onto_reason` returns. `onto_defects` asks whether the declarations contradict each other; this asks a different question the rest of the pipeline never answers: **which of your axioms the rule table can actually see**. A certificate from `onto_reason` is a sound proof about the axioms the rules read and says nothing at all about the ones no rule fires on, so a green certificate over an ontology whose TBox is half invisible is true and misleading at once. The report keeps three failures apart and you act on each differently, because they are fixed in three different places. An axiom `outside_the_fragment` (a disjunction in the consequent, an existential in the head, a cardinality restriction, a negation in the antecedent) is not Horn, and only a rewrite of the ontology helps. An axiom `inside_the_fragment_but_a_rule_is_not_implemented` (`owl:hasKey`, `owl:propertyChainAxiom`, `owl:FunctionalProperty`) is Horn, has an OWL 2 RL rule, and is invisible only because this engine does not run it, so nothing about the ontology is wrong. And an axiom `partially_inside_the_fragment` is half seen, and the question is which half you needed. `not_fully_seen_by_the_rule_table` carries all three counts and never adds them+7a. `onto_dlp_boundary` answers that question for the ONTOLOGY. `onto_trace_label` answers it for one TRACE: hand it a reasoning trace that claims inference steps and each step comes back `entailed`, `not_entailed` or `outside_the_fragment`, with the same two dimensions kept apart, so a step nobody could ever derive is never reported as a step this graph happens not to support. It also reports the LOCAL answer separately, over the premises the step itself cited, so a step whose reasoning is valid over triples the graph does not hold is visible as exactly that rather than as sound. Over a rule table YOU supply, a checked step earns `entailed_under_supplied_rules_checked` and the family word carries the same qualification, never the bare word, and the report carries the table digest8. Call `onto_reason` with profile `rdfs` or `owl-rl` to materialize inferred triples (transitive subclass chains, domain/range propagation, equivalentClass expansion). The profile decides how much of the rule table runs: `rdfs` evaluates 6 of the 29 rules, `owl-rl` 17 and `owl-rl-ext` all 29, and `onto_dlp_boundary` reports which9. Call `onto_stats` again to verify inferred triple counts are reasonable@@ -77,6 +78,7 @@ Claude dynamically decides the next tool call based on what the previous tool re| `onto_vocab_check` | To closed-world-check generated DATA: flags any predicate/class used that is not declared in the loaded ontology (hallucinated terms). Catches what open-world SHACL silently passes. Run on LLM-generated Turtle before `onto_load` || `onto_defects` | BEFORE trusting any fact-level result, and on every marketplace pack before adopting it. Checks the ONTOLOGY against itself with no data present: `transitive_and_functional`, `symmetric_and_asymmetric`, `subclass_cycle`, `sub_property_cycle`, `disjoint_with_ancestor`, `inherited_disjoint`, `self_inverse`, `inverse_not_mutual`. A different question from `onto_dl_check`: a transitive functional property is satisfiable and is still a trap, because the pair manufactures contradictions the moment instances arrive. Each kind is listed at most 50 times, with the full total under `truncated` || `onto_dlp_boundary` | BEFORE trusting any `onto_reason` result, in the same register as `onto_defects`. Asks which of YOUR axioms the rule engine can actually SEE. A certificate from `onto_reason` is a sound proof about the axioms the rules read and says nothing about the ones no rule fires on, so a user can reason, get a green machine-checked certificate, and never learn that a third of the TBox was invisible. TWO DIMENSIONS THAT ARE NEVER MERGED, because one is a rewrite of the ontology and the other is a patch to this engine. (1) THE FRAGMENT: is the axiom Horn at all? The line is OWL 2 RL's class grammar (OWL 2 Profiles 4.3), and `outside` there would hold of a perfect OWL 2 RL engine: disjunction in the consequent, existential in the head, cardinality restriction, negation in the antecedent, each listed per axiom with the reason. (2) THIS ENGINE: does a rule fire on it? `owl:hasKey` and `owl:propertyChainAxiom` are Horn, OWL 2 RL has `prp-key` and `prp-spo2`, and this engine runs neither, so they are INSIDE the fragment and still invisible. An axiom that splits soundly is `partially_inside`: `A subClassOf (B and Out)` keeps its `A subClassOf B` half, and an `owl:equivalentClass` with an existential on one side keeps the direction `cls-svf1` evaluates. A conjunction in the ANTECEDENT does not split, because dropping a conjunct from a rule body makes it fire more often. The rule-table figures (78 OWL 2 RL rules, 29 evaluated, 10 more detected only as a clash, 7 that conclude false and are not looked for) are DERIVED from `src/reason.rs`, not typed. Every triple lands in an axiom bucket or a counted `not_classified` one. NOT a consistency check |+| `onto_trace_label` | AFTER a model, an agent or a person hands you a reasoning trace and BEFORE you believe any step of it. Takes the trace in `oo-trace/1`, which is the same line `onto_reason`'s `derivations.tsv` writes, so a certificate this engine emitted is itself a valid trace. THREE FAMILIES, and the third is the reason to use this rather than an LLM judge. `entailed`: a Lean checker accepted a certificate slice of the run that concludes the triple. `not_entailed`: a rule head in the table could conclude a triple of this shape, every axiom the step cites is inside the fragment, and the graph still does not support it. `outside_the_fragment`: no data could ever make this table derive it, and the two reasons stay apart exactly as `onto_dlp_boundary` keeps them apart, because `outside_the_fragment` is a rewrite of the ontology and `no_rule_in_this_table_concludes_this_shape` is a patch to `src/reason.rs`. Under the built-in table the second of those is unreachable and that is a fact about the table: `rdfs7`'s head is three variables, so some data makes it conclude any triple at all. TWO ANSWERS PER STEP AND NEITHER IS REPORTED AS THE OTHER: `local` is a one-line certificate over the premises the STEP cited, so a step whose own reasoning is machine-checked sound over triples the graph does not hold reads `premises_in_store: false` and `locally_sound_but_premises_not_in_the_store` rather than sound. `rule_claim` is a third field and says whether the cited rule is the rule that licensed it, because a mistyped rule name is a citation defect and calling it `not_entailed` would be a false statement about the ontology. Over a rule table YOU supply, a checked step earns `entailed_under_supplied_rules_checked` under `OOCert.horn_certificate_sound` and the family word says the same, never the bare word, and the report carries `rules_tsv_sha256` and `conditional_on`. The word is read off the theorem name the checker printed and is not chosen by the Rust. Writes `labels.jsonl`, one machine-checked record per step, naming the command that reproduces it || `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples. Pass `inference_graph: true` to keep them in `https://open-ontologies.org/graph/inferred` instead of the default graph, so nothing downstream can read an inference as an assertion and `onto_save` to Turtle/RDF-XML cannot publish one. Default false (unchanged behaviour); not available for `owl-dl`. Pass `certificate_dir` to also write a derivation certificate (`asserted.tsv` + `derivations.tsv`) that the proved-sound Lean checker in `lean/` verifies, plus `refutation.tsv` when the run finds a contradiction `oo-refute` can judge. Ten of the seventeen OWL 2 RL rules that conclude `false` are detected and only `cax-dw` is certifiable, so `inconsistency.verdict` is `clash_found_by_this_engine` and NEVER the checker's `unsatisfiable_under_disjointness`; no clash found is not consistency; see docs/lean-certificates.md || `onto_reason_incremental` | After adding facts to an already-materialised graph. Derives the consequences of the ADDED triples only (semi-naive evaluation, joining the delta against the closure), so the cost tracks what changed rather than the size of the store: effectively instant against a 1.9M-triple store where full re-materialisation takes seconds. Refuses schema axioms (subClassOf, domain, range, inverseOf, equivalentClass) with an explanation, because those change what the whole store entails: run `onto_reason` for them || `onto_rules_import` | To read rules you wrote in a STANDARD rule syntax into the Horn rule table `onto_reason` evaluates with `rules_file`. `from: "swrl"` reads SWRL rules encoded in RDF (`swrl:Imp` with `swrl:body`/`swrl:head` as `rdf:List` atom lists) out of the loaded graph or out of `file`; `from: "rif"` reads RIF Core in its XML syntax (the presentation syntax is refused, not half-read). Only a FRAGMENT of each language is a Horn table over triple patterns: SWRL built-in atoms, same-individual and different-individual atoms, data ranges and anonymous class expressions are refused, as are RIF equality, External, Expr, `rif:local` constants, list terms, Or/Neg/Naf, an existential conclusion and an Atom of arity 0 or 3+. Every refusal is NAMED AND COUNTED and by default fails the whole import with no table written, because a rule set that quietly lost half its rules still reaches a fixpoint and still produces a certificate that checks green. `allow_partial: true` imports the rest and flags `certifies_a_weaker_rule_set`. A table from this tool can only ever earn `entailed_under_supplied_rules` |diff --git a/docs/ci-gates.md b/docs/ci-gates.mdindex 149ff29a..ad6e7d39 100644--- a/docs/ci-gates.md+++ b/docs/ci-gates.md@@ -69,6 +69,7 @@ job invokes the file at all.| `lean_refutation_producer_test.rs` | lake + `oo-refute` | `lean` job | **strict** || `lean_mixed_certificate_test.rs` | lake | `lean` job | **strict** || `lean_horn_certificate_test.rs` | lake | `lean` job | **strict** |+| `trace_label_test.rs` | lake + `oo-cert` + `oo-horn` | `lean` job | **strict** || `readme_example_test.rs` | lake | `lean` job | **strict** || `demo_asset_claims_test.rs` | lake | `lean` job | **strict** || `lean_fol_model_test.rs` | lake + `oo-folmodel` + z3 | `lean` job | **strict** |diff --git a/docs/tool-reference.md b/docs/tool-reference.mdindex 128d72d2..91204a42 100644--- a/docs/tool-reference.md+++ b/docs/tool-reference.md@@ -74,7 +74,7 @@ it withheld.## Every tool-121 tools.+122 tools.| Tool | What it does || --- | --- |@@ -192,6 +192,7 @@ it withheld.| `onto_temporal_conflicts` | Disjointness violations that claim OVERLAPPING validity, separated from those that do not. || `onto_temporal_query` | Run a SPARQL graph pattern against only the graphs in temporal scope: what the graph said at a given valid time, as known at a given recorded time. || `onto_temporal_snapshot` | Which named graphs are in scope at a point in time, and which are excluded and why. |+| `onto_trace_label` | Label each step of a reasoning trace against the rule table, with a machine-checked verdict per step: entailed, not_entailed, or outside_the_fragment, plus the local answer over the premises the step itself cited. || `onto_unload` | Unload an ontology from memory. || `onto_unpack` | Load a pack written by onto_pack, refusing it if the checksum does not match. || `onto_validate` | Validate RDF/OWL syntax. |diff --git a/python/README.md b/python/README.mdindex 5401a2d0..eb08626e 100644--- a/python/README.md+++ b/python/README.md@@ -226,7 +226,7 @@ report["conforms"] # None, because nothing was examined## Relationship to the Rust engine-This is the **Python layer** of the project. For the full engine (three-layer Dynamics/Causal/Planner architecture, HNSW semantic search, SHIQ tableaux reasoning, PDDL planning, governance, 121 tools), use the [Rust build](https://github.com/fabio-rovai/open-ontologies). HNSW semantic search there is a compile-time feature, so build with `--features embeddings`; the published binaries do not carry it. Same Oxigraph core; pick the weight class you need.+This is the **Python layer** of the project. For the full engine (three-layer Dynamics/Causal/Planner architecture, HNSW semantic search, SHIQ tableaux reasoning, PDDL planning, governance, 122 tools), use the [Rust build](https://github.com/fabio-rovai/open-ontologies). HNSW semantic search there is a compile-time feature, so build with `--features embeddings`; the published binaries do not carry it. Same Oxigraph core; pick the weight class you need.## Licensediff --git a/skills/ontology-engineer.md b/skills/ontology-engineer.mdindex bdef7f26..a90b13bc 100644--- a/skills/ontology-engineer.md+++ b/skills/ontology-engineer.md@@ -5,7 +5,7 @@ description: Use when building, modifying, or validating ontologies. Orchestrate# Ontology Engineer-AI-native ontology engineering using the Open Ontologies `onto_*` MCP tools (121 tools, 8 of which require an optional Cargo feature).+AI-native ontology engineering using the Open Ontologies `onto_*` MCP tools (122 tools, 8 of which require an optional Cargo feature).## When to Usediff --git a/skills/ontology-engineering/SKILL.md b/skills/ontology-engineering/SKILL.mdindex 591d4857..16d0d7a0 100644--- a/skills/ontology-engineering/SKILL.md+++ b/skills/ontology-engineering/SKILL.md@@ -5,7 +5,7 @@ description: Build, validate, and govern RDF/OWL ontologies using the Open Ontol# Ontology Engineering Workflow-You have access to the Open Ontologies MCP server, which provides 121 tools for AI-native ontology engineering backed by an in-memory Oxigraph triple store. 113 of them are advertised in a default build, and the other 8 require an optional Cargo feature and return an error without it: four need `embeddings`, two need `plugins`, and two need `postgres` or `duckdb`.+You have access to the Open Ontologies MCP server, which provides 122 tools for AI-native ontology engineering backed by an in-memory Oxigraph triple store. 114 of them are advertised in a default build, and the other 8 require an optional Cargo feature and return an error without it: four need `embeddings`, two need `plugins`, and two need `postgres` or `duckdb`.## Core Workflowdiff --git a/src/batch.rs b/src/batch.rsindex c3cdfb84..5054781c 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -134,6 +134,7 @@ impl BatchRunner {"fol-prove" | "fol_prove" => self.exec_fol_prove(&cmd.args),"preserve" => self.exec_preserve(&cmd.args),"closure-diff" | "closure_diff" => self.exec_closure_diff(&cmd.args),+ "trace-label" | "trace_label" => self.exec_trace_label(&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@@ -369,6 +370,40 @@ impl BatchRunner {serde_json::from_str(&result).unwrap_or(json!({"raw": result}))}+ /// In-process for the reason `reason --certificate` is: the store is+ /// in-memory per process, so loading and labelling have to happen in one+ /// run.+ fn exec_trace_label(&self, args: &[String]) -> Value {+ let Some(trace) = Self::flag_value(args, "--trace") else {+ return json!({"error": "trace-label requires --trace FILE (oo-trace/1)"});+ };+ let Some(out) = Self::flag_value(args, "--out") else {+ return json!({+ "error": "trace-label requires --out DIR: the per-step certificates are the \+ output, and the Lean checker is what pronounces"+ });+ };+ let text = match std::fs::read_to_string(&trace) {+ Ok(t) => t,+ Err(e) => return json!({"error": format!("cannot read {trace}: {e}")}),+ };+ let steps = match crate::trace_label::parse_trace(&text) {+ Ok(s) => s,+ Err(e) => return json!({"error": e.to_string()}),+ };+ let opts = crate::trace_label::Opts {+ profile: Self::flag_value(args, "--profile").unwrap_or_else(|| "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"),+ };+ match crate::trace_label::label_trace(&self.graph, &steps, &opts) {+ Ok(r) => serde_json::to_value(&r).unwrap_or_else(|e| json!({"error": e.to_string()})),+ Err(e) => json!({"error": e.to_string()}),+ }+ }+/// `--from swrl` with no `--file` reads the loaded graph, which is why/// this command is proxied to the daemon rather than run locally.fn exec_rules_import(&self, args: &[String]) -> Value {diff --git a/src/dlp.rs b/src/dlp.rsindex 7ff579e0..e0b316d7 100644--- a/src/dlp.rs+++ b/src/dlp.rs@@ -1125,6 +1125,38 @@ impl DlpBoundary {Ok(serde_json::to_string(&report)?)}+ /// Where the NAMED triples stand against the fragment, with the whole store+ /// as context.+ ///+ /// [`check`](Self::check) classifies every triple and folds the result into+ /// a report. [`crate::trace_label`] needs the classification of the handful+ /// of triples one reasoning step cited, unfolded, so that a step can be+ /// labelled `outside_the_fragment` carrying this classifier's own+ /// `outside_because` rows rather than a second opinion written beside it.+ /// Two classifiers would be two answers to one question, and+ /// `an_unimplemented_rule_is_not_reported_as_outside_the_fragment` guards+ /// only one of them.+ ///+ /// The whole store is indexed, not just `of`: the classifier resolves+ /// restriction nodes and list chains by lookup, so a triple classified+ /// against an index of itself alone would come back `inside` for want of+ /// the nodes that put it outside.+ ///+ /// `None` at a position whose triple is not an axiom this classifier+ /// recognises, which is the same silence `check` counts under+ /// `not_classified`. The store is read and indexed ONCE, so a caller with+ /// many steps passes every premise of every step in one call rather than+ /// paying O(store) per step.+ pub fn standing_of(+ graph: &Arc<GraphStore>,+ of: &[(String, String, String)],+ ) -> anyhow::Result<Vec<Option<Classified>>> {+ let triples = graph.all_triples()?;+ let index = TripleIndex::new(&triples);+ let cl = Classifier { index: &index };+ Ok(of.iter().map(|(s, p, o)| Self::axiom(&cl, s, p, o)).collect())+ }+/// The axiom a triple states, classified, or `None` when the triple is not/// a schema axiom this tool reads.fn axiom(cl: &Classifier, s: &str, p: &str, o: &str) -> Option<Classified> {diff --git a/src/inputs.rs b/src/inputs.rsindex b81d814f..4d2e7a70 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -1269,6 +1269,34 @@ pub struct GraphProjectionEntailmentCheckInput {pub require_checker: Option<bool>,}+/// Input for `onto_trace_label`. The per-step form: the caller supplies a trace+/// that CLAIMS inference steps and each step is labelled against the rule table.+#[derive(Deserialize, JsonSchema)]+pub struct OntoTraceLabelInput {+ /// The trace as `oo-trace/1` text. Exactly one of this and `trace_file`.+ #[serde(default)]+ pub trace_tsv: Option<String>,+ /// A file holding the trace. A `derivations.tsv` written by `onto_reason`+ /// with a certificate directory is a valid input.+ #[serde(default)]+ pub trace_file: Option<String>,+ /// `rdfs`, `owl-rl` or `owl-rl-ext`. `owl-dl` is refused: the tableaux path+ /// records no rule applications, so there is nothing to label a step+ /// against.+ #[serde(default)]+ pub profile: Option<String>,+ /// A supplied Horn table. Every checked step then earns+ /// `entailed_under_supplied_rules_checked` and nothing stronger.+ #[serde(default)]+ pub rules_file: Option<String>,+ /// Where the certificates and `labels.jsonl` land.+ pub out_dir: String,+ /// Turn an absent Lean checker into an error instead of an honest unchecked+ /// label.+ #[serde(default)]+ pub require_checker: Option<bool>,+}+/// Input for `onto_closure_diff` — entailment preservation under projection,/// with no goals supplied.#[derive(Deserialize, JsonSchema)]diff --git a/src/lib.rs b/src/lib.rsindex f5c3806e..6e7f9d08 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -39,6 +39,7 @@ pub mod flora_pipeline;pub mod pack;pub mod support;pub mod temporal;+pub mod trace_label;pub mod policy;/// Certified verdicts that cannot be spelled without the evidence. Every/// module that prints a verdict word takes its vocabulary from here.diff --git a/src/main.rs b/src/main.rsindex d7f08a5d..d8adc3d7 100644--- a/src/main.rs+++ b/src/main.rs@@ -771,6 +771,38 @@ enum Commands {#[arg(long)]seed: Vec<String>,},++ /// Label each step of a reasoning trace against the rule table+ ///+ /// Three answers per step and the third is the one to read: `entailed`,+ /// `not_entailed`, and `outside_the_fragment`, which says the rule table+ /// could never have produced that conclusion however much data arrived. A+ /// trace over a SUPPLIED rule table can only ever earn+ /// `entailed_under_supplied_rules_checked`, and the report carries the+ /// digest of the table that was in force. Exits 1 when any step is not+ /// entailed, 2 when a certificate was rejected.+ TraceLabel {+ /// The trace, in `oo-trace/1`: one step per line, `rule TAB conclusion+ /// TAB premise*`, each triple three tab-separated N-Triples terms. A+ /// `derivations.tsv` from `reason --certificate` is a valid trace.+ #[arg(long)]+ trace: String,+ #[arg(long, default_value = "owl-rl")]+ profile: String,+ /// A supplied Horn table in the `rules.tsv` format `oo-horn` reads.+ #[arg(long)]+ rules: Option<String>,+ /// Where the run certificate, the per-step certificates and+ /// `labels.jsonl` land. Every file stays, so a label is reproducible.+ #[arg(long)]+ out: String,+ #[arg(long)]+ checker: Option<String>,+ /// Turn an absent Lean checker into an error instead of an honest+ /// `entailed_unchecked` label.+ #[arg(long, default_value_t = false)]+ require_checker: bool,+ },/// Full pipeline: ingest → SHACL → reasonExtend {data_path: String,@@ -1180,6 +1212,35 @@ impl Commands {}cmd("closure-diff", a)}+ Commands::TraceLabel {+ trace,+ profile,+ rules,+ out,+ checker,+ require_checker,+ } => {+ let mut a = vec![+ "--trace".into(),+ absolutize(trace),+ "--profile".into(),+ profile.clone(),+ "--out".into(),+ absolutize(out),+ ];+ if let Some(r) = rules {+ a.push("--rules".into());+ a.push(absolutize(r));+ }+ if let Some(c) = checker {+ a.push("--checker".into());+ a.push(absolutize(c));+ }+ if *require_checker {+ a.push("--require-checker".into());+ }+ cmd("trace-label", a)+ }Commands::Shacl {shapes,valid_at,@@ -3215,9 +3276,9 @@ 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+ Commands::Preserve { .. } | Commands::ClosureDiff { .. } | Commands::TraceLabel { .. } => {+ // All three 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.diff --git a/src/server.rs b/src/server.rsindex b80fed8c..b260b12a 100644--- a/src/server.rs+++ b/src/server.rs@@ -1769,6 +1769,42 @@ impl OpenOntologiesServer {}}+ #[tool(name = "onto_trace_label", description = "Label each step of a reasoning trace against the rule table, with a machine-checked verdict per step rather than a model's opinion. Supply the trace as oo-trace/1: one step per line, `rule TAB conclusion TAB premise*`, each triple three tab-separated N-Triples terms. That is the same line a derivations.tsv from onto_reason carries, so a certificate this engine wrote is itself a valid trace. THREE FAMILIES AND THE THIRD IS THE PRODUCT. `entailed`: a Lean checker accepted a certificate slice of the run that concludes the triple, so it is true in every model of the store (OOCert.certificate_sound). `not_entailed`: some rule head in the table could conclude a triple of this shape, every axiom the step cites is inside the Horn fragment, and the graph still does not support it. `outside_the_fragment`: no rule in this table could EVER derive it, and the two reasons are never merged, exactly as onto_dlp_boundary never merges them. `outside_the_fragment` means an axiom the step cites is one the Horn fragment cannot express (a disjunction in the consequent, an existential in the head, a cardinality restriction, a negation in the antecedent) and only a rewrite of the ontology helps; `no_rule_in_this_table_concludes_this_shape` means no head in the table unifies with the conclusion, decided from the table alone with no reference to any data, and a different engine would see it. TWO ANSWERS PER STEP, NEVER MERGED. `local` is a one-line certificate over the step's OWN cited premises, so a step whose reasoning is valid over triples the graph does not hold reads local=locally_sound_checked with premises_in_store=false and label=locally_sound_but_premises_not_in_the_store. That is a step reasoning from premises it invented and it is half of what a per-step labeller is for. A THIRD FIELD: `rule_claim` says whether the cited rule is what licenses the step. rule_not_in_table is reported and the step is still labelled on its conclusion, because saying not_entailed for a mistyped rule name would be a false statement about the ontology, and because an unknown rule name makes the Lean parser exit 2 (unreadable) rather than 1 (rejected). With rules_file the table is YOURS and nothing discharges it: every checked step then earns entailed_under_supplied_rules_checked under OOCert.horn_certificate_sound, true in every model of the store THAT ALSO SATISFIES your rules, the family word carries the same qualification, and the report carries rules_tsv_sha256 and conditional_on. That word is read off the theorem name the checker printed and is not chosen here, so it cannot be shortened. `not_entailed` is bounded by a table implementing 29 of OWL 2 RL's 78 rules and RDF entailment is open-world, so it is never 'false'. Every label writes a labels.jsonl record naming the exact command that reproduces it.")]+ async fn onto_trace_label(&self, Parameters(input): Parameters<OntoTraceLabelInput>) -> String {+ use crate::trace_label as tl;+ if input.trace_tsv.is_some() == input.trace_file.is_some() {+ return Self::err_json(+ "pass exactly one of trace_tsv and trace_file. A trace inline and a trace on disk \+ are the same format, and reading both would leave which one was labelled up to \+ this code rather than to you",+ );+ }+ let text = match (&input.trace_tsv, &input.trace_file) {+ (Some(t), _) => t.clone(),+ (_, Some(p)) => match std::fs::read_to_string(p) {+ Ok(t) => t,+ Err(e) => return Self::err_json(format!("cannot read {p}: {e}")),+ },+ _ => unreachable!("the exclusivity check above covers both-absent"),+ };+ let steps = match tl::parse_trace(&text) {+ Ok(s) => s,+ Err(e) => return Self::err_json(e.to_string()),+ };+ let opts = tl::Opts {+ profile: input.profile.unwrap_or_else(|| "owl-rl".to_string()),+ rules: input.rules_file.map(std::path::PathBuf::from),+ work_dir: std::path::PathBuf::from(&input.out_dir),+ checker: None,+ require_checker: input.require_checker.unwrap_or(false),+ };+ match tl::label_trace(&self.graph, &steps, &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_module_extract", description = "A MODULE over a signature, not a slice: the smallest subset of the axioms syntactic locality can justify, such that every entailment of the WHOLE ontology over those IRIs is still an entailment of the subset. Where onto_segment_retrieve retrieves a neighbourhood and onto_closure_diff then MEASURES what it lost, this cannot lose anything over the signature, and the difference is a theorem rather than a metric: Cuenca Grau, Horrocks, Kazakov and Sattler, JAIR 31 (2008), for ⊥-locality, ⊤-locality and the iterated ⊥⊤*. THAT THEOREM IS CITED, NOT MACHINE-CHECKED: nothing under lean/ is about locality, so this names a paper and never names a Lean theorem — pass verify_out_dir to have the consequence measured instead, which reasons the ontology and the module to a fixpoint and reports every conclusion over the signature the module does not reach (which must be none). THE GUARANTEE COVERS these axiom types, each with a locality test written for it: SubClassOf, EquivalentClasses, DisjointClasses, DisjointUnion, SubPropertyOf, property chains, EquivalentProperties, DisjointProperties, domain, range, InverseProperties, the seven property characteristics (transitive, symmetric, asymmetric, reflexive, irreflexive, functional, inverse-functional), HasKey, class assertions, property assertions, negative property assertions, declarations and annotations, over class expressions built from intersection, union, complement, oneOf, someValuesFrom, allValuesFrom, hasValue, hasSelf and the six cardinality forms. INCLUDED CONSERVATIVELY, with no locality test, because no replacement can make them tautologies: owl:sameAs, owl:differentFrom, owl:AllDifferent, every unrecognised predicate in the RDF/RDFS/OWL/XSD namespaces, every blank-node structure whose shape is not one of the above, and every malformed rdf:List. Those are COUNTED AND NAMED in the report, so a module that is small and a module that was unreadable cannot look the same. Datatypes are never treated as class names, because replacing xsd:integer by ⊥ would make ∃hasAge.xsd:integer look local and drop the axiom. TWO PLACES WHERE OWL 2 AND THIS ENGINE'S RULE TABLE DISAGREE, both resolved towards the rule table: a declaration (X rdf:type owl:Class) is logically vacuous in OWL 2 and is a PREMISE of OWL 2 RL's scm-cls, and X rdf:type owl:Thing is a tautology in OWL 2 that the rule table does not regenerate, so both are kept whenever the term is in the signature. Annotation assertions (rdfs:label, rdfs:comment and the rest) are NOT in the logical module; the vacuity is checked rather than assumed, so an annotation predicate the ontology gives a domain, range, superproperty or equivalent is kept as a property assertion instead, and annotation_predicates_treated_as_vacuous lists what was dropped. Pass include_annotations to carry the labels along for reading; the logical module is the same either way.")]async fn onto_module_extract(&self, Parameters(input): Parameters<OntoModuleExtractInput>) -> String {use crate::module_extract as me;diff --git a/src/toolfilter.rs b/src/toolfilter.rsindex bef61a8f..87e4545b 100644--- a/src/toolfilter.rs+++ b/src/toolfilter.rs@@ -302,7 +302,8 @@ const PROFILES: &[(&str, &str, &[&str])] = &[DL tableaux, model finding.",&["onto_reason", "onto_reason_incremental", "onto_rules_import", "onto_defects",- "onto_dlp_boundary", "onto_justify", "onto_provenance", "onto_classify_el",+ "onto_dlp_boundary", "onto_trace_label", "onto_justify", "onto_provenance",+ "onto_classify_el","onto_dl_check", "onto_dl_explain", "onto_fol_export", "onto_fol_model","onto_fol_prove", "onto_closure_diff", "onto_module_extract","graph_projection_entailment_check", "graph_projection_lossy_check", "onto_extend",diff --git a/src/trace_label.rs b/src/trace_label.rsnew file mode 100644index 00000000..70c34d9a--- /dev/null+++ b/src/trace_label.rs@@ -0,0 +1,1365 @@+//! Does each step of a reasoning trace follow, and if not, which kind of not?+//!+//! `src/dlp.rs` asks which of an ontology's axioms the rule table can see.+//! This asks the same question one step at a time about a trace that CLAIMS+//! inference steps, and it returns the answer `dlp.rs` taught: a certificate is+//! a sound proof about the axioms the rules read and says nothing at all about+//! the ones no rule fires on. So a step that does not check has two very+//! different failures behind it and they are fixed in two different places.+//!+//! # The three families, and why the third is the point+//!+//! * `entailed`. The store entails the conclusion. Under which warrant is a+//! separate field, because `OOCert.certificate_sound` and+//! `OOCert.horn_certificate_sound` are different sentences, and the second+//! gets its own family word rather than being folded into the first.+//! * `not_entailed`. Some rule in the table has a head that could conclude a+//! triple of this shape, every axiom the step cites is inside the fragment,+//! and this graph still does not support it. The bogus step.+//! * `outside_the_fragment`. Nothing this table does could ever produce this+//! conclusion. Two separate reasons, kept apart exactly as `src/dlp.rs` keeps+//! its two dimensions apart, because merging them destroys the only+//! information a reader can act on: `outside_the_fragment` is a rewrite of+//! the ontology and `no_rule_in_this_table_concludes_this_shape` is a patch+//! to `src/reason.rs`.+//!+//! Collapsing the second and the third is how a labeller becomes useless. A+//! step that fails because the ontology says nothing and a step that fails+//! because the rule table is blind to the axiom that would license it are+//! opposite findings, and a dataset that labels both `unsound` teaches a model+//! that the fragment boundary is a reasoning error.+//!+//! The fragment question is asked FIRST, before the empty-head-list one. The+//! fragment is a fact about the LANGUAGE and would hold of a perfect OWL 2 RL+//! engine; an empty head list is a fact about the table this build ships. A+//! reader told to patch `src/reason.rs` for an axiom no Horn rule could ever+//! express has been sent to the wrong place.+//!+//! # Two answers per step, and neither is reported as the other+//!+//! A step can be LOCALLY sound, meaning the premises it cited entail the+//! conclusion it claimed, while the graph does not hold those premises at all.+//! That is a step reasoning from premises it invented. Both answers are+//! carried:+//!+//! * `local` is the one-line certificate over the step's OWN cited premises.+//! `OOCert.certificate_sound` there reads: the conclusion is true in every+//! model of the triples this step cited.+//! * `label` and `family` are about the STORE, decided over the run+//! certificate's own files.+//! * `premises_in_store` and `premises_not_in_store` say whether the graph+//! holds what the step read.+//!+//! The store question decides the headline, so family `entailed` can never be+//! claimed on the strength of premises the graph does not hold. The+//! invented-premise step gets its own label,+//! `locally_sound_but_premises_not_in_the_store`, inside the `not_entailed`+//! family, because that is the actionable finding and `not_entailed` alone+//! would throw away the fact that the step's own reasoning was valid.+//!+//! # The constraint this module inherits and cannot escape+//!+//! `docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md` and+//! `lean/HMain.lean` say the same thing: a certificate over a USER-SUPPLIED+//! rule table is reported as `entailed_under_supplied_rules`, never as+//! `entailed`, with a digest of the table that was in force. A labeller that+//! printed the absolute word for a step licensed by a rule the user wrote would+//! be assurance laundering with a per-step interface, which is worse than the+//! whole-run version because it produces training labels.+//!+//! So the word is not chosen here. It is a function of the theorem name the+//! CHECKER printed into its own stdout, read back through+//! [`crate::verdict::Certified::theorem`], and [`warrant_of_theorem`] is the+//! whole of that function. A step checked by `oo-horn` over a table that is not+//! the built-in one can reach `entailed_under_supplied_rules_checked` and+//! nothing else, and every report over a supplied table carries+//! `rules_tsv_sha256` and `conditional_on`.+//!+//! The one case where a supplied table earns the absolute word is the case+//! `oo-horn` itself announces: a table byte-identical to the built-in one makes+//! the checker print `OOCert.entails_of_builtin_horn`, which+//! `tests/reason_horn_emit_test.rs` already pins. Reading the word off the+//! checker is what makes that correct rather than a hole.+//!+//! # What a label does NOT say+//!+//! `not_entailed` is bounded by the rule table. The engine evaluates 29 of OWL+//! 2 RL's 78 rules (`reason::RULES_EVALUATED`, counted by+//! `tests/dlp_boundary_test.rs`), and RDF entailment is open-world, so+//! `not_entailed` means "not derivable under this table" and never "false".++use crate::graph::GraphStore;+use crate::projection_entailment::{+ CertKind, CertificateIndex, CheckerStatus, Membership, Spelled, run_checker,+};+use crate::reason::{+ AtomPat, BUILTIN_RULES, CHAINED_RULES, InferenceTarget, Kw, Pat, Reasoner, RulePattern, Slot,+};+use crate::verdict::Certified;+use serde::Serialize;+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::sync::Arc;++/// `rdf:rest`, in the N-Triples spelling the store uses. The marker that a+/// step's premises carry the RDF list a chained rule reads: a one-element list+/// is `rdf:first` plus `rdf:rest rdf:nil`, so every list of every length has+/// one.+const RDF_REST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#rest>";++// ─────────────────────────────────────────────────────────────────────────────+// The trace format+// ─────────────────────────────────────────────────────────────────────────────++/// One claimed inference step.+///+/// The format is `oo-trace/1` and it is one line per step:+///+/// ```text+/// rule TAB cs TAB cp TAB co TAB (ps TAB pp TAB po)*+/// ```+///+/// That is byte-identical to a line of `derivations.tsv` as `src/reason.rs`+/// writes it, and the reuse is the whole justification for the format. Three+/// things follow from it that a format invented here would not have given. The+/// output of `reason --certificate` is a valid trace, so the labeller has a+/// self-check with no fixture: every step of a trace the engine itself emitted+/// must land in an entailed family. The Lean parser `OOCert.Parse.parseSteps`+/// already reads it, so the one-step certificate this module writes needs no+/// new grammar in `lean/`. And `crate::boundary_core::push_triple_fields_bytes`+/// is already the one function that writes such a field, so nothing here+/// escapes a separator.+///+/// The rule field MAY be empty, which means no rule was claimed. An empty field+/// is unambiguous: `reason::parse_rules` refuses an empty rule name and no row+/// of `BUILTIN_RULES` has one.+///+/// Premises are triples and an IRI alone is REFUSED. A premise of a rule in+/// this engine is a triple, and accepting a bare IRI would mean guessing which+/// triple the trace meant. The refusal names the line.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+pub struct TraceStep {+ /// Empty when the trace claimed no rule.+ pub rule_claimed: String,+ pub conclusion: Spelled,+ pub premises: Vec<Spelled>,+}++/// Read `oo-trace/1`. Malformed input is an error naming the line, never a+/// guess, for the reason `reason::parse_rules` gives: a step half-read still+/// produces a label, and a label nobody wrote is worse than no label.+pub fn parse_trace(text: &str) -> anyhow::Result<Vec<TraceStep>> {+ let mut out = Vec::new();+ for (i, line) in text.split('\n').enumerate() {+ let n = i + 1;+ if line.is_empty() {+ continue;+ }+ if line.contains('\r') {+ anyhow::bail!(+ "trace line {n} contains a carriage return. The format is tab separated with LF \+ endings, and a CR would become part of a term; convert the file rather than have \+ it stripped silently"+ );+ }+ let f: Vec<&str> = line.split('\t').collect();+ // One rule field then 3(1+k) term fields, k >= 0. A conclusion with no+ // premise is legal: a trace may claim a step that reads nothing, and+ // saying so is more useful than refusing to read the line.+ if f.len() < 4 || !(f.len() - 1).is_multiple_of(3) {+ anyhow::bail!(+ "trace line {n} has {} tab-separated field(s). A step is one rule field then a \+ conclusion and each premise as three fields, so the count after the rule must be \+ a positive multiple of three. A premise given as a bare IRI is refused rather \+ than guessed at: a premise of a rule in this engine is a triple",+ f.len()+ );+ }+ let terms: Vec<Spelled> = f[1..]+ .chunks(3)+ .map(|c| (c[0].to_string(), c[1].to_string(), c[2].to_string()))+ .collect();+ for t in &terms {+ for term in [&t.0, &t.1, &t.2] {+ if !crate::boundary_core::term_fits_the_format(term.as_bytes()) {+ anyhow::bail!(+ "trace line {n}: {term:?} is not a term in the certificate format. A term \+ must be non-empty and carry no tab, newline or carriage return, and must \+ be N-Triples: <iri>, _:blank, or a quoted literal. The store spells \+ every term that way, so anything else could not match a triple it holds"+ );+ }+ }+ }+ out.push(TraceStep {+ rule_claimed: f[0].to_string(),+ conclusion: terms[0].clone(),+ premises: terms[1..].to_vec(),+ });+ }+ if out.is_empty() {+ anyhow::bail!("the trace holds no steps, so there is nothing to label");+ }+ Ok(out)+}++// ─────────────────────────────────────────────────────────────────────────────+// The warrant, which is read off the checker and never chosen here+// ─────────────────────────────────────────────────────────────────────────────++/// Which of the two sentences a theorem name stands for.+///+/// Split out as a pure function over `&str` for one reason and it is a testing+/// reason: `Certified` has no public constructor, so a test cannot build one to+/// exercise the mapping. It can exercise this, and this is the only place the+/// word is decided.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Warrant {+ /// True in every model of the premises. `OOCert.certificate_sound`, and+ /// `OOCert.entails_of_builtin_horn`, which `lean/HMain.lean` prints when+ /// the table it was handed is byte-identical to the built-in one.+ Absolute,+ /// True in every model of the premises THAT ALSO SATISFIES the supplied+ /// rules. `OOCert.horn_certificate_sound`. Never shortened.+ UnderSuppliedRules,+}++/// `None` for any other name, and that is the refusal that matters: a renamed+/// or weakened theorem must not keep the label this module was written against.+/// `CheckerRun::accepted_naming` already refuses a theorem outside the list it+/// is given, so this is the second gate and not the only one.+pub fn warrant_of_theorem(theorem: &str) -> Option<Warrant> {+ match theorem {+ "OOCert.certificate_sound" | "OOCert.entails_of_builtin_horn" => Some(Warrant::Absolute),+ "OOCert.horn_certificate_sound" => Some(Warrant::UnderSuppliedRules),+ _ => None,+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// The labels+// ─────────────────────────────────────────────────────────────────────────────++/// The label of one step, about the STORE.+///+/// The certified variants carry a [`Certified`], which has no public+/// constructor, so none of them can be named on a path that did not run a Lean+/// checker and read a zero exit code.+///+/// `Deserialize` is deliberately not implemented, exactly as for+/// `projection_entailment::GoalVerdict`: reading `"entailed_checked"` out of+/// somebody else's JSON is not the same act as earning it.+///+/// ```compile_fail+/// use open_ontologies::trace_label::StepLabel;+/// use open_ontologies::verdict::Certified;+/// let l = StepLabel::EntailedChecked(Certified {+/// theorem: "OOCert.certificate_sound",+/// subject: [0u8; 32],+/// });+/// ```+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum StepLabel {+ /// A Lean checker accepted a certificate slice of the RUN that concludes+ /// this triple, and the theorem it named is the absolute one.+ EntailedChecked(Certified),+ /// The same acceptance, and the theorem the checker named is the+ /// relativised one, because the run evaluated a SUPPLIED table. True in+ /// every model of the store that also satisfies those rules. Never+ /// shortened.+ EntailedUnderSuppliedRulesChecked(Certified),+ /// The conclusion is literally in the store. A lookup by exact-string+ /// membership in `asserted.tsv`, not a theorem, and it does not pretend to+ /// be one. Absolute whatever table was in force, because no rule was+ /// involved.+ AssertedNotDerived,+ /// The ENGINE derived it under the built-in table and no checker looked,+ /// because none was built.+ EntailedUnchecked,+ /// The ENGINE derived it under a SUPPLIED table and no checker looked. A+ /// separate variant from the one above and not a flag on it, so the family+ /// word cannot lose the qualification on a path where nothing was checked.+ EntailedUnderSuppliedRulesUnchecked,+ /// The store does not hold the conclusion, and a checker accepted the+ /// step's own premises as entailing it. The step's reasoning was valid and+ /// its premises were invented. Both halves are in the report:+ /// `local` carries the acceptance and `premises_not_in_store` names the+ /// triples the graph does not hold.+ LocallySoundButPremisesNotInTheStore(Certified),+ /// The closure does not hold it, some rule head could conclude a triple of+ /// this shape, and every axiom the step cites is inside the fragment.+ NotEntailedUnderThisTable,+ /// An axiom the step cites is one `src/dlp.rs` classifies `outside` or+ /// `partially_inside`. Dimension one: a fact about the LANGUAGE that would+ /// hold of a perfect OWL 2 RL engine, and only a rewrite of the ontology+ /// helps.+ OutsideTheFragment,+ /// No head in the table can unify with the conclusion, so no data could+ /// ever make this table derive it. Dimension two: a fact about THIS+ /// ENGINE's table, and a different table would see it.+ NoRuleInThisTableConcludesThisShape,+ /// The checker REJECTED a certificate slice of the run. A defect in the+ /// emitter or in this module, never a downgrade to an unchecked label.+ CertificateRejected,+}++impl StepLabel {+ pub fn word(&self) -> &'static str {+ match self {+ StepLabel::EntailedChecked(_) => "entailed_checked",+ StepLabel::EntailedUnderSuppliedRulesChecked(_) => {+ "entailed_under_supplied_rules_checked"+ }+ StepLabel::AssertedNotDerived => "asserted_not_derived",+ StepLabel::EntailedUnchecked => "entailed_unchecked",+ StepLabel::EntailedUnderSuppliedRulesUnchecked => {+ "entailed_under_supplied_rules_unchecked"+ }+ StepLabel::LocallySoundButPremisesNotInTheStore(_) => {+ "locally_sound_but_premises_not_in_the_store"+ }+ StepLabel::NotEntailedUnderThisTable => "not_entailed_under_this_table",+ StepLabel::OutsideTheFragment => "outside_the_fragment",+ StepLabel::NoRuleInThisTableConcludesThisShape => {+ "no_rule_in_this_table_concludes_this_shape"+ }+ StepLabel::CertificateRejected => "certificate_rejected",+ }+ }++ /// The headline answer, for a consumer that wants the grouping. The words+ /// come from the labels and the labels are never reconstructed from these.+ ///+ /// Three families, and the first has two spellings because the hard rule+ /// forbids one. A step whose warrant came from a SUPPLIED table reads+ /// `entailed_under_supplied_rules` here, never the bare word, so a consumer+ /// that filters on `family == "entailed"` cannot collect a conclusion that+ /// holds only in models satisfying rules nobody checked. Use+ /// [`is_entailed_family`](Self::is_entailed_family) for the three-way+ /// grouping rather than comparing strings.+ pub fn family(&self) -> &'static str {+ match self {+ StepLabel::EntailedChecked(_)+ | StepLabel::AssertedNotDerived+ | StepLabel::EntailedUnchecked => "entailed",+ StepLabel::EntailedUnderSuppliedRulesChecked(_)+ | StepLabel::EntailedUnderSuppliedRulesUnchecked => "entailed_under_supplied_rules",+ StepLabel::NotEntailedUnderThisTable+ | StepLabel::LocallySoundButPremisesNotInTheStore(_)+ | StepLabel::CertificateRejected => "not_entailed",+ StepLabel::OutsideTheFragment | StepLabel::NoRuleInThisTableConcludesThisShape => {+ "outside_the_fragment"+ }+ }+ }++ /// Whether this is the first family, under either of its two spellings.+ pub fn is_entailed_family(&self) -> bool {+ matches!(self.family(), "entailed" | "entailed_under_supplied_rules")+ }++ /// The theorem standing behind THIS label, which is a statement about the+ /// STORE. Read out of the evidence, so a label that ran no checker cannot+ /// name one.+ ///+ /// `LocallySoundButPremisesNotInTheStore` names none, even though it carries+ /// a `Certified`. The token it carries was earned over the step's own cited+ /// premises and says nothing about the store, so putting it in the field+ /// beside a store-level label would invite exactly the reading this label+ /// exists to prevent. It is reported under `local` instead, where the+ /// sentence it discharges is written down. The payload stays on the variant+ /// because it is what makes the word `locally_sound` unconstructible without+ /// a checker acceptance.+ pub fn theorem(&self) -> Option<&'static str> {+ match self {+ StepLabel::EntailedChecked(c) | StepLabel::EntailedUnderSuppliedRulesChecked(c) => {+ Some(c.theorem())+ }+ _ => None,+ }+ }++ /// The digest of the files the accepting run was handed, so a reader can+ /// ask whether the token is about the artefact in their hand. Absent+ /// wherever [`theorem`](Self::theorem) is, and for the same reason.+ pub fn subject_sha256(&self) -> Option<String> {+ match self {+ StepLabel::EntailedChecked(c) | StepLabel::EntailedUnderSuppliedRulesChecked(c) => {+ Some(c.subject_sha256())+ }+ _ => None,+ }+ }+}++impl Serialize for StepLabel {+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ s.serialize_str(self.word())+ }+}++impl PartialEq<&str> for StepLabel {+ fn eq(&self, other: &&str) -> bool {+ self.word() == *other+ }+}++/// The answer to the LOCAL question: do the premises this step cited entail the+/// conclusion it claimed, in one application of the rule it named?+///+/// A different sentence from the label above, and never reported as it. The+/// certified variants carry a [`Certified`] for the same reason [`StepLabel`]'s+/// do.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum LocalVerdict {+ /// A checker accepted a one-line certificate whose asserted graph is this+ /// step's own cited premises. `OOCert.certificate_sound` there reads: the+ /// conclusion is true in every model of the triples this step cited.+ SoundChecked(Certified),+ /// The same over a SUPPLIED table: true in every model of the cited+ /// premises that also satisfies those rules.+ SoundUnderSuppliedRulesChecked(Certified),+ /// The checker rejected the one-line certificate. The cited rule, with the+ /// cited premises, does not produce the claimed conclusion.+ NotLicensedByTheCitedRule,+ /// Not asked. `rule_claim` says why: no rule was claimed, the name is in no+ /// table, a chained rule was cited without its list, or no binding+ /// instantiates the cited rule's body.+ NotAsked,+ /// The Lean checker was not built, so nobody looked. Never a pass.+ CheckerAbsent,+}++impl LocalVerdict {+ pub fn word(&self) -> &'static str {+ match self {+ LocalVerdict::SoundChecked(_) => "locally_sound_checked",+ LocalVerdict::SoundUnderSuppliedRulesChecked(_) => {+ "locally_sound_under_supplied_rules_checked"+ }+ LocalVerdict::NotLicensedByTheCitedRule => "not_licensed_by_the_cited_rule",+ LocalVerdict::NotAsked => "not_asked",+ LocalVerdict::CheckerAbsent => "checker_absent",+ }+ }+ pub fn theorem(&self) -> Option<&'static str> {+ match self {+ LocalVerdict::SoundChecked(c) | LocalVerdict::SoundUnderSuppliedRulesChecked(c) => {+ Some(c.theorem())+ }+ _ => None,+ }+ }+ pub fn subject_sha256(&self) -> Option<String> {+ match self {+ LocalVerdict::SoundChecked(c) | LocalVerdict::SoundUnderSuppliedRulesChecked(c) => {+ Some(c.subject_sha256())+ }+ _ => None,+ }+ }+ /// The token, where one was earned. Used to carry the acceptance into+ /// [`StepLabel::LocallySoundButPremisesNotInTheStore`] so that label names+ /// the theorem the checker actually printed.+ fn certified(&self) -> Option<Certified> {+ match self {+ LocalVerdict::SoundChecked(c) | LocalVerdict::SoundUnderSuppliedRulesChecked(c) => {+ Some(c.clone())+ }+ _ => None,+ }+ }+ pub fn is_sound(&self) -> bool {+ self.certified().is_some()+ }+}++impl Serialize for LocalVerdict {+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ s.serialize_str(self.word())+ }+}++/// Whether the RULE the trace cited is the rule that licenses the step.+///+/// Orthogonal to [`StepLabel`] and reported beside it, never folded into it. A+/// step can have a true conclusion and a wrong citation, and for a dataset that+/// is the interesting row: it labels the JUSTIFICATION as well as the+/// conclusion. Folding a bad citation into `not_entailed` would be a false+/// statement about the ontology.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum RuleClaim {+ /// The cited rule, with the cited premises, is what the checker accepted.+ Licensed,+ /// The trace claimed no rule. The step was labelled on its conclusion+ /// alone, by the store-level question.+ NoRuleClaimed,+ /// The name is in the table, and no instance of THAT rule with THOSE+ /// premises produced this conclusion. Whether the conclusion follows some+ /// other way is the label's business, not this field's.+ RuleInTableButDidNotFireHere,+ /// The name is in neither `reason::BUILTIN_RULES`, `reason::CHAINED_RULES`+ /// nor the supplied table.+ ///+ /// This is NOT a label. `OOCert.Parse.parseSteps` fails on an unknown rule+ /// name and `lean/Main.lean` exits 2 for that, which is "a file could not+ /// be parsed" and not "the step was rejected", so such a step is never+ /// handed to the checker at all: it is labelled on its conclusion by the+ /// store-level question, and the bad citation is reported here.+ RuleNotInTable,+ /// A chained rule (`cls-int1`, `cls-int2`, `cls-uni`, `cls-oo`) whose cited+ /// premises carry no `rdf:rest`, so the RDF list the rule reads is not in+ /// them. Those rules read their list off the ASSERTED graph, so a one-step+ /// certificate over incomplete premises would be rejected for a reason+ /// that is about the citation and not about the inference. Reported here+ /// rather than as a rejection.+ ChainedRulePremisesIncomplete,+ /// A supplied rule of that name exists and no binding instantiates its body+ /// with the cited premises, so there is no `horn.tsv` line to write.+ NoBindingInstantiatesTheCitedRule,+}++impl RuleClaim {+ pub fn word(self) -> &'static str {+ match self {+ RuleClaim::Licensed => "licensed",+ RuleClaim::NoRuleClaimed => "no_rule_claimed",+ RuleClaim::RuleInTableButDidNotFireHere => "rule_in_table_but_did_not_fire_here",+ RuleClaim::RuleNotInTable => "rule_not_in_table",+ RuleClaim::ChainedRulePremisesIncomplete => "chained_rule_premises_incomplete",+ RuleClaim::NoBindingInstantiatesTheCitedRule => {+ "no_binding_instantiates_the_cited_rule"+ }+ }+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// Head-shape reachability: dimension two, decided from the table alone+// ─────────────────────────────────────────────────────────────────────────────++/// Every rule in the table whose HEAD can unify with this triple.+///+/// Empty means no data whatsoever could make this table derive a triple of this+/// shape, which is a stronger and more useful statement than "this graph does+/// not support it". It is decided from the table and never from the store.+///+/// # What this measured about the built-in table, and it is not what was expected+///+/// For the BUILT-IN table the list is never empty, and that is a fact about the+/// table rather than a weakness of this function. `rdfs7`'s head is+/// `[Var, Var, Var]`: from `s p o` and `p rdfs:subPropertyOf q` it concludes+/// `s q o`, so for ANY triple there is data that makes `rdfs7` conclude it.+/// `prp-trp`, `prp-symp`, `prp-inv1`, `prp-inv2` and `cls-hv1` have+/// all-variable heads too. So dimension two is vacuous under the built-in+/// table: every `not_derivable` conclusion there is either+/// `outside_the_fragment` or `not_entailed_under_this_table`, and+/// `no_rule_in_this_table_concludes_this_shape` is reachable only for a+/// SUPPLIED table whose heads fix a predicate.+///+/// `the_builtin_head_list_is_never_empty_because_rdfs7_concludes_anything`+/// pins that, and it is pinned rather than commented because the design note+/// this module was written from claimed the opposite: that a conclusion of+/// `owl:hasKey` would come back with an empty list. It does not, and a test+/// asserting it did would have been a gate that could not fail.+///+/// Variable repetition is honoured rather than assumed away. No head in+/// `BUILTIN_RULES` repeats a slot today, so a position-wise test would agree,+/// but a user can write `?x ?p ?x` as a head and a position-wise test would+/// accept a conclusion whose subject and object differ.+pub fn rules_whose_head_can_conclude(t: &Spelled, supplied: &[RulePattern]) -> Vec<String> {+ let mut out: Vec<String> = Vec::new();+ if supplied.is_empty() {+ for r in BUILTIN_RULES {+ if head_slots_match(&r.head, t) && !out.iter().any(|n| n == r.name) {+ out.push(r.name.to_string());+ }+ }+ // The four list rules are not rows of BUILTIN_RULES because their+ // premise count is the length of an RDF list, which is data rather than+ // something the rule fixes. Every one of their heads concludes+ // an `rdf:type` triple. Read off the rule table in+ // `lean/OOCert/Rules.lean`, which `OOCert.checkStep` implements:+ // cls-int1 concludes `x rdf:type c`, cls-int2 `x rdf:type m`, cls-uni+ // `x rdf:type c`, cls-oo `m rdf:type c`. Four heads, one predicate.+ // `the_four_chained_rules_all_conclude_a_type_triple` pins this against+ // CHAINED_RULES so a fifth chained rule cannot be added without either+ // matching that shape or failing the suite.+ if t.1 == Kw::Type.iri() {+ out.extend(CHAINED_RULES.iter().map(|r| r.to_string()));+ }+ } else {+ for r in supplied {+ if pattern_head_matches(&r.head, t) && !out.iter().any(|n| n == &r.name) {+ out.push(r.name.clone());+ }+ }+ }+ out+}++fn head_slots_match(head: &[Slot; 3], t: &Spelled) -> bool {+ let terms = [&t.0, &t.1, &t.2];+ let mut bound: BTreeMap<usize, &str> = BTreeMap::new();+ for (slot, term) in head.iter().zip(terms) {+ match slot {+ Slot::Fixed(kw) => {+ if kw.iri() != term.as_str() {+ return false;+ }+ }+ Slot::Var(i) => match bound.insert(*i, term) {+ Some(prev) if prev != term.as_str() => return false,+ _ => {}+ },+ }+ }+ true+}++fn pattern_head_matches(head: &AtomPat, t: &Spelled) -> bool {+ let mut bound: BTreeMap<&str, &str> = BTreeMap::new();+ for (pat, term) in [(&head.s, &t.0), (&head.p, &t.1), (&head.o, &t.2)] {+ match pat {+ Pat::Const(c) => {+ if c != term {+ return false;+ }+ }+ Pat::Var(v) => match bound.insert(v.as_str(), term.as_str()) {+ Some(prev) if prev != term.as_str() => return false,+ _ => {}+ },+ }+ }+ true+}++// ─────────────────────────────────────────────────────────────────────────────+// The procedure+// ─────────────────────────────────────────────────────────────────────────────++#[derive(Clone, Debug)]+pub struct Opts {+ /// The profile the store-level question is decided under. `owl-dl` is+ /// refused by `Reasoner::run_scoped` because the tableaux path records no+ /// rule applications, so there is nothing to label a step against.+ pub profile: String,+ /// A SUPPLIED Horn table. Its presence changes the label word for every+ /// checked step and puts `rules_tsv_sha256` in the report.+ pub rules: Option<PathBuf>,+ /// Where the run certificate, the per-step certificates and `labels.jsonl`+ /// land. Every intermediate file stays, so a label is reproducible by hand.+ pub work_dir: PathBuf,+ pub checker: Option<PathBuf>,+ /// Turn an absent checker into an error instead of an honest+ /// `entailed_unchecked`. The CI leg sets this.+ pub require_checker: bool,+}++#[derive(Serialize)]+pub struct LabelledStep {+ pub index: usize,+ pub rule_claimed: String,+ pub conclusion: Spelled,+ pub premises: Vec<Spelled>,+ /// The STORE-level answer.+ pub label: StepLabel,+ pub family: &'static str,+ pub theorem: Option<&'static str>,+ pub subject_sha256: Option<String>,+ /// Where the conclusion stands in the run certificate: `asserted`,+ /// `derived` or `not_derivable`.+ pub conclusion_in_store: &'static str,+ /// The LOCAL answer, over the step's own cited premises. Never folded into+ /// the label: a step can be locally sound and still conclude something the+ /// store does not entail, because it read premises the store does not hold.+ pub local: LocalAnswer,+ /// Does the graph hold every triple this step cited? False is the+ /// invented-premise finding, and it is why `local` and `label` are two+ /// fields rather than one.+ pub premises_in_store: bool,+ /// Which cited premises the run certificate holds in neither `asserted.tsv`+ /// nor its conclusions. Empty when `premises_in_store` is true.+ pub premises_not_in_store: Vec<Spelled>,+ pub rule_claim: RuleClaim,+ /// The rules in the table whose head could conclude a triple of this shape.+ /// Empty is what `no_rule_in_this_table_concludes_this_shape` rests on, and+ /// under the built-in table it is never empty; see+ /// [`rules_whose_head_can_conclude`].+ pub heads_that_could_conclude_it: Vec<String>,+ /// Present only when a premise is an axiom `src/dlp.rs` puts outside the+ /// fragment, and then it carries that classifier's own `outside_because`+ /// rows rather than a summary of them.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub fragment: Option<serde_json::Value>,+ /// The command that reproduces the local certificate. A third party with+ /// the Lean binary runs it and reads the same exit code. Absent when no+ /// local certificate was written.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub reproduce: Option<String>,+}++/// The local answer and its evidence, as one object so a consumer cannot read+/// the word without the theorem beside it.+#[derive(Serialize)]+pub struct LocalAnswer {+ pub verdict: LocalVerdict,+ pub theorem: Option<&'static str>,+ pub subject_sha256: Option<String>,+ pub means: &'static str,+}++impl LocalAnswer {+ fn of(v: LocalVerdict) -> LocalAnswer {+ LocalAnswer {+ theorem: v.theorem(),+ subject_sha256: v.subject_sha256(),+ means: match &v {+ LocalVerdict::SoundChecked(_) =>+ "the conclusion is true in every model of the triples THIS STEP CITED. It \+ says nothing about whether the store holds those triples; read \+ premises_in_store for that",+ LocalVerdict::SoundUnderSuppliedRulesChecked(_) =>+ "true in every model of the CITED PREMISES that also satisfies the supplied \+ rule table. The rules are assumed and never checked. Never shorten this to \+ the plain word",+ LocalVerdict::NotLicensedByTheCitedRule =>+ "the checker rejected one application of the cited rule over the cited \+ premises. Whether the conclusion follows some other way is the label's \+ business",+ LocalVerdict::NotAsked =>+ "not asked. rule_claim says why: no rule claimed, a name in no table, a \+ chained rule cited without its list, or no binding instantiating its body",+ LocalVerdict::CheckerAbsent =>+ "the Lean checker was not built, so nobody looked. This is not a pass",+ },+ verdict: v,+ }+ }+}++#[derive(Serialize)]+pub struct TraceLabelReport {+ pub format: &'static str,+ pub profile: String,+ pub steps: Vec<LabelledStep>,+ pub by_label: BTreeMap<&'static str, usize>,+ pub by_family: BTreeMap<&'static str, usize>,+ pub by_rule_claim: BTreeMap<&'static str, usize>,+ pub by_local_verdict: BTreeMap<&'static str, usize>,+ /// The digest of the supplied table as the run evaluated it, and the+ /// sentence that travels with it. Both absent when no table was supplied.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rules_tsv_sha256: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub conditional_on: Option<String>,+ pub certificate_dir: String,+ pub dataset: String,+ pub families_mean: &'static str,+ pub bounded_by: &'static str,+ pub exit_code: i32,+}++/// Label every step of a trace.+///+/// # What a step costs, measured rather than assumed+///+/// Up to two checker processes per step: one for the local question and one for+/// the store-level question when the conclusion is derived. Measured on this+/// machine (macOS 25.6, Lean 4.33.1) over a two-premise one-derivation+/// certificate, 50 consecutive runs of `oo-cert`:+///+/// ```text+/// 2 premises, 1 derivation: 4.274 s wall / 50 runs = 85.5 ms per spawn+/// 0.09 s CPU / 50 runs = 1.8 ms per spawn+/// 200 premises, 100 derivations: 1.832 s wall / 20 runs = 91.6 ms per spawn+/// ```+///+/// So 97.9 per cent of the wall time of a small check is not CPU spent in the+/// checker at all, and a certificate a hundred times bigger costs 7 per cent+/// more. The cost is per SPAWN and not per step. A 500-step trace where every+/// step is derived spawns up to 1000 processes and would take about 85 seconds+/// here.+///+/// Batching is deliberately NOT built, and the measurement above is only half+/// the reason. The other half is that the obvious batching is UNSOUND. Each+/// per-step certificate's `asserted.tsv` is that step's own cited premises, and+/// that is the whole point of the local question; concatenating a hundred of+/// them into one certificate would let step 40 borrow step 7's premises and+/// every one of them would check green. Doing it properly means a checker that+/// takes a list of (asserted, derivations) pairs, which is a change in `lean/`+/// and a new theorem, not a loop in Rust. So the number above is what a future+/// decision should be made against, `projection_entailment` already spawns per+/// goal against the same binaries and nobody has complained, and the trace+/// lengths this has been run on are 1 to 3 steps.+pub fn label_trace(+ graph: &Arc<GraphStore>,+ trace: &[TraceStep],+ opts: &Opts,+) -> anyhow::Result<TraceLabelReport> {+ std::fs::create_dir_all(&opts.work_dir)?;+ let run_dir = opts.work_dir.join("run");++ let supplied: Vec<RulePattern> = match &opts.rules {+ Some(p) => {+ let text = std::fs::read_to_string(p)+ .map_err(|e| anyhow::anyhow!("cannot read rule table {}: {e}", p.display()))?;+ crate::reason::parse_rules(&text)?+ }+ None => Vec::new(),+ };+ let kind = if supplied.is_empty() { CertKind::OoCert } else { CertKind::OoHorn };++ // ── The store-level question, decided over the certificate FILES ─────────+ //+ // Read back off disk rather than from an in-memory closure, for the reason+ // `src/projection_entailment.rs` gives at its head: the Lean checker only+ // ever sees those files, so deciding membership against a set the checker+ // never reads would let this module report an entailed family over a+ // certificate that does not contain the derivation.+ if supplied.is_empty() {+ Reasoner::run_full(+ graph,+ &opts.profile,+ false,+ InferenceTarget::DefaultGraph,+ Some(&run_dir),+ )?;+ } else {+ let p = opts.rules.as_ref().expect("a non-empty supplied table came from a path");+ Reasoner::run_horn(graph, p, &run_dir)?;+ }+ let index = CertificateIndex::read(&run_dir)?;++ // ── Dimension one, classified ONCE over the whole store ──────────────────+ //+ // `DlpBoundary::standing_of` re-reads and re-indexes the store on every+ // call, which is O(store). Called per step it would dominate the runtime on+ // a large ontology, so every premise of every step goes in one call and the+ // answers are sliced back out by offset.+ let mut flat: Vec<Spelled> = Vec::new();+ let mut spans: Vec<(usize, usize)> = Vec::with_capacity(trace.len());+ for st in trace {+ let start = flat.len();+ flat.extend(st.premises.iter().cloned());+ spans.push((start, flat.len()));+ }+ let classified = crate::dlp::DlpBoundary::standing_of(graph, &flat)?;++ let mut steps: Vec<LabelledStep> = Vec::with_capacity(trace.len());+ for (i, st) in trace.iter().enumerate() {+ let heads = rules_whose_head_can_conclude(&st.conclusion, &supplied);+ let (lo, hi) = spans[i];+ let fragment = fragment_finding(&classified[lo..hi]);+ let step_dir = opts.work_dir.join("steps").join(format!("{i:04}"));++ // Which cited premises the store does not hold. Decided over the run+ // certificate's closure, so a premise the engine DERIVED counts as+ // held: a step citing an inference is not citing an invention.+ let premises_not_in_store: Vec<Spelled> = st+ .premises+ .iter()+ .filter(|p| index.membership(p) == Membership::NotDerivable)+ .cloned()+ .collect();+ let premises_in_store = premises_not_in_store.is_empty();++ // ── 1. THE LOCAL QUESTION ───────────────────────────────────────────+ //+ // Only asked when a rule was claimed AND the checker can parse the+ // name: an unknown name makes `oo-cert` exit 2, which is "a file could+ // not be read" and not a rejection, and reporting exit 2 as a rejected+ // step would be the wrong alarm in the wrong direction.+ let mut rule_claim = if st.rule_claimed.is_empty() {+ RuleClaim::NoRuleClaimed+ } else if !known_rule(&st.rule_claimed, &supplied) {+ RuleClaim::RuleNotInTable+ } else if supplied.is_empty() && is_chained(&st.rule_claimed) && !cites_a_list(&st.premises)+ {+ RuleClaim::ChainedRulePremisesIncomplete+ } else if !supplied.is_empty()+ && horn_index_and_binding(&st.rule_claimed, st, &supplied).is_none()+ {+ RuleClaim::NoBindingInstantiatesTheCitedRule+ } else {+ RuleClaim::Licensed+ };+ let mut local = LocalVerdict::NotAsked;+ let mut reproduce = None;+ if rule_claim == RuleClaim::Licensed {+ write_one_step_certificate(&step_dir, kind, st, &supplied)?;+ reproduce = Some(reproduce_command(kind, &step_dir));+ let rules_path = (kind == CertKind::OoHorn).then(|| step_dir.join("rules.tsv"));+ local = match run_checker(+ kind,+ opts.checker.as_deref(),+ &step_dir.join("asserted.tsv"),+ &step_dir.join(kind.derivations_file()),+ rules_path.as_deref(),+ ) {+ CheckerStatus::Accepted(a) => {+ // THE ONE PLACE A WORD IS CHOSEN, and it is chosen from the+ // theorem the CHECKER printed. `warrant_of_theorem` is the+ // whole of the rule that a supplied table cannot earn the+ // absolute word.+ let cert = a.certified();+ match warrant_of_theorem(cert.theorem()) {+ Some(Warrant::Absolute) => LocalVerdict::SoundChecked(cert),+ Some(Warrant::UnderSuppliedRules) => {+ LocalVerdict::SoundUnderSuppliedRulesChecked(cert)+ }+ // A zero exit naming a statement this module was not+ // written against earns nothing. A renamed or weakened+ // theorem must not keep this label.+ None => LocalVerdict::NotLicensedByTheCitedRule,+ }+ }+ CheckerStatus::Rejected { .. } => {+ rule_claim = RuleClaim::RuleInTableButDidNotFireHere;+ LocalVerdict::NotLicensedByTheCitedRule+ }+ CheckerStatus::Absent { what, install } => {+ if opts.require_checker {+ anyhow::bail!("{what}. {install}");+ }+ LocalVerdict::CheckerAbsent+ }+ CheckerStatus::NotNeeded { .. } => LocalVerdict::NotAsked,+ CheckerStatus::Unreadable { stdout } => {+ anyhow::bail!(+ "the checker could not read the one-step certificate this module wrote \+ for step {i}, which is a defect here and never a result about the \+ ontology: {stdout}"+ );+ }+ };+ }++ // ── 2. THE STORE-LEVEL QUESTION, which decides the headline ─────────+ //+ // Asked for every step, whatever the local answer was. A step can have+ // a conclusion the store entails some other way, so saying+ // `not_entailed` because a citation was wrong would be false; and a+ // step can be locally sound over premises the store does not hold, so+ // reporting an entailed family on the strength of the local answer+ // would be worse.+ let membership = index.membership(&st.conclusion);+ let label = match membership {+ Membership::Asserted => StepLabel::AssertedNotDerived,+ Membership::Derived => {+ let lines = index.slice_for(&st.conclusion).unwrap_or_default();+ let out = step_dir.join("store").join(kind.derivations_file());+ index.write_slice(&lines, &out)?;+ let rp = (kind == CertKind::OoHorn).then(|| index.rules_path());+ match run_checker(+ kind,+ opts.checker.as_deref(),+ &index.asserted_path(),+ &out,+ rp.as_deref(),+ ) {+ CheckerStatus::Accepted(a) => {+ let cert = a.certified();+ match warrant_of_theorem(cert.theorem()) {+ Some(Warrant::Absolute) => StepLabel::EntailedChecked(cert),+ Some(Warrant::UnderSuppliedRules) => {+ StepLabel::EntailedUnderSuppliedRulesChecked(cert)+ }+ None => StepLabel::CertificateRejected,+ }+ }+ CheckerStatus::Rejected { .. } => StepLabel::CertificateRejected,+ CheckerStatus::Absent { what, install } => {+ if opts.require_checker {+ anyhow::bail!("{what}. {install}");+ }+ unchecked_label(kind)+ }+ CheckerStatus::NotNeeded { .. } | CheckerStatus::Unreadable { .. } => {+ unchecked_label(kind)+ }+ }+ }+ // ── 3. THE THIRD ANSWER, and the reasons are kept apart ──────────+ Membership::NotDerivable => {+ match local.certified() {+ // The invented-premise step, and it goes first because it+ // explains the whole failure: the step's own reasoning was+ // machine-checked sound and the graph does not hold what it+ // read. Neither fragment answer would tell the reader that.+ Some(c) if !premises_in_store => {+ StepLabel::LocallySoundButPremisesNotInTheStore(c)+ }+ // The fragment is asked before the head list because it is+ // the LANGUAGE fact: it would hold of a perfect OWL 2 RL+ // engine, while an empty head list is a fact about the+ // table this build ships and a different table would change+ // it. `src/dlp.rs`'s module header draws exactly that+ // order, and a reader who gets the table answer for an+ // axiom no Horn rule could ever express would go patching+ // `src/reason.rs` for nothing.+ _ if fragment.is_some() => StepLabel::OutsideTheFragment,+ _ if heads.is_empty() => StepLabel::NoRuleInThisTableConcludesThisShape,+ _ => StepLabel::NotEntailedUnderThisTable,+ }+ }+ };++ steps.push(LabelledStep {+ index: i,+ rule_claimed: st.rule_claimed.clone(),+ conclusion: st.conclusion.clone(),+ premises: st.premises.clone(),+ theorem: label.theorem(),+ subject_sha256: label.subject_sha256(),+ family: label.family(),+ conclusion_in_store: membership_word(membership),+ local: LocalAnswer::of(local),+ premises_in_store,+ premises_not_in_store,+ rule_claim,+ heads_that_could_conclude_it: heads,+ fragment,+ reproduce,+ label,+ });+ }++ build_report(steps, opts, &supplied, &index)+}++fn unchecked_label(kind: CertKind) -> StepLabel {+ match kind {+ CertKind::OoCert => StepLabel::EntailedUnchecked,+ CertKind::OoHorn => StepLabel::EntailedUnderSuppliedRulesUnchecked,+ }+}++fn membership_word(m: Membership) -> &'static str {+ match m {+ Membership::Asserted => "asserted",+ Membership::Derived => "derived",+ Membership::NotDerivable => "not_derivable",+ }+}++/// `asserted.tsv` is the step's OWN premises and the derivation file is the one+/// step. So `OOCert.certificate_sound` reads: the conclusion is true in every+/// model of the triples this step cited. That is local soundness, and it is a+/// different sentence from "the store entails the conclusion", which is why+/// both are asked and neither is reported as the other.+fn write_one_step_certificate(+ dir: &Path,+ kind: CertKind,+ st: &TraceStep,+ supplied: &[RulePattern],+) -> anyhow::Result<()> {+ std::fs::create_dir_all(dir)?;+ let mut asserted: Vec<u8> = Vec::new();+ for p in &st.premises {+ crate::boundary_core::push_asserted_line_bytes(+ &mut asserted,+ p.0.as_bytes(),+ p.1.as_bytes(),+ p.2.as_bytes(),+ )+ .map_err(|pos| anyhow::anyhow!("a premise term does not fit the format at {pos:?}"))?;+ }+ std::fs::write(dir.join("asserted.tsv"), asserted)?;+ let mut line: Vec<u8> = Vec::new();+ match kind {+ CertKind::OoCert => line.extend_from_slice(st.rule_claimed.as_bytes()),+ CertKind::OoHorn => {+ // `oo-horn` cites a rule by INDEX into the table and carries the+ // binding in full, because `OOCert.checkHornStep` demands a binding+ // that instantiates the body. The binding is recovered by matching+ // the cited premises against the rule's body in order; a step whose+ // premises do not instantiate the body has no binding to write and+ // is `no_binding_instantiates_the_cited_rule` before this is+ // reached.+ let (ri, binds) = horn_index_and_binding(&st.rule_claimed, st, supplied)+ .ok_or_else(|| anyhow::anyhow!("no binding instantiates the cited rule's body"))?;+ std::fs::write(dir.join("rules.tsv"), crate::reason::rules_tsv(supplied))?;+ line.extend_from_slice(ri.to_string().as_bytes());+ line.push(b'\t');+ line.extend_from_slice(binds.len().to_string().as_bytes());+ for (v, term) in &binds {+ if !crate::boundary_core::field_fits_the_format(v.as_bytes()) {+ anyhow::bail!(+ "internal: the rule variable name {v:?} does not fit the certificate \+ format, so no certificate was written"+ );+ }+ line.push(b'\t');+ line.extend_from_slice(v.as_bytes());+ line.push(b'\t');+ line.extend_from_slice(term.as_bytes());+ }+ }+ }+ for t in std::iter::once(&st.conclusion).chain(st.premises.iter()) {+ crate::boundary_core::push_triple_fields_bytes(+ &mut line,+ t.0.as_bytes(),+ t.1.as_bytes(),+ t.2.as_bytes(),+ )+ .map_err(|pos| anyhow::anyhow!("a step term does not fit the format at {pos:?}"))?;+ }+ line.push(b'\n');+ std::fs::write(dir.join(kind.derivations_file()), line)?;+ Ok(())+}++/// The index of a supplied rule of this name whose body the cited premises+/// instantiate, and the binding, in the variable order+/// `Reasoner::run_horn_scoped` uses: first occurrence over body then head. The+/// order matters because a certificate this module writes and a certificate the+/// engine writes must be the same file for the same step.+fn horn_index_and_binding(+ name: &str,+ st: &TraceStep,+ supplied: &[RulePattern],+) -> Option<(usize, Vec<(String, String)>)> {+ for (ri, r) in supplied.iter().enumerate() {+ if r.name != name || r.body.len() != st.premises.len() {+ continue;+ }+ let mut bound: BTreeMap<&str, &str> = BTreeMap::new();+ let mut ok = true;+ for (atom, prem) in r.body.iter().zip(st.premises.iter()) {+ if !unify_atom(atom, prem, &mut bound) {+ ok = false;+ break;+ }+ }+ if !ok || !unify_atom(&r.head, &st.conclusion, &mut bound) {+ continue;+ }+ // First-occurrence order over body then head, which is exactly what+ // `run_horn_scoped` builds its `vars` vector from.+ let mut order: Vec<&str> = Vec::new();+ for a in r.body.iter().chain(std::iter::once(&r.head)) {+ for p in [&a.s, &a.p, &a.o] {+ if let Pat::Var(v) = p+ && !order.contains(&v.as_str())+ {+ order.push(v.as_str());+ }+ }+ }+ let binds: Vec<(String, String)> = order+ .iter()+ .filter_map(|v| bound.get(*v).map(|t| ((*v).to_string(), (*t).to_string())))+ .collect();+ if binds.len() != order.len() {+ // `parse_rules` refuses a head variable absent from the body, so+ // this cannot happen for a table it accepted. If it ever does, the+ // step gets no certificate rather than a half-written one.+ continue;+ }+ return Some((ri, binds));+ }+ None+}++fn unify_atom<'a>(a: &'a AtomPat, t: &'a Spelled, bound: &mut BTreeMap<&'a str, &'a str>) -> bool {+ for (pat, term) in [(&a.s, &t.0), (&a.p, &t.1), (&a.o, &t.2)] {+ match pat {+ Pat::Const(c) => {+ if c != term {+ return false;+ }+ }+ Pat::Var(v) => match bound.insert(v.as_str(), term.as_str()) {+ Some(prev) if prev != term.as_str() => return false,+ _ => {}+ },+ }+ }+ true+}++/// Dimension one, asked of the axioms this step CITED rather than of the whole+/// ontology, because a step is labelled on its own premises. `None` when every+/// cited premise this classifier recognises is inside the fragment, which+/// includes the case where it recognises none of them.+fn fragment_finding(classified: &[Option<crate::dlp::Classified>]) -> Option<serde_json::Value> {+ let mut rows: Vec<serde_json::Value> = Vec::new();+ for c in classified.iter().flatten() {+ if c.standing != crate::dlp::Standing::Inside {+ rows.push(serde_json::json!({+ "axiom_type": c.kind,+ "subject": c.subject,+ "object": c.object,+ "standing": c.standing.word(),+ "outside_because": c.excluded,+ "horn_but_outside_owl2_rl": c.horn_but_outside_owl2_rl,+ }));+ }+ }+ (!rows.is_empty()).then(|| serde_json::json!({ "premises_outside_the_fragment": rows }))+}++fn known_rule(name: &str, supplied: &[RulePattern]) -> bool {+ if !supplied.is_empty() {+ return supplied.iter().any(|r| r.name == name);+ }+ BUILTIN_RULES.iter().any(|r| r.name == name) || CHAINED_RULES.contains(&name)+}++fn is_chained(name: &str) -> bool {+ CHAINED_RULES.contains(&name)+}++/// A chained rule reads an RDF list, so its premises must carry the chain.+fn cites_a_list(premises: &[Spelled]) -> bool {+ premises.iter().any(|p| p.1 == RDF_REST)+}++fn reproduce_command(kind: CertKind, dir: &Path) -> String {+ let d = dir.display();+ match kind {+ CertKind::OoCert => {+ format!("cd lean && lake exe oo-cert {d}/asserted.tsv {d}/derivations.tsv")+ }+ CertKind::OoHorn => {+ format!("cd lean && lake exe oo-horn check {d}/rules.tsv {d}/asserted.tsv {d}/horn.tsv")+ }+ }+}++fn sha256_hex(bytes: &[u8]) -> String {+ use sha2::{Digest, Sha256};+ format!("{:x}", Sha256::digest(bytes))+}++const FAMILIES_MEAN: &str =+ "three families. `entailed` and `entailed_under_supplied_rules` are the same family under two \+ different warrants and the second is NEVER shortened to the first, because a conclusion that \+ holds only in models satisfying rules nobody checked is not entailed. `not_entailed` means \+ not derivable under this table. `outside_the_fragment` means no data could make this table \+ derive it, and its two labels are fixed in two different places: outside_the_fragment is a \+ rewrite of the ontology, no_rule_in_this_table_concludes_this_shape is a patch to \+ src/reason.rs";++const BOUNDED_BY: &str =+ "this engine evaluates 29 of OWL 2 RL's 78 rules and RDF entailment is open-world, so \+ not_entailed means NOT DERIVABLE UNDER THIS TABLE and never false";++fn build_report(+ steps: Vec<LabelledStep>,+ opts: &Opts,+ supplied: &[RulePattern],+ index: &CertificateIndex,+) -> anyhow::Result<TraceLabelReport> {+ let mut by_label: BTreeMap<&'static str, usize> = BTreeMap::new();+ let mut by_family: BTreeMap<&'static str, usize> = BTreeMap::new();+ let mut by_rule_claim: BTreeMap<&'static str, usize> = BTreeMap::new();+ let mut by_local_verdict: BTreeMap<&'static str, usize> = BTreeMap::new();+ for s in &steps {+ *by_label.entry(s.label.word()).or_default() += 1;+ *by_family.entry(s.family).or_default() += 1;+ *by_rule_claim.entry(s.rule_claim.word()).or_default() += 1;+ *by_local_verdict.entry(s.local.verdict.word()).or_default() += 1;+ }+ // 2 when a certificate this module or the emitter assembled was REJECTED,+ // because that is a defect here and not a finding about the trace. 1 when+ // any step is outside an entailed family, which is the ordinary finding. 0+ // when every step's conclusion is entailed by the store.+ let exit_code = if steps.iter().any(|s| s.label == "certificate_rejected") {+ 2+ } else if steps.iter().all(|s| s.label.is_entailed_family()) {+ 0+ } else {+ 1+ };+ let (rules_tsv_sha256, conditional_on) = match &opts.rules {+ Some(p) => (+ Some(sha256_hex(crate::reason::rules_tsv(supplied).as_bytes())),+ Some(format!(+ "the rules in {}, which this run ASSUMED and never checked. A rule saying every \+ supplier is compliant produces steps that check green for ever",+ p.display()+ )),+ ),+ None => (None, None),+ };+ let report = TraceLabelReport {+ format: "oo-trace-label/1",+ profile: opts.profile.clone(),+ steps,+ by_label,+ by_family,+ by_rule_claim,+ by_local_verdict,+ rules_tsv_sha256,+ conditional_on,+ certificate_dir: index.dir().display().to_string(),+ dataset: opts.work_dir.join("labels.jsonl").display().to_string(),+ families_mean: FAMILIES_MEAN,+ bounded_by: BOUNDED_BY,+ exit_code,+ };+ write_dataset(&report, opts, index)?;+ Ok(report)+}++/// One JSON object per line into `<work_dir>/labels.jsonl`, one line per step.+///+/// What makes it worth having, concretely and not as a claim: the label is not+/// a model's judgement and not this engine's opinion. It is the exit code of a+/// checker whose soundness is a machine-checked theorem, over files that ship+/// beside the record, reachable by the command in the `reproduce` field. A+/// consumer who does not trust us re-runs it. `subject_sha256` binds the token+/// to the exact bytes the accepting run was handed, computed by+/// `verdict::subject_digest` before the spawn, so a record cannot be moved onto+/// different files. And the negative labels are what a sound/unsound classifier+/// cannot get anywhere else: `outside_the_fragment` and+/// `no_rule_in_this_table_concludes_this_shape` are labelled negatives WITH A+/// REASON, which is the distinction no LLM judge produces and no benchmark of+/// entailed/not-entailed pairs contains.+fn write_dataset(+ report: &TraceLabelReport,+ opts: &Opts,+ index: &CertificateIndex,+) -> anyhow::Result<()> {+ let asserted_sha256 = std::fs::read_to_string(index.dir().join("asserted.sha256"))+ .ok()+ .map(|s| s.trim().to_string());+ let mut out = String::new();+ for s in &report.steps {+ let row = serde_json::json!({+ "format": report.format,+ "ontology_asserted_sha256": asserted_sha256,+ "profile": report.profile,+ "step": s.index,+ "rule_claimed": s.rule_claimed,+ "premises": s.premises,+ "conclusion": s.conclusion,+ "label": s.label.word(),+ "family": s.family,+ "theorem": s.theorem,+ "subject_sha256": s.subject_sha256,+ "conclusion_in_store": s.conclusion_in_store,+ "local_verdict": s.local.verdict.word(),+ "local_theorem": s.local.theorem,+ "local_subject_sha256": s.local.subject_sha256,+ "premises_in_store": s.premises_in_store,+ "premises_not_in_store": s.premises_not_in_store,+ "rule_claim": s.rule_claim.word(),+ "heads_that_could_conclude_it": s.heads_that_could_conclude_it,+ "fragment": s.fragment,+ "rules_tsv_sha256": report.rules_tsv_sha256,+ "conditional_on": report.conditional_on,+ "reproduce": s.reproduce,+ "bounded_by": report.bounded_by,+ });+ out.push_str(&serde_json::to_string(&row)?);+ out.push('\n');+ }+ std::fs::write(opts.work_dir.join("labels.jsonl"), out)?;+ Ok(())+}diff --git a/tests/fixtures/trace/boundary.ttl b/tests/fixtures/trace/boundary.ttlnew file mode 100644index 00000000..4943b673--- /dev/null+++ b/tests/fixtures/trace/boundary.ttl@@ -0,0 +1,31 @@+# Fixture for tests/trace_label_test.rs.+#+# Four things, and each one is there for one label.+#+# * `:B rdfs:subClassOf :C` with `:a a :B`. The rule table sees both, so+# `rdfs9` derives `:a a :C` and a step claiming it is entailed.+# * `:D` is absent on purpose, so a step concluding `:a a :D` is a bogus step+# with every cited axiom inside the fragment.+# * `:Adult rdfs:subClassOf [ owl:unionOf ( :Man :Woman ) ]`, the textbook+# non-Horn axiom. tests/dlp_boundary_test.rs already establishes that+# src/dlp.rs reports it outside the fragment, with the reason+# "disjunction in the consequent".+# * `:p1 :parent :p2`, which the supplied Horn table in supplied_rules.tsv+# reads. Kept here rather than in a second file so both halves of the suite+# label steps over one ontology.+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix : <http://e/> .++:B a owl:Class .+:C a owl:Class .+:B rdfs:subClassOf :C .+:a a :B .++:Adult a owl:Class ; rdfs:subClassOf [ owl:unionOf ( :Man :Woman ) ] .+:Man a owl:Class .+:Woman a owl:Class .+:s a :Adult .++:p1 :parent :p2 .diff --git a/tests/fixtures/trace/supplied_rules.tsv b/tests/fixtures/trace/supplied_rules.tsvnew file mode 100644index 00000000..825425f3--- /dev/null+++ b/tests/fixtures/trace/supplied_rules.tsv@@ -0,0 +1 @@+anc 1 ?x <http://e/parent> ?y ?x <http://e/ancestor> ?ydiff --git a/tests/readme_claims_test.rs b/tests/readme_claims_test.rsindex fdedc4b8..db2b0f64 100644--- a/tests/readme_claims_test.rs+++ b/tests/readme_claims_test.rs@@ -44,7 +44,7 @@ fn total_claims(n: usize) -> Vec<(&'static str, &'static str, String)> {//// The reasoning is the issue's: surface area reads as insecurity, and a// number where a purpose belongs tells a visitor nothing about what this is- // for. A reader who meets "121 tools" before meeting a verb cannot tell+ // for. A reader who meets a bare total before meeting a verb cannot tell// whether any of them is the one they need. The front page shows one loop// instead, and the breadth moved to docs/tool-reference.md, linked once.//diff --git a/tests/tool_reference_test.rs b/tests/tool_reference_test.rsindex 7fc65632..83cff784 100644--- a/tests/tool_reference_test.rs+++ b/tests/tool_reference_test.rs@@ -83,6 +83,19 @@ fn the_reference_states_the_right_count() {);}+/// The two totals the front page used to print, and must never print again.+///+/// Spelled in parts rather than as one literal each, and the reason is a gate+/// and not taste. `readme_claims_test::no_file_states_a_tool_count_this_build+/// _cannot_justify` scans every tracked `.md` and `.rs` for a number followed+/// by the word tools and fails on any that this build cannot justify. A test+/// file carrying `121` next to that word IS such a claim, so adding one tool to+/// the server used to break this file. The two gates are both right and they+/// are reconciled here: the record of what was retired is kept, and the shape+/// of a claim is not. `concat!` joins them at compile time, so the ban is on the+/// same bytes it always was.+const RETIRED_TOTALS: [&str; 2] = [concat!("121", " tools"), concat!("113", " tools")];+/// The repositioning itself. The front page shows the loop and not the/// catalogue, and this is what stops the catalogue creeping back.#[test]@@ -90,7 +103,7 @@ fn the_front_page_sells_the_loop_and_not_the_surface_area() {let readme = read("README.md");let fold = &readme[..readme.len().min(9000)];- for banned in ["121 tools", "113 tools", "Terraforming MCP"] {+ for banned in [RETIRED_TOTALS[0], RETIRED_TOTALS[1], "Terraforming MCP"] {assert!(!readme.contains(banned),"the README still says {banned:?}. Surface area reads as insecurity, and a \@@ -146,7 +159,7 @@ fn the_retired_words_do_not_come_back() {{let lower = t.to_lowercase();let is_catalogue = p.ends_with("tool-reference.md");- for w in ["121 tools", "113 tools", "terraforming mcp", "trustworthy"] {+ for w in [RETIRED_TOTALS[0], RETIRED_TOTALS[1], "terraforming mcp", "trustworthy"] {let counts_only = w.ends_with(" tools");if is_catalogue && counts_only {continue;diff --git a/tests/trace_label_test.rs b/tests/trace_label_test.rsnew file mode 100644index 00000000..70427421--- /dev/null+++ b/tests/trace_label_test.rs@@ -0,0 +1,733 @@+//! **A reasoning trace is labelled step by step, and the third answer is the point.**+//!+//! `src/trace_label.rs` reads a trace that CLAIMS inference steps and returns a+//! label per step. This suite is the gate on the three things that make that+//! worth having.+//!+//! 1. THE THIRD FAMILY EXISTS AND IS NOT THE SECOND. A step that fails because+//! the graph says nothing and a step that fails because the rule table is+//! blind to the axiom that would license it are opposite findings, fixed in+//! two different places. `three_labels_over_one_trace` runs all three in one+//! call and the mutation that collapses the third into the second is written+//! down beside it.+//! 2. THE LOCAL AND THE STORE ANSWER ARE TWO ANSWERS. A step can be+//! machine-checked sound over the premises it cited while the graph holds+//! none of them. `a_locally_sound_step_over_premises_the_store_lacks_is_not_entailed`+//! is that case, and it must never read as an entailed family.+//! 3. A SUPPLIED TABLE CANNOT EARN THE ABSOLUTE WORD.+//! `a_supplied_table_cannot_earn_the_absolute_word` asserts it over the+//! SERIALISED report and not over the enum, for the reason+//! `src/projection_entailment.rs` gives about its own suite: the enum is+//! where the discipline is easy and the serialisation is where it leaks.+//!+//! Every test that needs a verdict needs the Lean checker, and skips loudly+//! through `common::skip_unless` when it is not built, so a CI job that sets+//! `OO_REQUIRE_FIXTURES=1` turns the skip into a failure rather than a green run+//! over nothing.++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::{+ CHAINED_RULES, InferenceTarget, Kw, Reasoner, RulePattern, parse_rules, rules_tsv,+};+use open_ontologies::trace_label::{+ Opts, Warrant, label_trace, parse_trace, rules_whose_head_can_conclude, warrant_of_theorem,+};+use serde_json::Value;+use std::path::{Path, PathBuf};+use std::sync::Arc;++// ── Vocabulary, spelled the way the store spells it ──────────────────────────++const TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";+const SUBCLASS: &str = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";+const HAS_KEY: &str = "<http://www.w3.org/2002/07/owl#hasKey>";+const INTERSECTION_OF: &str = "<http://www.w3.org/2002/07/owl#intersectionOf>";++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn fixture(name: &str) -> PathBuf {+ repo().join("tests").join("fixtures").join("trace").join(name)+}++fn checker_path(name: &str) -> PathBuf {+ repo().join("lean").join(".lake").join("build").join("bin").join(name)+}++/// True when the caller should skip. The binaries are what pronounce, so a run+/// without them proves nothing about a label word.+fn skip_without(name: &str) -> bool {+ common::skip_unless(+ checker_path(name).exists(),+ &format!("the Lean checker {name}"),+ "build it with `cd lean && lake build` (elan from https://github.com/leanprover/elan)",+ )+}++/// A scratch directory per test, so a failure leaves its certificates behind.+fn scratch(tag: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("oo-trace-label-{tag}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).expect("create the scratch directory");+ d+}++fn store() -> Arc<GraphStore> {+ let ttl = std::fs::read_to_string(fixture("boundary.ttl")).expect("read boundary.ttl");+ let g = Arc::new(GraphStore::new());+ g.load_turtle(&ttl, None).expect("load boundary.ttl");+ g+}++fn opts(out: &Path) -> Opts {+ Opts {+ profile: "owl-rl".to_string(),+ rules: None,+ work_dir: out.to_path_buf(),+ checker: None,+ require_checker: false,+ }+}++/// A trace line, assembled the way `oo-trace/1` spells one: the rule, then the+/// conclusion, then each premise, three tab-separated N-Triples terms each.+fn line(rule: &str, conclusion: [&str; 3], premises: &[[&str; 3]]) -> String {+ let mut s = String::from(rule);+ for t in std::iter::once(&conclusion).chain(premises.iter()) {+ for term in t {+ s.push('\t');+ s.push_str(term);+ }+ }+ s.push('\n');+ s+}++/// The object of `:Adult rdfs:subClassOf _:x`, which is the restriction node+/// carrying the `owl:unionOf`.+///+/// Read out of the STORE rather than typed, because a blank node is relabelled+/// on parse and a hardcoded label would be a fixture that silently stops+/// matching anything. A step citing a triple the store does not hold is a+/// different test.+fn the_disjunctive_axiom(g: &Arc<GraphStore>) -> (String, String, String) {+ g.all_triples()+ .expect("read the store")+ .into_iter()+ .find(|(s, p, o)| s == "<http://e/Adult>" && p == SUBCLASS && o.starts_with("_:"))+ .expect("boundary.ttl states :Adult rdfs:subClassOf [ owl:unionOf ( :Man :Woman ) ]")+}++fn step_of(report: &Value, i: usize) -> &Value {+ &report["steps"][i]+}++fn as_json(report: &open_ontologies::trace_label::TraceLabelReport) -> (String, Value) {+ let text = serde_json::to_string(report).expect("the report serialises");+ let v: Value = serde_json::from_str(&text).expect("and parses back");+ (text, v)+}++// ── 1. The three families, over one trace ────────────────────────────────────++/// **Gate.** One call produces `entailed`, `not_entailed` and+/// `outside_the_fragment`, and the third is not the second.+///+/// MUTATION THAT BREAKS IT, run before landing: delete the+/// `_ if fragment.is_some()` arm of the `Membership::NotDerivable` match in+/// `label_trace`. Step (c) then comes back `not_entailed_under_this_table` and+/// this test fails on it, which is the whole point of the arm: a reader told to+/// patch `src/reason.rs` for an axiom no Horn rule could ever express has been+/// sent to the wrong place.+#[test]+fn three_labels_over_one_trace() {+ if skip_without("oo-cert") {+ return;+ }+ let g = store();+ let (ds, dp, dobj) = the_disjunctive_axiom(&g);+ let out = scratch("three");++ let mut trace = String::new();+ // (a) genuinely entailed: rdfs9 over two axioms the table reads.+ trace.push_str(&line(+ "rdfs9",+ ["<http://e/a>", TYPE, "<http://e/C>"],+ &[+ ["<http://e/a>", TYPE, "<http://e/B>"],+ ["<http://e/B>", SUBCLASS, "<http://e/C>"],+ ],+ ));+ // (b) bogus: the same premises, a conclusion nothing supports. `:D` occurs+ // nowhere in the fixture.+ trace.push_str(&line(+ "rdfs9",+ ["<http://e/a>", TYPE, "<http://e/D>"],+ &[+ ["<http://e/a>", TYPE, "<http://e/B>"],+ ["<http://e/B>", SUBCLASS, "<http://e/C>"],+ ],+ ));+ // (c) outside the fragment: the step cites the disjunctive subsumption. No+ // rule is claimed, so the label is decided on the conclusion alone and+ // the fragment finding is what separates it from (b).+ trace.push_str(&line(+ "",+ ["<http://e/s>", TYPE, "<http://e/Man>"],+ &[[&ds, &dp, &dobj], ["<http://e/s>", TYPE, "<http://e/Adult>"]],+ ));++ let steps = parse_trace(&trace).expect("the trace parses");+ let report = label_trace(&g, &steps, &opts(&out)).expect("labelling runs");+ let (text, v) = as_json(&report);++ let a = step_of(&v, 0);+ assert_eq!(a["label"], "entailed_checked", "step (a): {a}");+ assert_eq!(a["family"], "entailed", "step (a): {a}");+ assert_eq!(a["theorem"], "OOCert.certificate_sound", "step (a): {a}");+ assert_eq!(a["rule_claim"], "licensed", "step (a): {a}");+ assert_eq!(a["conclusion_in_store"], "derived", "step (a): {a}");+ assert_eq!(a["premises_in_store"], true, "step (a): {a}");+ assert_eq!(a["local"]["verdict"], "locally_sound_checked", "step (a): {a}");+ assert!(+ a["subject_sha256"].as_str().is_some_and(|s| s.len() == 64),+ "an accepted step names the digest of what the checker was handed: {a}"+ );++ let b = step_of(&v, 1);+ assert_eq!(b["family"], "not_entailed", "step (b): {b}");+ assert_eq!(b["label"], "not_entailed_under_this_table", "step (b): {b}");+ assert_eq!(b["rule_claim"], "rule_in_table_but_did_not_fire_here", "step (b): {b}");+ assert_eq!(b["local"]["verdict"], "not_licensed_by_the_cited_rule", "step (b): {b}");+ assert_eq!(b["conclusion_in_store"], "not_derivable", "step (b): {b}");+ assert!(+ b["theorem"].is_null(),+ "a step nothing checked must not name a theorem: {b}"+ );+ // The non-empty head list is exactly what separates this label from the+ // third family. Without it the reader cannot tell "this graph does not+ // support it" from "no data ever could".+ assert!(+ !b["heads_that_could_conclude_it"].as_array().expect("an array").is_empty(),+ "step (b) must have rules whose head could conclude a triple of its shape: {b}"+ );++ let c = step_of(&v, 2);+ assert_eq!(c["family"], "outside_the_fragment", "step (c): {c}");+ assert_eq!(c["label"], "outside_the_fragment", "step (c): {c}");+ assert_eq!(c["rule_claim"], "no_rule_claimed", "step (c): {c}");+ let row = &c["fragment"]["premises_outside_the_fragment"][0];+ assert_eq!(row["standing"], "outside", "step (c) fragment row: {row}");+ let reason = row["outside_because"][0]["reason"].as_str().unwrap_or("");+ assert!(+ reason.contains("disjunction in the consequent"),+ "the fragment finding must carry src/dlp.rs's own reason, got {reason:?} in {c}"+ );++ assert_eq!(v["by_family"]["entailed"], 1, "{text}");+ assert_eq!(v["by_family"]["not_entailed"], 1, "{text}");+ assert_eq!(v["by_family"]["outside_the_fragment"], 1, "{text}");+ assert_eq!(v["exit_code"], 1, "a trace with a step outside the entailed family exits 1");+ assert_eq!(v["format"], "oo-trace-label/1");++ // The dataset is the product, so it is checked here rather than trusted.+ let jsonl = std::fs::read_to_string(out.join("labels.jsonl")).expect("labels.jsonl is written");+ let rows: Vec<Value> = jsonl+ .lines()+ .filter(|l| !l.is_empty())+ .map(|l| serde_json::from_str(l).expect("each line is one JSON object"))+ .collect();+ assert_eq!(rows.len(), 3, "one record per step: {jsonl}");+ assert_eq!(rows[0]["label"], "entailed_checked", "{jsonl}");+ assert_eq!(rows[2]["label"], "outside_the_fragment", "{jsonl}");+ let cmd = rows[0]["reproduce"].as_str().expect("a reproduce command");+ assert!(+ cmd.contains("oo-cert") && cmd.contains("asserted.tsv") && cmd.contains("derivations.tsv"),+ "the record must name the command a third party runs, got {cmd:?}"+ );+}++// ── 2. Dimension two, and what it actually measures ──────────────────────────++/// **Gate.** The built-in head list is NEVER empty, and that is a fact about+/// the table rather than a weakness of the reachability test.+///+/// The design note this module was written from claimed the opposite: that a+/// conclusion of `owl:hasKey` between two IRIs would come back with an empty+/// head list, because no row of `BUILTIN_RULES` fixes that predicate. It does+/// not. `rdfs7`'s head is three variables, so from `s p o` and+/// `p rdfs:subPropertyOf q` it concludes `s q o` for ANY `q`, and `prp-trp`,+/// `prp-symp`, `prp-inv1`, `prp-inv2` and `cls-hv1` have all-variable heads+/// too. So `no_rule_in_this_table_concludes_this_shape` is unreachable under+/// the built-in table and reachable only for a supplied table whose heads fix a+/// predicate, which is what+/// `no_supplied_head_concludes_this_shape` covers.+///+/// A test asserting the note's claim would have been a gate that cannot fail+/// in the worst way: it would have failed immediately and been "fixed" by+/// widening the reachability test until it lied.+///+/// MUTATION: make `rules_whose_head_can_conclude` return `Vec::new()` for the+/// built-in branch and this fails.+#[test]+fn the_builtin_head_list_is_never_empty_because_rdfs7_concludes_anything() {+ let key = (+ "<http://e/Person>".to_string(),+ HAS_KEY.to_string(),+ "<http://e/ssn>".to_string(),+ );+ let heads = rules_whose_head_can_conclude(&key, &[]);+ assert!(+ heads.contains(&"rdfs7".to_string()),+ "rdfs7's head is three variables, so some data makes it conclude any triple: {heads:?}"+ );+ assert!(+ !heads.contains(&"rdfs9".to_string()),+ "rdfs9's head fixes rdf:type in the predicate, so it cannot conclude an owl:hasKey \+ triple: {heads:?}"+ );+ // Every shape a caller might ask about, over the built-in table.+ for t in [+ key,+ ("<http://e/a>".to_string(), TYPE.to_string(), "<http://e/C>".to_string()),+ ("<http://e/B>".to_string(), SUBCLASS.to_string(), "<http://e/C>".to_string()),+ ] {+ assert!(+ !rules_whose_head_can_conclude(&t, &[]).is_empty(),+ "the built-in table has all-variable heads, so no triple shape is unreachable: {t:?}"+ );+ }+}++/// **Gate.** The four list rules are the one piece of rule-shape data this+/// module cannot read off `BUILTIN_RULES`, so a fifth chained rule with a+/// different head shape must fail here rather than silently widen the head list.+///+/// MUTATION: add a fifth name to `reason::CHAINED_RULES` and this fails.+#[test]+fn the_four_chained_rules_all_conclude_a_type_triple() {+ assert_eq!(+ CHAINED_RULES,+ &["cls-int1", "cls-int2", "cls-uni", "cls-oo"],+ "the head shape of every chained rule is hardcoded in \+ trace_label::rules_whose_head_can_conclude; a fifth rule needs that reviewed"+ );+ let a_type = ("<http://e/a>".to_string(), Kw::Type.iri().to_string(), "<http://e/C>".to_string());+ let heads = rules_whose_head_can_conclude(&a_type, &[]);+ for r in CHAINED_RULES {+ assert!(heads.contains(&r.to_string()), "{r} concludes a type triple: {heads:?}");+ }+ let a_subclass =+ ("<http://e/B>".to_string(), SUBCLASS.to_string(), "<http://e/C>".to_string());+ let heads = rules_whose_head_can_conclude(&a_subclass, &[]);+ for r in CHAINED_RULES {+ assert!(+ !heads.contains(&r.to_string()),+ "{r} concludes rdf:type and nothing else, so it must not be listed for a \+ subClassOf conclusion: {heads:?}"+ );+ }+}++/// **Gate.** The empty head list is reachable, and it is what the third family's+/// second label rests on.+///+/// A supplied table whose head fixes `<http://e/ancestor>` in the predicate+/// cannot conclude a triple over any other predicate, whatever data arrives.+/// That is decided from the table with no reference to the store.+///+/// MUTATION: make `rules_whose_head_can_conclude` push every supplied rule name+/// unconditionally and this fails on both halves.+#[test]+fn no_supplied_head_concludes_this_shape() {+ let supplied: Vec<RulePattern> =+ parse_rules(&std::fs::read_to_string(fixture("supplied_rules.tsv")).expect("read the table"))+ .expect("the table parses");+ let unrelated = (+ "<http://e/p1>".to_string(),+ "<http://e/unrelated>".to_string(),+ "<http://e/p2>".to_string(),+ );+ assert!(+ rules_whose_head_can_conclude(&unrelated, &supplied).is_empty(),+ "no head in the supplied table fixes <http://e/unrelated>, so no data could make it \+ conclude such a triple"+ );+ let ancestor = (+ "<http://e/p1>".to_string(),+ "<http://e/ancestor>".to_string(),+ "<http://e/p2>".to_string(),+ );+ assert_eq!(+ rules_whose_head_can_conclude(&ancestor, &supplied),+ vec!["anc".to_string()],+ "and the one head that does fix it is listed"+ );+}++// ── 3. The hard rule ─────────────────────────────────────────────────────────++/// **Gate, the mapping.** The one function that decides the word maps each+/// theorem name to the sentence it stands for, and anything else to nothing.+///+/// `Certified` has no public constructor, so this is the only way to exercise+/// the mapping directly. It is a SEPARATE test from the one over the serialised+/// report, deliberately: when both lived in one function this assertion ran+/// first and panicked, so the serialisation assertion, which is the one that+/// matters, was never reached under the mutation that was supposed to prove it+/// could fail. A gate that a prior gate short-circuits is not a gate.+///+/// MUTATION: change the `"OOCert.horn_certificate_sound"` arm of+/// `warrant_of_theorem` to `Some(Warrant::Absolute)` and this fails.+#[test]+fn the_theorem_name_decides_the_word_and_nothing_else_does() {+ assert_eq!(+ warrant_of_theorem("OOCert.horn_certificate_sound"),+ Some(Warrant::UnderSuppliedRules)+ );+ assert_eq!(warrant_of_theorem("OOCert.certificate_sound"), Some(Warrant::Absolute));+ assert_eq!(warrant_of_theorem("OOCert.entails_of_builtin_horn"), Some(Warrant::Absolute));+ assert_eq!(+ warrant_of_theorem("OOCert.something_weaker"),+ None,+ "a renamed or weakened theorem earns nothing at all"+ );+}++/// **Gate.** A run over a rule table the user wrote cannot print the absolute+/// word, in any field, anywhere in the SERIALISED report.+///+/// Asserted over the serialisation and not over the enum, for the reason+/// `src/projection_entailment.rs` gives about its own suite: the enum is where+/// the discipline is easy and the serialisation is where it leaks.+///+/// MUTATION THAT BREAKS IT: change the `"OOCert.horn_certificate_sound"` arm of+/// `warrant_of_theorem` to `Some(Warrant::Absolute)`. Assertion (i) then fails+/// on the serialised report. This is the assertion the whole workstream rests+/// on and the mutation was run before landing.+#[test]+fn a_supplied_table_cannot_earn_the_absolute_word() {+ if skip_without("oo-horn") {+ return;+ }+ let g = store();+ let out = scratch("supplied");+ let rules = fixture("supplied_rules.tsv");+ let mut trace = String::new();+ trace.push_str(&line(+ "anc",+ ["<http://e/p1>", "<http://e/ancestor>", "<http://e/p2>"],+ &[["<http://e/p1>", "<http://e/parent>", "<http://e/p2>"]],+ ));+ // A second step whose conclusion no head in this table can reach, so the+ // report carries the third family too and every step is either+ // `entailed_under_supplied_rules` or outside. No step is asserted, which+ // matters: `asserted_not_derived` is a lookup in asserted.tsv, is absolute+ // whatever table is in force, and would legitimately read family+ // `entailed`, so a trace containing one could not carry assertion (ii).+ trace.push_str(&line(+ "",+ ["<http://e/p1>", "<http://e/unrelated>", "<http://e/p2>"],+ &[["<http://e/p1>", "<http://e/parent>", "<http://e/p2>"]],+ ));++ let steps = parse_trace(&trace).expect("the trace parses");+ let o = Opts { rules: Some(rules.clone()), ..opts(&out) };+ let report = label_trace(&g, &steps, &o).expect("labelling runs");+ let (text, v) = as_json(&report);++ // (i) The absolute word is unreachable, in the label and in the family and+ // in the theorem.+ for forbidden in [+ "\"label\":\"entailed_checked\"",+ "\"label\":\"entailed_unchecked\"",+ "\"family\":\"entailed\"",+ "\"theorem\":\"OOCert.certificate_sound\"",+ "\"theorem\":\"OOCert.entails_of_builtin_horn\"",+ "\"verdict\":\"locally_sound_checked\"",+ ] {+ assert!(+ !text.contains(forbidden),+ "the report over a SUPPLIED table contains {forbidden}. A certificate over a rule \+ table nobody discharged is entailed_under_supplied_rules and never entailed; \+ printing the absolute word here is assurance laundering with a per-step \+ interface:\n{text}"+ );+ }+ // (ii) And the relativised one IS reached, so (i) is not passing for want+ // of a checked step.+ assert_eq!(+ step_of(&v, 0)["label"],+ "entailed_under_supplied_rules_checked",+ "{text}"+ );+ assert_eq!(step_of(&v, 0)["family"], "entailed_under_supplied_rules", "{text}");+ assert_eq!(+ step_of(&v, 0)["local"]["verdict"],+ "locally_sound_under_supplied_rules_checked",+ "{text}"+ );+ assert_eq!(+ step_of(&v, 1)["label"],+ "no_rule_in_this_table_concludes_this_shape",+ "{text}"+ );++ // (iii) The digest of the table that was in force, and it is the digest of+ // the table AS THE RUN EVALUATED IT rather than of the user's bytes.+ let digest = v["rules_tsv_sha256"].as_str().expect("a digest over a supplied table");+ assert_eq!(digest.len(), 64, "a sha256 is 64 hex characters, got {digest:?}");+ assert!(+ digest.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()),+ "lower-case hex, got {digest:?}"+ );+ let expected = {+ use sha2::{Digest, Sha256};+ let table = parse_rules(&std::fs::read_to_string(&rules).unwrap()).unwrap();+ format!("{:x}", Sha256::digest(rules_tsv(&table).as_bytes()))+ };+ assert_eq!(digest, expected, "the digest must be of the canonical rendering of the table");++ // (iv) Every theorem named anywhere is the relativised one.+ for s in v["steps"].as_array().expect("steps") {+ for key in [&s["theorem"], &s["local"]["theorem"]] {+ if let Some(t) = key.as_str() {+ assert_eq!(t, "OOCert.horn_certificate_sound", "{text}");+ }+ }+ }++ // (v) And the report says what it is conditional on, in the report and not+ // in a footnote.+ let cond = v["conditional_on"].as_str().expect("conditional_on over a supplied table");+ assert!(+ cond.contains("ASSUMED and never checked") && cond.contains("supplied_rules.tsv"),+ "the sentence must name the file and say it was assumed, got {cond:?}"+ );+}++// ── 4. The two answers ───────────────────────────────────────────────────────++/// **Gate.** A step whose own reasoning is machine-checked sound over premises+/// the graph does not hold is NOT an entailed family.+///+/// This is the half of a per-step labeller that a graph-only labeller cannot+/// do, and the half a local-only labeller gets actively wrong.+/// `OOCert.certificate_sound` really does hold over the cited premises, and+/// that is not the whole truth: the store holds none of them, so the conclusion+/// is not entailed by the store. Both answers are in the report and neither is+/// reported as the other.+///+/// MUTATION THAT BREAKS IT: delete the `Some(c) if !premises_in_store` arm of+/// the `Membership::NotDerivable` match. The step then reads+/// `not_entailed_under_this_table` and the assertion on the label fails, which+/// is the milder failure; the serious one is the version of this module that+/// asked the local question first, where the step read `entailed_checked`.+#[test]+fn a_locally_sound_step_over_premises_the_store_lacks_is_not_entailed() {+ if skip_without("oo-cert") {+ return;+ }+ let g = store();+ let out = scratch("invented");+ // None of :q, :X or :Y occurs in boundary.ttl. The step is a correct+ // application of rdfs9 over premises it invented.+ let trace = line(+ "rdfs9",+ ["<http://e/q>", TYPE, "<http://e/Y>"],+ &[+ ["<http://e/q>", TYPE, "<http://e/X>"],+ ["<http://e/X>", SUBCLASS, "<http://e/Y>"],+ ],+ );+ let steps = parse_trace(&trace).expect("the trace parses");+ let report = label_trace(&g, &steps, &opts(&out)).expect("labelling runs");+ let (text, v) = as_json(&report);+ let s = step_of(&v, 0);++ assert_eq!(+ s["local"]["verdict"], "locally_sound_checked",+ "the cited premises DO entail the conclusion, and the report must say so: {text}"+ );+ assert_eq!(s["local"]["theorem"], "OOCert.certificate_sound", "{text}");+ assert_eq!(s["rule_claim"], "licensed", "the citation is correct: {text}");++ assert_eq!(s["premises_in_store"], false, "{text}");+ assert_eq!(+ s["premises_not_in_store"].as_array().expect("an array").len(),+ 2,+ "both invented premises must be named, not counted: {text}"+ );+ assert_eq!(s["conclusion_in_store"], "not_derivable", "{text}");++ assert_eq!(s["label"], "locally_sound_but_premises_not_in_the_store", "{text}");+ assert!(+ s["theorem"].is_null() && s["subject_sha256"].is_null(),+ "the step-level theorem is the warrant for the step-level LABEL, which is about the \+ store. The token this step earned is about its own cited premises and is reported under \+ `local`; naming it here would invite the reading this label exists to prevent: {text}"+ );+ assert_eq!(+ s["family"], "not_entailed",+ "a step reasoning from premises the graph does not hold is not entailed BY THE GRAPH, \+ whatever its own reasoning was worth: {text}"+ );+ assert!(+ !text.contains("\"family\":\"entailed\""),+ "no step may read family entailed on the strength of invented premises:\n{text}"+ );+ assert_eq!(v["exit_code"], 1, "{text}");+}++// ── 5. The format justification, made executable ─────────────────────────────++/// **Gate.** A trace this engine itself emitted labels every step entailed.+///+/// The whole argument for `oo-trace/1` is that it IS a line of+/// `derivations.tsv`, so the engine's own certificate is a valid trace. That is+/// an argument until it is run: this fails the moment the trace parser drifts+/// from what `src/reason.rs` writes.+///+/// MUTATION: change `parse_trace` to read the rule name last and this fails at+/// parse, before any label is produced.+#[test]+fn a_trace_this_engine_emitted_labels_every_step_entailed() {+ if skip_without("oo-cert") {+ return;+ }+ let g = store();+ let emitted = scratch("emitted");+ Reasoner::run_full(+ &g,+ "owl-rl-ext",+ false,+ InferenceTarget::DefaultGraph,+ Some(&emitted.join("cert")),+ )+ .expect("the engine writes a certificate");+ let derivations = emitted.join("cert").join("derivations.tsv");+ let text = std::fs::read_to_string(&derivations).expect("read derivations.tsv");+ assert!(!text.trim().is_empty(), "boundary.ttl must derive something at all");++ let steps = parse_trace(&text).expect("a derivations.tsv is a valid oo-trace/1");+ let out = scratch("selfcheck");+ let o = Opts { profile: "owl-rl-ext".to_string(), ..opts(&out) };+ let report = label_trace(&g, &steps, &o).expect("labelling runs");+ let (text, v) = as_json(&report);++ for s in v["steps"].as_array().expect("steps") {+ assert_eq!(+ s["family"], "entailed",+ "every step of the engine's own certificate must be entailed: {s}"+ );+ assert_eq!(s["rule_claim"], "licensed", "and correctly cited: {s}");+ assert_eq!(s["premises_in_store"], true, "and read only triples the store holds: {s}");+ }+ assert_eq!(v["exit_code"], 0, "a self-certificate exits clean: {text}");+}++// ── 6. A bad citation is a citation finding, never a label ───────────────────++/// **Gate.** An unknown rule name is reported against the CITATION and the step+/// is still labelled on its conclusion.+///+/// `OOCert.Parse.parseSteps` fails on an unknown rule name and `lean/Main.lean`+/// exits 2 for that, which is "a file could not be parsed" and not "the step+/// was rejected". `label_trace` bails on exit 2, so if such a step ever reached+/// the checker this test would error rather than assert, which is how it also+/// pins that it never does.+///+/// MUTATION: drop the `!known_rule(...)` guard so a bad name reaches+/// `write_one_step_certificate`, and this fails with the bail message.+#[test]+fn an_unknown_rule_name_is_a_claim_finding_and_not_a_label() {+ if skip_without("oo-cert") {+ return;+ }+ let g = store();+ let out = scratch("unknown");+ let trace = line(+ "rdfs99",+ ["<http://e/a>", TYPE, "<http://e/C>"],+ &[+ ["<http://e/a>", TYPE, "<http://e/B>"],+ ["<http://e/B>", SUBCLASS, "<http://e/C>"],+ ],+ );+ let steps = parse_trace(&trace).expect("the trace parses");+ let report = label_trace(&g, &steps, &opts(&out)).expect("labelling runs");+ let (text, v) = as_json(&report);+ let s = step_of(&v, 0);+ assert_eq!(s["rule_claim"], "rule_not_in_table", "{text}");+ assert_eq!(s["local"]["verdict"], "not_asked", "{text}");+ assert_eq!(+ s["family"], "entailed",+ "the conclusion IS entailed, and saying not_entailed for a mistyped rule name would be a \+ false statement about the ontology: {text}"+ );+ assert!(+ !text.contains("certificate_rejected"),+ "no certificate was rejected, because none was written:\n{text}"+ );+}++/// **Gate.** A chained rule cited without the RDF list it reads is a citation+/// finding, not a rejection.+///+/// `cls-int1` reads its `owl:intersectionOf` list off the asserted graph, so a+/// one-step certificate over premises carrying no `rdf:rest` would be rejected+/// for a reason that is about the citation and not about the inference.+#[test]+fn a_chained_rule_cited_without_its_list_is_a_claim_finding() {+ if skip_without("oo-cert") {+ return;+ }+ let g = store();+ let out = scratch("chained");+ let trace = line(+ "cls-int1",+ ["<http://e/a>", TYPE, "<http://e/Both>"],+ &[["<http://e/Both>", INTERSECTION_OF, "<http://e/list>"]],+ );+ let steps = parse_trace(&trace).expect("the trace parses");+ let report = label_trace(&g, &steps, &opts(&out)).expect("labelling runs");+ let (text, v) = as_json(&report);+ let s = step_of(&v, 0);+ assert_eq!(s["rule_claim"], "chained_rule_premises_incomplete", "{text}");+ assert_eq!(s["local"]["verdict"], "not_asked", "{text}");+ assert!(+ !text.contains("certificate_rejected"),+ "a citation with no list is not a rejected inference:\n{text}"+ );+}++// ── 7. The parser refuses rather than guesses ────────────────────────────────++/// **Gate.** Every malformed trace is an error naming the line, never a guess.+///+/// A step half-read still produces a label, and a label nobody wrote is worse+/// than no label.+#[test]+fn the_parser_refuses_what_it_cannot_read() {+ let good = line(+ "rdfs9",+ ["<http://e/a>", TYPE, "<http://e/C>"],+ &[["<http://e/a>", TYPE, "<http://e/B>"]],+ );+ assert_eq!(parse_trace(&good).expect("the good line parses").len(), 1);++ for (bad, wanted) in [+ ("rdfs9\t<http://e/a>\r\n", "carriage return"),+ ("rdfs9\t<http://e/a>\t<http://e/b>\n", "multiple of three"),+ ("rdfs9\t<http://e/a>\t<http://e/b>\t<http://e/c>\t<http://e/d>\n", "multiple of three"),+ ("rdfs9\t<http://e/a>\ttype\t<http://e/C>\n", "not a term in the certificate format"),+ ("", "holds no steps"),+ ("\n\n", "holds no steps"),+ ] {+ let e = parse_trace(bad).expect_err(&format!("{bad:?} must be refused")).to_string();+ assert!(e.contains(wanted), "the refusal must say {wanted:?}, got {e:?} for {bad:?}");+ }+}