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
Closes #206: the verified SHACL compiler names what it ignores (#247)
Fabio Rovai1af64e183b14
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3dfc7c28..5405daa5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -481,6 +481,12 @@ jobs:# claim in the repository was a lab result with a binary beside it.# Strict, because a skip here would put it straight back.run: OO_REQUIRE_FIXTURES=1 cargo test --test shacl_verified_tool_test -- --nocapture+ - name: The SHACL compiler names what it ignores+ # #206. Strict because four of the five tests need `oo-shacl`, and the+ # thing they protect is that a predicate the compiler waves through+ # still REACHES the report. A skip here restores the silence the issue+ # was about and nothing would go red.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test shacl_ignored_is_named_test -- --nocapture- name: Check the description-logic refutation certificates# The other half of the line above. That one certifies that an ontology# HAS a model by exhibiting one; this certifies that it has NONE bydiff --git a/docs/ci-gates.md b/docs/ci-gates.mdindex b961ae63..06fd8076 100644--- a/docs/ci-gates.md+++ b/docs/ci-gates.md@@ -59,6 +59,7 @@ job invokes the file at all.| `shacl_core_verified_test.rs` | lake + vendored W3C SHACL suite | `lean` job | **strict** || `dl_model_certificate_test.rs` | lake + `oo-dlmodel` | `lean` job | **strict** || `shacl_verified_tool_test.rs` | lake + `oo-shacl` | `lean` job | **strict** |+| `shacl_ignored_is_named_test.rs` | lake + `oo-shacl` | `lean` job | **strict** || `dl_refutation_certificate_test.rs` | lake + `oo-dlrefute` | `lean` job | **strict** || `lean_refutation_test.rs` | lake + `oo-refute` | `lean` job | **strict** || `lean_refutation_producer_test.rs` | lake + `oo-refute` | `lean` job | **strict** |diff --git a/lean/Shacl/Compile.lean b/lean/Shacl/Compile.leanindex 60113f66..2512031e 100644--- a/lean/Shacl/Compile.lean+++ b/lean/Shacl/Compile.lean@@ -42,6 +42,14 @@ measurement, which counts it separately from a pass and from a failure.ignored, so every result this validator produces is a violation with no severityrecorded. That is a real gap and it is named here rather than discovered: a reportconsumer that acts on severity must not use this validator.++What is no longer true is that the gap is INVISIBLE from the output.+`ignoredPairs` collects every `(subject, predicate)` pair in the shapes graph+whose predicate this list waves through, and the verdict carries it, so a reader+of the JSON alone learns that a severity or a message was present and dropped.+That is the defect issue #206 named: not the ignoring, which is honest, but the+silence, in the one place a compiler whose rule is refuse rather than guess+discarded instead.-/namespace Shacl.Compile@@ -140,11 +148,45 @@ def knownParams : List Term :=/-- Parameters with no effect on the verdict or on the result fields thisvalidator reports. `sh:severity` is the one that is a real gap; see the module-header. -/+header.++Adding a predicate here is enough to make it appear in the report's `ignored`+list, because `ignoredPairs` reads THIS list. There is no second place to+update, and `tests/shacl_ignored_is_named_test.rs` reads this list out of the+source rather than typing the IRIs, so a predicate added here without reaching+the report turns that file red. -/def ignoredParams : List Term :=[ SH.message, SH.name, SH.description, SH.order, SH.group, SH.defaultValue,SH.severity ]+/-- Every `(subject, predicate)` pair in the shapes graph whose predicate this+compiler IGNORES: present, read past, and with no effect on the verdict or on+any result field.++This exists because discarding in silence is the one place the compiler broke+the rule the rest of it keeps. A predicate in neither `knownParams` nor+`ignoredParams` is REFUSED with a reason; a predicate in `ignoredParams`+vanished, and a shapes graph that marked a constraint `sh:Warning` produced+byte-identical output to one that marked it `sh:Violation`. A reader could not+learn from the output that anything had been dropped. Now they can.++It is a filter over the graph and NOT a trace of the compiler's reads, and the+difference is worth stating rather than glossing. The compiler visits targeted+nodes and the shapes nested inside them, so a pair sitting on a node nothing+targets appears here and was never read. It had no effect either, which is the+fact a reader of this list wants, so both readings of "ignored" agree on the+answer while disagreeing on the route.++It reads `ignoredParams`, the same list `compileShape` waves through, so the+report and the compiler cannot drift apart: a predicate added to that list+starts appearing here on the same build.++Nothing here touches `Shacl.validate_spec`. The verdict is unchanged, because+none of these predicates ever affected it; what changes is that the report now+says so. -/+def ignoredPairs (G : Graph) : List (Term × Term) :=+ dedup ((G.filter (fun t => ignoredParams.contains t.p)).map (fun t => (t.s, t.p)))+def isShaclPred (p : Term) : Bool := p.startsWith ("<" ++ SH.ns)/-! ## Reading the graph -/diff --git a/lean/ShaclMain.lean b/lean/ShaclMain.leanindex a2af6e69..5a95fb8e 100644--- a/lean/ShaclMain.lean+++ b/lean/ShaclMain.lean@@ -30,6 +30,11 @@ What that theorem does NOT cover, and what a reader must therefore not assume:outside the theorem, and it refuses rather than guesses;* that the N-Triples parser is correct. Also outside, and a parse error is exit 2;* `sh:resultSeverity`. Never emitted; `sh:severity` in the shapes graph is ignored.+ It is no longer ignored in SILENCE: the verdict carries an `ignored` list naming+ every `(subject, predicate)` pair whose predicate this compiler waves through, so+ a reader learns from the output that a severity or a message was present and had+ no effect. The list says nothing about what those predicates MEAN; the theorem is+ about conformance and is silent on both.-/open Shacl@@ -68,6 +73,21 @@ def readOrFail (path : String) : IO (Except String String) := docatch e =>return .error s!"cannot read {path}: {e}"+/-- One `(shape, predicate)` pair the compiler ignored. -/+def showIgnored (pair : Shacl.Term × Shacl.Term) : String :=+ "{\"subject\":" ++ jsonStr pair.1 ++ ",\"predicate\":" ++ jsonStr pair.2 ++ "}"++/-- What the `ignored` list means, carried beside it so a consumer reading the+JSON alone cannot mistake it for a list of violations. -/+def ignoredMeans : String :=+ "these SHACL predicates are present in the shapes graph and had NO effect on the verdict \+ or on any field of any result. sh:severity and sh:message are the two that carry meaning \+ to a reader: a shapes graph marking a constraint sh:Warning produces the same verdict \+ here as one marking it sh:Violation, and sh:resultSeverity is never emitted. \+ Shacl.validate_spec is about conformance and says NOTHING about either of them. Listed \+ rather than dropped in silence, because the rest of this compiler refuses what it cannot \+ do and this was the one place it discarded instead."+def emitError (reason : String) : IO UInt32 := doIO.println ("{\"status\":\"error\",\"reason\":" ++ jsonStr reason ++ "}")return 2@@ -97,10 +117,13 @@ def run (dataPath shapesPath : String) : IO UInt32 := doemitUndetermined s!"the evaluator declined: {refusal.describe}"| .ok results =>let conforms := results.isEmpty+ let ignored := Compile.ignoredPairs shapesGIO.println ("{\"status\":\"verdict\",\"conforms\":" ++ (if conforms then "true" else "false") ++",\"shapes\":" ++ toString decls.length ++",\"data_triples\":" ++ toString dataG.length ++",\"results\":[" ++ String.intercalate "," (results.map showResult) ++ "]" +++ ",\"ignored\":[" ++ String.intercalate "," (ignored.map showIgnored) ++ "]" +++ ",\"ignored_means\":" ++ jsonStr ignoredMeans ++",\"theorem\":\"Shacl.validate_spec\"}")return 0diff --git a/tests/shacl_ignored_is_named_test.rs b/tests/shacl_ignored_is_named_test.rsnew file mode 100644index 00000000..3530c824--- /dev/null+++ b/tests/shacl_ignored_is_named_test.rs@@ -0,0 +1,313 @@+//! The verified SHACL compiler NAMES what it ignores, instead of discarding it.+//!+//! Issue #206. `ignoredParams` in `lean/Shacl/Compile.lean` lists seven SHACL+//! predicates that compile silently and leave no trace. Five of them carry no+//! conformance meaning and ignoring them is right. Two do not fit that+//! description:+//!+//! `sh:severity` exists to change what a result means to a reader. A shapes+//! graph marking a constraint `sh:Warning` and one marking it `sh:Violation`+//! produced byte-identical output, and `sh:resultSeverity` is never emitted.+//! `sh:message` is the author's explanation of the constraint, and a report+//! that blames a node without the sentence its author wrote for exactly that+//! case is less useful than the shapes graph it came from.+//!+//! The defect is not that they are ignored. It is that they were ignored in+//! SILENCE, in the one place a compiler whose stated rule is refuse rather+//! than guess discarded instead. A predicate in neither `knownParams` nor+//! `ignoredParams` is refused with a reason; a predicate in `ignoredParams`+//! vanished, and nothing in the output said so.+//!+//! So the report gains an `ignored` list of `(subject, predicate)` pairs, in+//! the spirit of `skipped_constraints` on the Rust path. The verdict does not+//! change, because none of these predicates ever affected it, and+//! `Shacl.validate_spec` is untouched. Steps 2 and 3 of the issue, carrying+//! the message and the severity through to each result, are deliberately not+//! here: they would put fields in a report that the theorem says nothing+//! about, and that is a separate decision from removing the silence.+//!+//! # The expectation is read out of the Lean source+//!+//! [`ignored_params_in_the_source`] scans `ignoredParams` in `Compile.lean`+//! and resolves each entry to its IRI. A predicate added to that list without+//! flowing through to the report turns+//! `every_ignored_parameter_reaches_the_report` red on the day it lands, which+//! a list of seven IRIs typed here could never do.++mod common;++use std::collections::BTreeSet;+use std::path::PathBuf;+use std::process::Command;++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn compile_lean() -> String {+ std::fs::read_to_string(repo().join("lean").join("Shacl").join("Compile.lean"))+ .expect("read lean/Shacl/Compile.lean")+}++/// The IRIs of the predicates `ignoredParams` holds, resolved through the+/// `SH` vocabulary block in the same file.+fn ignored_params_in_the_source() -> BTreeSet<String> {+ let src = compile_lean();+ let start = src.find("def ignoredParams : List Term :=").expect(+ "`ignoredParams` is gone from Compile.lean. If it was renamed this scan reads \+ nothing and every assertion below is vacuous",+ );+ let body = &src[start..];+ let open = body.find('[').expect("the list opens");+ let close = body.find(']').expect("the list closes");+ let names: Vec<String> = body[open + 1..close]+ .split(',')+ .map(|s| s.trim().trim_start_matches("SH.").to_string())+ .filter(|s| !s.is_empty())+ .collect();+ assert!(+ names.len() >= 5,+ "the scan of ignoredParams found only {names:?}, so the spelling has changed and \+ this file is measuring nothing"+ );++ // Each name is a `def <name> : Term := iri "<local>"` in the vocabulary+ // block. Resolving through it rather than assuming the Lean identifier and+ // the SHACL local name coincide, because several of them do not: the+ // compiler spells `sh:class` as `klass` and `sh:not` as `notC`.+ let ns = "http://www.w3.org/ns/shacl#";+ names+ .iter()+ .map(|n| {+ let needle = format!("def {n} : Term := iri \"");+ let at = src+ .find(&needle)+ .unwrap_or_else(|| panic!("no vocabulary entry for SH.{n} in Compile.lean"));+ let rest = &src[at + needle.len()..];+ let end = rest.find('"').expect("the local name closes");+ format!("<{ns}{}>", &rest[..end])+ })+ .collect()+}++fn checker() -> Option<PathBuf> {+ if let Ok(p) = std::env::var("OO_SHACL") {+ let p = PathBuf::from(p);+ return p.exists().then_some(p);+ }+ let built = repo().join("lean/.lake/build/bin/oo-shacl");+ built.exists().then_some(built)+}++fn skip() -> bool {+ common::skip_unless(+ checker().is_some(),+ "the verified SHACL evaluator (oo-shacl)",+ "run `lake build oo-shacl` in lean/, or point $OO_SHACL at a built one",+ )+}++fn dir(tag: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("oo-shacl-ignored-{}-{tag}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++fn validate(tag: &str, data: &str, shapes: &str) -> serde_json::Value {+ let d = dir(tag);+ let dp = d.join("data.nt");+ let sp = d.join("shapes.nt");+ std::fs::write(&dp, data).unwrap();+ std::fs::write(&sp, shapes).unwrap();+ let out = Command::new(checker().expect("checked by skip()"))+ .arg("validate")+ .arg(&dp)+ .arg(&sp)+ .output()+ .expect("run oo-shacl");+ let text = String::from_utf8_lossy(&out.stdout).to_string();+ serde_json::from_str(&text).unwrap_or_else(|e| panic!("oo-shacl printed no JSON ({e}): {text}"))+}++fn ignored_predicates(report: &serde_json::Value) -> BTreeSet<String> {+ report["ignored"]+ .as_array()+ .unwrap_or(&Vec::new())+ .iter()+ .filter_map(|p| p["predicate"].as_str().map(|s| s.to_string()))+ .collect()+}++const DATA: &str = concat!(+ "<http://ex.org/alice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Person> .\n",+ "<http://ex.org/alice> <http://ex.org/name> \"Alice\" .\n",+ "<http://ex.org/bob> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Person> .\n",+);++/// A shapes graph using only predicates the compiler implements.+const PLAIN_SHAPES: &str = concat!(+ "<http://ex.org/S> <http://www.w3.org/ns/shacl#targetClass> <http://ex.org/Person> .\n",+ "<http://ex.org/S> <http://www.w3.org/ns/shacl#property> _:p .\n",+ "_:p <http://www.w3.org/ns/shacl#path> <http://ex.org/name> .\n",+ "_:p <http://www.w3.org/ns/shacl#minCount> \"1\"^^<http://www.w3.org/2001/XMLSchema#integer> .\n",+);++#[test]+fn a_shapes_graph_that_ignores_nothing_lists_nothing() {+ if skip() {+ return;+ }+ let r = validate("plain", DATA, PLAIN_SHAPES);+ assert_eq!(r["conforms"], false, "bob has no name: {r}");+ assert!(+ ignored_predicates(&r).is_empty(),+ "a shapes graph using only implemented predicates must report an EMPTY ignored \+ list. A list that is never empty says nothing: {r}"+ );+}++#[test]+fn every_ignored_parameter_reaches_the_report() {+ if skip() {+ return;+ }+ let want = ignored_params_in_the_source();+ // One triple per ignored predicate, all on the shape node, with an object+ // that is never read. The compiler must accept every one of them, which is+ // what `ignoredParams` means, and must now name every one of them.+ let mut shapes = String::from(PLAIN_SHAPES);+ for (i, p) in want.iter().enumerate() {+ shapes.push_str(&format!("<http://ex.org/S> {p} \"ignored {i}\" .\n"));+ }+ let r = validate("all", DATA, &shapes);+ assert_eq!(+ r["status"], "verdict",+ "every predicate in ignoredParams must COMPILE, not be refused: {r}"+ );+ let got = ignored_predicates(&r);+ assert_eq!(+ got, want,+ "the report must name every parameter the compiler ignores. A predicate in \+ ignoredParams that never reaches the report is discarded in silence, which is \+ the defect this closes"+ );+}++#[test]+fn severity_changes_the_ignored_list_and_not_the_verdict() {+ if skip() {+ return;+ }+ // The pair the issue is really about. These two shapes graphs differ in one+ // triple, and that triple is the whole of what a reader would use to decide+ // whether a result blocks a pipeline or is logged.+ let warning = format!(+ "{PLAIN_SHAPES}<http://ex.org/S> <http://www.w3.org/ns/shacl#severity> \+ <http://www.w3.org/ns/shacl#Warning> .\n"+ );+ let violation = format!(+ "{PLAIN_SHAPES}<http://ex.org/S> <http://www.w3.org/ns/shacl#severity> \+ <http://www.w3.org/ns/shacl#Violation> .\n"+ );+ let a = validate("warn", DATA, &warning);+ let b = validate("viol", DATA, &violation);++ // Unchanged, which is the honest half: the theorem is about conformance and+ // severity is outside it. This must NOT start differing.+ assert_eq!(a["conforms"], b["conforms"], "severity must not move the verdict");+ assert_eq!(a["results"], b["results"], "nor any result field");+ assert_eq!(a["theorem"], "Shacl.validate_spec");++ // And the half that changed: both now SAY a severity was present and+ // dropped, where before the two reports were byte-identical.+ for (label, r) in [("warning", &a), ("violation", &b)] {+ assert!(+ ignored_predicates(r).contains("<http://www.w3.org/ns/shacl#severity>"),+ "the {label} graph carries sh:severity and the report must say it was \+ ignored: {r}"+ );+ }+ assert!(+ r_means(&a).contains("resultSeverity"),+ "and the report must say what ignoring it costs the reader: {a}"+ );+}++fn r_means(r: &serde_json::Value) -> String {+ r["ignored_means"].as_str().unwrap_or_default().to_string()+}++/// The pair names the SHAPE, not just the predicate, or a reader with a large+/// shapes graph learns that something somewhere was dropped.+#[test]+fn the_pair_names_the_shape_it_sat_on() {+ if skip() {+ return;+ }+ let shapes = format!(+ "{PLAIN_SHAPES}_:p <http://www.w3.org/ns/shacl#message> \"every person needs a name\" .\n"+ );+ let r = validate("subject", DATA, &shapes);+ let subjects: BTreeSet<String> = r["ignored"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|p| p["subject"].as_str().map(|s| s.to_string()))+ .collect();+ assert!(+ subjects.contains("_:p"),+ "the message sits on the property shape and the report must say which node \+ carried it: {r}"+ );+}++/// The Rust side echoes the checker's JSON rather than restating it, so the+/// field has to arrive through `onto_shacl`'s verified path without anybody+/// teaching it the name.+#[test]+fn the_field_reaches_the_rust_report_without_being_restated() {+ if skip() {+ return;+ }+ let src = std::fs::read_to_string(repo().join("src").join("shacl_verified.rs"))+ .expect("read src/shacl_verified.rs");+ assert!(+ !src.contains("ignored_means"),+ "the Rust side must not carry a copy of the checker's explanation. It echoes the \+ checker's report; a second copy here would be a string that can drift from the \+ one the checker prints"+ );++ let store = std::sync::Arc::new(open_ontologies::graph::GraphStore::new());+ store+ .load_file(&write_turtle_data())+ .expect("load the data");+ let shapes_ttl = concat!(+ "@prefix sh: <http://www.w3.org/ns/shacl#> .\n",+ "@prefix ex: <http://ex.org/> .\n",+ "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n",+ "ex:S a sh:NodeShape ; sh:targetClass ex:Person ; sh:severity sh:Warning ;\n",+ " sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:message \"needs a name\" ] .\n",+ );+ let v = open_ontologies::shacl_verified::validate_verified(&store, shapes_ttl)+ .expect("the verified path runs");+ let listed = v["report"]["ignored"].as_array().cloned().unwrap_or_default();+ assert!(+ listed.len() >= 2,+ "sh:severity and sh:message are both in these shapes and both must reach the \+ Rust report: {v}"+ );+}++fn write_turtle_data() -> String {+ let d = dir("rust");+ let p = d.join("data.ttl");+ std::fs::write(+ &p,+ "@prefix ex: <http://ex.org/> .\nex:alice a ex:Person ; ex:name \"Alice\" .\nex:bob a ex:Person .\n",+ )+ .unwrap();+ p.display().to_string()+}+