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
The verified SHACL evaluator is reachable from a tool (#210)
Fabio Rovai6acf3c83dc08
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c81c5572..cb7b557e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -452,6 +452,12 @@ jobs:run: OO_REQUIRE_FIXTURES=1 cargo test --test shacl_core_verified_test -- --nocapture- name: Check the description-logic model certificatesrun: OO_REQUIRE_FIXTURES=1 cargo test --test dl_model_certificate_test -- --nocapture+ - name: Reach the verified SHACL evaluator through the tool+ # The point of this leg is reachability. `Shacl/` has been mechanised+ # for a while and nothing in `src/` could call it, so the strongest+ # 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: 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 9f8dda93..b961ae63 100644--- a/docs/ci-gates.md+++ b/docs/ci-gates.md@@ -58,6 +58,7 @@ job invokes the file at all.| `provenance_test.rs` | the same shipped ontology | `lean` job | **strict** || `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** || `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/src/inputs.rs b/src/inputs.rsindex 8b2d2923..5f5b923b 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -235,6 +235,26 @@ pub struct OntoShaclInput {/// `valid_at` or `as_of`. On a store that uses no temporal vocabulary this/// changes nothing: every graph is read either way.pub all_versions: Option<bool>,+ /// Run the VERIFIED evaluator instead of the SPARQL one.+ ///+ /// `Shacl/` is a mechanised SHACL Core evaluator whose soundness is a+ /// machine-checked theorem, `Shacl.validate_spec`. Setting this runs+ /// `oo-shacl` over the same store and shapes and returns its verdict,+ /// which is covered by that theorem, together with the theorem's name and+ /// what it does not cover.+ ///+ /// It answers a DIFFERENT set of questions from the default path, not a+ /// larger one. This evaluator covers SHACL Core and REFUSES `sh:sparql`+ /// and user-defined constraint components outright rather than skipping+ /// them, so where the default path would list a `skipped_constraints`+ /// entry this one returns `conforms: null` with a reason. That refusal is+ /// the point: "everything conforms" and "I did not check everything" are+ /// different answers and this path will not collapse them.+ ///+ /// Needs `oo-shacl` on disk: `cd lean && lake build`, or set `OO_SHACL`.+ /// Temporal scoping is not applied on this path and a scope argument+ /// alongside it is refused rather than silently ignored.+ pub verified: Option<bool>,}#[derive(Deserialize, JsonSchema)]diff --git a/src/lib.rs b/src/lib.rsindex 4bb02c3a..820c9798 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -99,6 +99,7 @@ pub mod schema;pub mod segment_retrieve;pub mod server;pub mod shacl;+pub mod shacl_verified;#[cfg(unix)]pub mod socket;#[cfg(windows)]diff --git a/src/server.rs b/src/server.rsindex d14a1c3f..8a2a99c0 100644--- a/src/server.rs+++ b/src/server.rs@@ -1258,6 +1258,25 @@ impl OpenOntologiesServer {Err(e) => return Self::err_json(format!("Cannot read shapes file: {}", e)),}};+ if input.verified.unwrap_or(false) {+ // Refused rather than ignored. The verified evaluator reads one+ // N-Triples dump of the store and has no notion of a temporal+ // scope, so honouring the argument is impossible and dropping it+ // would answer a different question from the one that was asked.+ if input.valid_at.is_some()+ || input.as_of.is_some()+ || input.all_versions.unwrap_or(false)+ {+ return Self::err_json(+ "verified: true cannot be combined with valid_at, as_of or all_versions. The verified evaluator reads the whole store and has no temporal scope, so the scope would be silently dropped. Run the scoped question on the default path, or the verified question without a scope."+ .to_string(),+ );+ }+ return match crate::shacl_verified::validate_verified(&self.graph, &shapes) {+ Ok(v) => v.to_string(),+ Err(e) => Self::err_json(e.to_string()),+ };+ }let request = match crate::temporal::ScopeRequest::from_args(input.valid_at.as_deref(),input.as_of.as_deref(),diff --git a/src/shacl_verified.rs b/src/shacl_verified.rsnew file mode 100644index 00000000..723bbabf--- /dev/null+++ b/src/shacl_verified.rs@@ -0,0 +1,233 @@+//! **The verified SHACL evaluator, reachable from a tool.**+//!+//! `Shacl/` holds a mechanised SHACL Core evaluator whose soundness is a+//! machine-checked theorem, `Shacl.validate_spec`, and `oo-shacl` is the binary+//! that runs it. Until this module existed nothing in `src/` mentioned either.+//! A grep for `oo-shacl`, `ShaclMain` or `validate_spec` across the whole crate+//! returned one file, `tests/shacl_core_verified_test.rs`, and that is a test.+//!+//! So the strongest claim in the repository was unreachable from its own+//! interface. `onto_shacl` and the CLI compiled every constraint to SPARQL and+//! handed it to Oxigraph, unverified, with a `skipped_constraints` list; the+//! Lean result was a lab measurement with a binary beside it rather than+//! something a user could obtain. This closes that, behind `verified: true`.+//!+//! # Why a second path rather than a replacement+//!+//! The Rust path answers more. `Shacl/` covers SHACL Core and refuses+//! `sh:sparql` and user-defined components outright, which is 22 of the 120+//! W3C tests; the Rust evaluator runs those and skips others. Neither is a+//! superset, so replacing one with the other would lose answers people depend+//! on. `verified: true` says which question you are asking.+//!+//! # The three exit codes, and why the middle one is the point+//!+//! `oo-shacl` exits 0 with a verdict, 2 when a file could not be read, and 3+//! UNDETERMINED when the shapes graph uses something the development does not+//! implement or the evaluator declined to judge. Three is the code that+//! matters: it is the difference between "everything conforms" and "I did not+//! check everything", and a caller that collapsed them would be doing exactly+//! what the unverified path's `skipped_constraints` list exists to prevent.+//! There is no `conforms: true` on this path that is not covered by the+//! theorem.+//!+//! # The word is earned+//!+//! `ShaclVerified::Checked` carries a [`Certified`], which has no public+//! constructor: the only one in the crate comes out of+//! [`CheckerRun::accepted`] after a process exited zero. The same discipline+//! `src/fol_solve.rs` uses, and for the same reason.++use crate::graph::GraphStore;+use crate::verdict::{CheckerBinary, CheckerRun, Certified};+use std::path::PathBuf;+use std::sync::atomic::{AtomicU64, Ordering};+use std::process::Command;+use std::sync::Arc;++/// Serial number for the scratch directory, so concurrent calls cannot share+/// one. See `validate_verified`.+static NEXT_RUN: AtomicU64 = AtomicU64::new(0);++/// Where `oo-shacl` is, or a message saying how to get one.+///+/// `$OO_SHACL` first, so an operator can point at an installed binary, then the+/// repository's own build output. Mirrors `find_checker` in `src/fol_solve.rs`+/// and `src/closure_diff.rs`; the paths differ, the shape does not.+pub fn find_checker() -> Result<CheckerBinary, String> {+ resolve_checker(std::env::var("OO_SHACL").ok())+}++/// The resolution itself, with the environment passed in rather than read.+///+/// Split out so it is testable without `set_var`. A test that pointed+/// `OO_SHACL` at a nonexistent path to exercise the not-found branch changed+/// the variable for every OTHER test in the same process, because the+/// environment is process-global and the harness runs tests in parallel: two+/// unrelated tests in this file went red and one of them was the reachability+/// claim itself. A pure function has no such reach.+pub fn resolve_checker(env: Option<String>) -> Result<CheckerBinary, String> {+ if let Some(v) = env {+ let p = PathBuf::from(&v);+ if p.exists() {+ return Ok(CheckerBinary::found_at(p));+ }+ return Err(format!("OO_SHACL is set to {v}, which does not exist"));+ }+ let local = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("lean/.lake/build/bin/oo-shacl");+ if local.exists() {+ return Ok(CheckerBinary::found_at(local));+ }+ Err(format!(+ "the verified SHACL evaluator was not found. Build it with `cd lean && lake build \+ oo-shacl` (it is in defaultTargets, so a bare `lake build` is enough), or set \+ OO_SHACL. Looked in {}",+ local.display()+ ))+}++/// What the verified evaluator said.+#[derive(Debug, Clone)]+pub enum ShaclVerified {+ /// Exit 0. A verdict covered by `Shacl.validate_spec`. The `bool` is+ /// `conforms`; the token is the evidence a checker accepted the run.+ Checked(bool, Certified),+ /// Exit 3. The evaluator declined to judge, and said why. NOT a conformance+ /// verdict in either direction, and the reason it is a separate variant is+ /// that a caller cannot accidentally read it as one.+ Undetermined(String),+}++/// Serialise the store and the shapes and run the verified evaluator over them.+///+/// The two files are N-Triples because that is what `oo-shacl` reads, and the+/// shapes are round-tripped through a scratch store so a caller can pass the+/// Turtle every other tool here takes.+pub fn validate_verified(+ graph: &Arc<GraphStore>,+ shapes_ttl: &str,+) -> anyhow::Result<serde_json::Value> {+ let checker = match find_checker() {+ Ok(c) => c,+ Err(why) => {+ return Ok(serde_json::json!({+ "verified": false,+ "error": why,+ "note": "no verdict. A missing checker is not a conformance answer.",+ }))+ }+ };++ let data_nt = graph.snapshot("ntriples")?;+ // The shapes arrive as Turtle and `oo-shacl` reads N-Triples, so they go+ // through a scratch store. A shapes file that will not parse is an error+ // here rather than an empty shapes graph, because an empty shapes graph+ // conforms vacuously and that is the one answer nobody wants by accident.+ let scratch = GraphStore::new();+ scratch.load_turtle(shapes_ttl, None)?;+ let shapes_nt = scratch.snapshot("ntriples")?;++ // A directory per CALL, not per process.+ //+ // This was keyed on the pid alone, which is the same for every call in a+ // process, so two concurrent validations wrote each other's `data.nt` and+ // read it back. Two tests in this suite came back with byte-identical+ // reports over different graphs, one of them claiming `conforms: true` for+ // a graph that violates its shape, with a theorem name attached. The+ // server is the concurrent case that matters: `onto_shacl` is a tool+ // several sessions can call at once, and a verdict computed over another+ // caller's data is the worst thing this layer could produce.+ let serial = NEXT_RUN.fetch_add(1, Ordering::Relaxed);+ let dir = std::env::temp_dir().join(format!("oo-shacl-{}-{serial}", std::process::id()));+ std::fs::create_dir_all(&dir)?;+ let data_path = dir.join("data.nt");+ let shapes_path = dir.join("shapes.nt");+ std::fs::write(&data_path, &data_nt)?;+ std::fs::write(&shapes_path, &shapes_nt)?;++ let mut cmd = Command::new(checker.path());+ cmd.arg("validate").arg(&data_path).arg(&shapes_path);+ let run = CheckerRun::spawn(&checker, cmd)?;+ let _ = std::fs::remove_dir_all(&dir);++ // The checker's own JSON, echoed rather than restated. Its verdict words+ // are its to print; this module quotes bytes it read from that stdout.+ let report: serde_json::Value =+ serde_json::from_str(run.stdout()).unwrap_or(serde_json::Value::Null);++ match run.exit() {+ 0 => {+ let conforms = report+ .get("conforms")+ .and_then(|v| v.as_bool())+ .ok_or_else(|| {+ anyhow::anyhow!(+ "oo-shacl exited 0 without a boolean `conforms`; refusing to guess \+ one. stdout was: {}",+ run.stdout()+ )+ })?;+ let token = run.accepted("Shacl.validate_spec").ok_or_else(|| {+ anyhow::anyhow!("exit 0 did not yield a certificate token, which cannot happen")+ })?;+ let v = ShaclVerified::Checked(conforms, token);+ Ok(describe(&v, &report, run.binary().display().to_string()))+ }+ 3 => {+ let why = report+ .get("reason")+ .and_then(|v| v.as_str())+ .unwrap_or("the evaluator declined to judge and named no reason")+ .to_string();+ Ok(describe(+ &ShaclVerified::Undetermined(why),+ &report,+ run.binary().display().to_string(),+ ))+ }+ 2 => Ok(serde_json::json!({+ "verified": false,+ "conforms": serde_json::Value::Null,+ "error": "the verified evaluator could not read the data or the shapes",+ "detail": run.output(),+ "note": "exit 2 is a parse failure, not a conformance answer",+ })),+ other => Ok(serde_json::json!({+ "verified": false,+ "conforms": serde_json::Value::Null,+ "error": format!("the verified evaluator exited {other}, which its CLI does not define"),+ "detail": run.output(),+ })),+ }+}++fn describe(v: &ShaclVerified, report: &serde_json::Value, binary: String) -> serde_json::Value {+ match v {+ ShaclVerified::Checked(conforms, token) => serde_json::json!({+ "verified": true,+ "conforms": conforms,+ "theorem": token.theorem(),+ "checker": binary,+ "report": report,+ "covers": "SHACL Core under Shacl/Spec.lean. sh:sparql and user-defined \+ constraint components are REFUSED by this evaluator rather than \+ skipped, so a verdict here is about every constraint it read.",+ "does_not_cover": "that Shacl/Spec.lean is the W3C Recommendation; it is a \+ reading of it, measured against the Working Group's suite. \+ Nor that the shapes compiler or the N-Triples parser is \+ correct: both are outside the theorem and refuse rather \+ than guess.",+ }),+ ShaclVerified::Undetermined(why) => serde_json::json!({+ "verified": true,+ "conforms": serde_json::Value::Null,+ "undetermined": why,+ "checker": binary,+ "report": report,+ "note": "the evaluator declined to judge. This is NOT conformance: the \+ difference between 'everything conforms' and 'I did not check \+ everything' is the whole reason this path exists.",+ }),+ }+}diff --git a/tests/shacl_verified_tool_test.rs b/tests/shacl_verified_tool_test.rsnew file mode 100644index 00000000..e6bb973f--- /dev/null+++ b/tests/shacl_verified_tool_test.rs@@ -0,0 +1,145 @@+//! **The verified SHACL evaluator, reachable from a tool (session feedback).**+//!+//! `Shacl/` is a mechanised SHACL Core evaluator whose soundness is a+//! machine-checked theorem. Until `src/shacl_verified.rs` existed, a grep of+//! `src/` for `oo-shacl`, `ShaclMain` or `validate_spec` returned NOTHING: the+//! only caller in the repository was `tests/shacl_core_verified_test.rs`. The+//! strongest claim here was unreachable from its own interface, which made it a+//! lab result with a binary beside it rather than a feature.+//!+//! These tests are about reachability and about the one thing that must not go+//! wrong on the way: a refusal must never read as conformance.++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::shacl_verified::{find_checker, validate_verified};+use std::sync::Arc;++fn skip() -> bool {+ match find_checker() {+ Ok(_) => false,+ Err(why) => common::skip_unless(+ false,+ &why,+ "the verified SHACL tests need the oo-shacl binary and check nothing without it",+ ),+ }+}++const PREFIXES: &str = r#"+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix ex: <http://ex.org/> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .+"#;++fn run(data: &str, shapes: &str) -> serde_json::Value {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(&format!("{PREFIXES}{data}"), None).expect("data");+ validate_verified(&g, &format!("{PREFIXES}{shapes}")).expect("run")+}++/// The reachability claim itself: a caller with a store and shapes gets the+/// verified verdict and the name of the theorem covering it.+#[test]+fn a_conforming_graph_is_certified_and_names_its_theorem() {+ if skip() {+ return;+ }+ let v = run(+ "ex:alice a ex:Person ; ex:name \"Alice\" .",+ "ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:name ; sh:minCount 1 ] .",+ );+ assert_eq!(v["verified"], serde_json::json!(true), "{v}");+ assert_eq!(v["conforms"], serde_json::json!(true), "{v}");+ assert_eq!(+ v["theorem"],+ serde_json::json!("Shacl.validate_spec"),+ "a verified verdict has to name what covers it: {v}"+ );+}++/// And it can say no. A verdict layer that only ever agrees is decoration.+#[test]+fn a_violating_graph_is_certified_as_not_conforming() {+ if skip() {+ return;+ }+ let v = run(+ "ex:bob a ex:Person .",+ "ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:name ; sh:minCount 1 ] .",+ );+ assert_eq!(v["verified"], serde_json::json!(true), "{v}");+ assert_eq!(v["conforms"], serde_json::json!(false), "{v}");+ assert_eq!(v["theorem"], serde_json::json!("Shacl.validate_spec"), "{v}");+}++/// **The one that matters.**+///+/// `sh:sparql` is outside what the Lean development implements, and the whole+/// argument for this path is that it REFUSES rather than skipping. A refusal+/// must come back as `conforms: null` with a reason, never as `true`. If this+/// ever returns `true`, the verified path is claiming to have checked a+/// constraint it did not read, which is worse than the unverified path's+/// `skipped_constraints` list because it carries a theorem name.+#[test]+fn a_constraint_outside_the_development_is_undetermined_and_never_conforming() {+ if skip() {+ return;+ }+ let v = run(+ "ex:carol a ex:Person .",+ "ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:sparql [ sh:select \"SELECT $this WHERE { $this ex:x ?v }\" ] .",+ );+ assert_ne!(+ v["conforms"],+ serde_json::json!(true),+ "a constraint the evaluator cannot read came back as CONFORMING, carrying a theorem \+ name. That is the failure this whole path exists to prevent: {v}"+ );+}++/// A temporal scope cannot be honoured on this path, so asking for one must be+/// refused rather than dropped. Answering the unscoped question when a scoped+/// one was asked is a wrong answer, not a lenient one.+#[test]+fn a_scoped_request_is_refused_rather_than_silently_unscoped() {+ let src = std::fs::read_to_string(+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/server.rs"),+ )+ .expect("server.rs");+ let i = src+ .find("if input.verified.unwrap_or(false)")+ .expect("the verified branch");+ let window = &src[i..i + 1200];+ for arg in ["valid_at", "as_of", "all_versions"] {+ assert!(+ window.contains(arg),+ "the verified branch does not mention {arg}, so a scoped request would be \+ answered unscoped"+ );+ }+ assert!(+ window.contains("cannot be combined"),+ "the verified branch does not refuse a scoped request"+ );+}++/// Without the binary there is no verdict, and the absence says so rather than+/// producing one. A missing checker is not a conformance answer.+///+/// Exercised through `resolve_checker` rather than by setting `OO_SHACL`. The+/// environment is process-global and the harness runs tests in parallel, so the+/// first version of this test turned the two reachability tests above red by+/// pointing every other test at a path that does not exist.+#[test]+fn a_missing_checker_yields_no_verdict() {+ let e = open_ontologies::shacl_verified::resolve_checker(Some(+ "/nonexistent/oo-shacl".to_string(),+ ))+ .expect_err("a path that does not exist must not resolve to a checker");+ assert!(e.contains("does not exist"), "{e}");+}