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
SHACL results lacked the value node and no W3C report graph existed; add value and report_format
FABIOTESS1f9666853ee6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 28a447e6..607072ad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,33 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]+### Added++- **`onto_shacl` and `shacl` write a W3C `sh:ValidationReport` graph**+ (#318, reported by @noahgift). `report_format: "turtle" | "ntriples"`+ (`--report-format` on the CLI) returns the report as RDF, carrying+ `sh:conforms` and, per result, `sh:focusNode`, `sh:resultPath`, `sh:value`,+ `sh:sourceShape`, `sh:sourceConstraintComponent`, `sh:resultSeverity` and+ `sh:resultMessage`; a custom severity IRI and a language-tagged `sh:message`+ are written as declared. An undetermined run (`conforms: null`) is written+ `sh:conforms false` plus `oo:undetermined true` and its reason, never+ `sh:conforms true`, and keeps the results it found. The CLI exit code is+ still taken from the verdict (0, 1, 2) in every format. JSON stays the+ default and is unchanged apart from `value`. Measured against the W3C suite:+ 48 of the 56 `core/` cases that pass today produce a report matching the+ expected one after RDFC-1.0 canonicalisation; the 8 that differ are named in+ `tests/shacl_validation_report_w3c_test.rs` with their causes, which include+ an `sh:or` false negative on IRI and ill-typed values.++### Fixed++- **Default-path SHACL results now carry the value node** (#318, reported by+ @noahgift). The `sh:class`, `sh:datatype`, `sh:nodeKind`, `sh:pattern`,+ `sh:in`, `sh:or`, `sh:not`, length and range queries selected the offending+ value and dropped it, so `value` appeared only on `sh:sparql` results. It is+ now on every result whose query binds it, and on node-shape results as the+ focus node.+## [2.1.0] - 2026-10-23### Fixeddiff --git a/src/batch.rs b/src/batch.rsindex 487e93a7..825bc9d0 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -636,6 +636,17 @@ impl BatchRunner {Some(p) => p,None => return json!({"error": "shacl requires a shapes file path"}),};+ // A batch result is a JSON value, so an RDF report has nowhere to go.+ // The CLI keeps such an invocation local for that reason; one written+ // into a batch file by hand is refused rather than answered in JSON.+ if let Some(f) = Self::flag_value(args, "--report-format")+ && f != "json"+ {+ return json!({"error": format!(+ "--report-format {f} is not available in a batch: batch results are JSON. \+ Run `shacl --report-format {f}` directly."+ )});+ }if args.iter().any(|a| a == "--verified") {// Refused rather than ignored, the same answer `onto_shacl` gives.// The verified evaluator reads one N-Triples dump of the store anddiff --git a/src/inputs.rs b/src/inputs.rsindex ee4ad135..904d15cc 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -258,6 +258,17 @@ pub struct OntoShaclInput {/// Temporal scoping is not applied on this path and a scope argument/// alongside it is refused rather than silently ignored.pub verified: Option<bool>,+ /// `"json"` (the default), `"turtle"` or `"ntriples"`. The RDF forms are a+ /// W3C `sh:ValidationReport` graph carrying `sh:conforms` and, per result,+ /// `sh:focusNode`, `sh:resultPath`, `sh:value`, `sh:sourceShape`,+ /// `sh:sourceConstraintComponent`, `sh:resultSeverity` and+ /// `sh:resultMessage`, so the report can be loaded into a store or+ /// compared with pyshacl's or Jena's. An undetermined run (`conforms:+ /// null`) is written `sh:conforms false` plus+ /// `<https://open-ontologies.org/shacl#undetermined> true` and its reason,+ /// never `sh:conforms true`. Refused with `verified: true`, whose report+ /// is a different structure.+ pub report_format: Option<String>,}#[derive(Deserialize, JsonSchema)]diff --git a/src/lib.rs b/src/lib.rsindex 903972fd..9f4066b9 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -111,6 +111,7 @@ pub mod schema;pub mod segment_retrieve;pub mod server;pub mod shacl;+pub mod shacl_report;pub mod shacl_verified;#[cfg(unix)]pub mod socket;diff --git a/src/main.rs b/src/main.rsindex 0f166502..caa45308 100644--- a/src/main.rs+++ b/src/main.rs@@ -489,6 +489,13 @@ enum Commands {/// impossible and dropping it would answer a different question.#[arg(long)]verified: bool,+ /// `json`, `turtle` or `ntriples`. The RDF forms are a W3C+ /// `sh:ValidationReport` graph. An undetermined run is written+ /// `sh:conforms false` plus `oo:undetermined true`, and the exit code+ /// is taken from the verdict, never from the text, so it is the same+ /// in every format.+ #[arg(long, default_value = "json")]+ report_format: String,},/// Closed-world vocab check: flag data terms not declared in the loaded ontologyVocabCheck { data: String },@@ -1310,13 +1317,19 @@ impl Commands {}cmd("trace-label", a)}+ // The batch runner answers in JSON, so an RDF report runs locally+ // rather than being proxied and coming back in the wrong format.Commands::Shacl {shapes,valid_at,as_of,all_versions,verified,+ report_format,} => {+ if report_format != "json" {+ return None;+ }let mut a = vec![absolutize(shapes)];if let Some(v) = valid_at {a.push("--valid-at".into());@@ -3174,8 +3187,31 @@ async fn async_main() -> anyhow::Result<()> {as_of,all_versions,verified,+ report_format,} => {use open_ontologies::shacl::ShaclValidator;+ use open_ontologies::shacl_report::ReportFormat;+ let format = match ReportFormat::parse(Some(&report_format)) {+ Ok(f) => f,+ Err(e) => {+ output_result_gated(&serde_json::json!({"error": e}).to_string(), cli.pretty, Gate::Shacl);+ return Ok(());+ }+ };+ // Refused before the store is opened: nothing here needs it.+ if verified && format != ReportFormat::Json {+ output_result_gated(+ &serde_json::json!({"error":+ "--verified cannot be combined with --report-format other than json. \+ The verified evaluator returns its own report structure, which the \+ sh:ValidationReport writer does not read, so the format would be \+ silently dropped."})+ .to_string(),+ cli.pretty,+ Gate::Shacl,+ );+ return Ok(());+ }let (_db, graph) = setup(&cli.data_dir)?;let shapes_content = std::fs::read_to_string(&shapes)?;if verified {@@ -3197,16 +3233,45 @@ async fn async_main() -> anyhow::Result<()> {output_result_gated(&result.to_string(), cli.pretty, Gate::Shacl);return Ok(());}- let result = match open_ontologies::temporal::ScopeRequest::from_args(+ let report = open_ontologies::temporal::ScopeRequest::from_args(valid_at.as_deref(),as_of.as_deref(),all_versions,- ) {- Ok(request) => ShaclValidator::validate_scoped(&graph, &shapes_content, &request)- .unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string()),- Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),+ )+ .and_then(|request| ShaclValidator::report_scoped(&graph, &shapes_content, &request));+ let report = match report {+ Ok(r) => r,+ Err(e) => {+ output_result_gated(+ &serde_json::json!({"error": e.to_string()}).to_string(),+ cli.pretty,+ Gate::Shacl,+ );+ return Ok(());+ }};- output_result_gated(&result, cli.pretty, Gate::Shacl);+ if format == ReportFormat::Json {+ output_result_gated(&report.to_json_string(), cli.pretty, Gate::Shacl);+ return Ok(());+ }+ // The code comes from the JSON verdict through the same mapping+ // every format uses (#329), not from the Turtle: a graph has no+ // `conforms` key, and `sh:conforms false` is written for both a+ // failing run and an undetermined one, which exit 1 and 2.+ let code = gate_exit_code(Gate::Shacl, &report.to_json_string());+ match report.render(format) {+ Ok(rdf) => {+ print!("{rdf}");+ if code != 0 {+ std::process::exit(code);+ }+ }+ Err(e) => output_result_gated(+ &serde_json::json!({"error": e.to_string()}).to_string(),+ cli.pretty,+ Gate::Shacl,+ ),+ }}Commands::VocabCheck { data } => {let (_db, graph) = setup(&cli.data_dir)?;@@ -4042,13 +4107,13 @@ mod proxy_serialization_tests {Commands::Fol { out: "/tmp/fol".into(), format: "tptp".into(), smt_domain: None, clif_dialect: "iso".into(), clif_comments: "standalone".into(), goals: None, goals_skip_columns: 0 },Commands::FolModel { out: "/tmp/folmodel".into(), solver: "z3".into(), max_domain: 16, timeout_secs: 30, unbounded_probe: true, goals: None, goals_skip_columns: 0, checker: None },Commands::FolProve { out: Some("/tmp/folprove".into()), prover: "vampire".into(), timeout_secs: 30, goals: None, goals_skip_columns: 0, problem: None, proof: None },- Commands::Shacl { shapes: "s.ttl".into(), valid_at: None, as_of: None, all_versions: false, verified: false },- Commands::Shacl { shapes: "s.ttl".into(), valid_at: None, as_of: None, all_versions: true, verified: false },+ Commands::Shacl { shapes: "s.ttl".into(), valid_at: None, as_of: None, all_versions: false, verified: false, report_format: "json".into() },+ Commands::Shacl { shapes: "s.ttl".into(), valid_at: None, as_of: None, all_versions: true, verified: false, report_format: "json".into() },// The verified form proxies too, for the reason the scoped `reason`// form above is here: a daemon-backed `shacl --verified` that// silently dropped the flag would run the UNVERIFIED evaluator and// answer with a conformance verdict that no theorem stands behind.- Commands::Shacl { shapes: "s.ttl".into(), valid_at: None, as_of: None, all_versions: false, verified: true },+ Commands::Shacl { shapes: "s.ttl".into(), valid_at: None, as_of: None, all_versions: false, verified: true, report_format: "json".into() },Commands::Status,Commands::Pull { url: "http://example.org".into(), sparql: false, query: None },Commands::Push { endpoint: "http://example.org".into(), graph: None },diff --git a/src/server.rs b/src/server.rsindex 74aa315f..9246e7e1 100644--- a/src/server.rs+++ b/src/server.rs@@ -1368,7 +1368,7 @@ impl OpenOntologiesServer {result.to_string()}- #[tool(name = "onto_shacl", description = "Validate the loaded ontology data against SHACL shapes. Checks the core constraint components written under `sh:property`, including `sh:minCount`, `sh:maxCount`, `sh:datatype`, `sh:class`, `sh:nodeKind`, `sh:pattern`, `sh:in`, `sh:hasValue`, `sh:or` and `sh:not`, plus `sh:sparql`. A constraint it cannot execute is listed in `skipped_constraints` and the verdict is null rather than true. An entry there is one CONSTRAINT-EVALUATION SITE and not one shape: a single `sh:property` block carrying both `sh:minCount` and `sh:node` can produce a violation from the first and a skip entry from the second, so the SAME shape can appear in `violations` and in `skipped_constraints` at once and that is not a contradiction. Every entry names the `shape` it was written on and the `constraint` predicate that was not evaluated, which is what separates a constraint that did not run from one that ran and selected nothing. Returns a conformance report with violations, `focus_nodes` and `unmatched_shapes`, plus `scope`, which names the graphs the run READ. By default every graph in the store is read. Over a store that describes its named graphs with the temporal vocabulary (https://open-ontologies.org/temporal#) that union is a state that held at no instant, so a run with no instant named is REFUSED rather than answered: pass `valid_at` (what was TRUE then), `as_of` (what was KNOWN then) or `all_versions: true` to say the union is what you meant. A scoped run evaluates every data-side query, `sh:sparql` included, against the in-scope named graphs plus the default graph and nothing else. A snapshot that selects no graph returns `conforms: null` with its own reason rather than conforming vacuously. Class and property DECLARATION lookups are never scoped: a declaration is context-free and has the same answer at every instant.")]+ #[tool(name = "onto_shacl", description = "Validate the loaded ontology data against SHACL shapes. Checks the core constraint components written under `sh:property`, including `sh:minCount`, `sh:maxCount`, `sh:datatype`, `sh:class`, `sh:nodeKind`, `sh:pattern`, `sh:in`, `sh:hasValue`, `sh:or` and `sh:not`, plus `sh:sparql`. A constraint it cannot execute is listed in `skipped_constraints` and the verdict is null rather than true. An entry there is one CONSTRAINT-EVALUATION SITE and not one shape: a single `sh:property` block carrying both `sh:minCount` and `sh:node` can produce a violation from the first and a skip entry from the second, so the SAME shape can appear in `violations` and in `skipped_constraints` at once and that is not a contradiction. Every entry names the `shape` it was written on and the `constraint` predicate that was not evaluated, which is what separates a constraint that did not run from one that ran and selected nothing. Returns a conformance report with violations, `focus_nodes` and `unmatched_shapes`, plus `scope`, which names the graphs the run READ. By default every graph in the store is read. Over a store that describes its named graphs with the temporal vocabulary (https://open-ontologies.org/temporal#) that union is a state that held at no instant, so a run with no instant named is REFUSED rather than answered: pass `valid_at` (what was TRUE then), `as_of` (what was KNOWN then) or `all_versions: true` to say the union is what you meant. A scoped run evaluates every data-side query, `sh:sparql` included, against the in-scope named graphs plus the default graph and nothing else. A snapshot that selects no graph returns `conforms: null` with its own reason rather than conforming vacuously. Class and property DECLARATION lookups are never scoped: a declaration is context-free and has the same answer at every instant. `report_format: \"turtle\"` or `\"ntriples\"` returns a W3C sh:ValidationReport graph instead of JSON; an undetermined run is written sh:conforms false plus oo:undetermined true, never sh:conforms true.")]async fn onto_shacl(&self, Parameters(input): Parameters<OntoShaclInput>) -> String {use crate::shacl::ShaclValidator;let shapes = if input.inline.unwrap_or(false) {@@ -1379,7 +1379,20 @@ impl OpenOntologiesServer {Err(e) => return Self::err_json(format!("Cannot read shapes file: {}", e)),}};+ let format = match crate::shacl_report::ReportFormat::parse(input.report_format.as_deref()) {+ Ok(f) => f,+ Err(e) => return Self::err_json(e),+ };if input.verified.unwrap_or(false) {+ if format != crate::shacl_report::ReportFormat::Json {+ return Self::err_json(+ "verified: true cannot be combined with a report_format other than json. \+ The verified evaluator returns its own report structure, which the \+ sh:ValidationReport writer does not read, so the format would be silently \+ dropped."+ .to_string(),+ );+ }// 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@@ -1406,7 +1419,8 @@ impl OpenOntologiesServer {Ok(r) => r,Err(e) => return Self::err_json(e),};- ShaclValidator::validate_scoped(&self.graph, &shapes, &request)+ ShaclValidator::report_scoped(&self.graph, &shapes, &request)+ .and_then(|report| report.render(format)).unwrap_or_else(Self::err_json)}diff --git a/src/shacl.rs b/src/shacl.rsindex 5cc4f0ef..132abd5c 100644--- a/src/shacl.rs+++ b/src/shacl.rs@@ -47,6 +47,46 @@ use std::sync::Arc;/// form selected the shape, and suppress the verdict.pub struct ShaclValidator;+/// One run's report, before it is written out in any format.+///+/// The verdict is read from here and not from the text: the CLI's exit code is+/// a function of `conforms`, and a Turtle report has no `conforms` key to read+/// (`gate_exit_code` in `src/main.rs`, #329).+pub struct ShaclReport {+ /// The JSON report, with each violation's [`RdfTerms`] still attached.+ report: serde_json::Value,+}++impl ShaclReport {+ /// The three-valued verdict: `Some(true)` conforms, `Some(false)` does+ /// not, `None` undetermined.+ pub fn conforms(&self) -> Option<bool> {+ self.report["conforms"].as_bool()+ }++ /// The JSON report exactly as `onto_shacl` has always returned it.+ pub fn to_json_string(&self) -> String {+ let mut report = self.report.clone();+ if let Some(vs) = report["violations"].as_array_mut() {+ for v in vs {+ if let Some(obj) = v.as_object_mut() {+ obj.remove(crate::shacl_report::RDF_TERMS_KEY);+ }+ }+ }+ report.to_string()+ }++ /// The report in `format`. JSON is [`to_json_string`](Self::to_json_string);+ /// Turtle and N-Triples are a W3C `sh:ValidationReport` graph.+ pub fn render(&self, format: crate::shacl_report::ReportFormat) -> anyhow::Result<String> {+ match format {+ crate::shacl_report::ReportFormat::Json => Ok(self.to_json_string()),+ rdf => crate::shacl_report::to_rdf(&self.report, rdf),+ }+ }+}+impl ShaclValidator {/// Validate the data in `graph` against SHACL shapes (inline Turtle)./// Returns a JSON report: `{conforms, violation_count, violations[]}`.@@ -58,6 +98,16 @@ impl ShaclValidator {/// predate those (`constraint`, `focus_node`, `message`, `severity`,/// `path`) are unchanged.///+ /// `value` is the offending value node (`sh:value`) wherever the query+ /// that found the violation binds it (#318). The value queries selected it+ /// all along and the report dropped it, so whoever repaired the data had to+ /// query the store again for what the validator already knew. It is absent+ /// where SHACL gives a result no value (`sh:minCount`, `sh:maxCount`,+ /// `sh:hasValue`, the qualified counts) and for `sh:lessThan`,+ /// `sh:lessThanOrEquals` and `sh:node`, whose queries select+ /// `DISTINCT ?focus`: projecting the value there would change how many+ /// results they emit, which is a different change from this one.+ ////// Reads the whole store. Over a store that uses the temporal vocabulary/// that is now REFUSED rather than done silently — see/// [`validate_scoped`](Self::validate_scoped), which this delegates to.@@ -91,6 +141,17 @@ impl ShaclValidator {shapes_ttl: &str,request: &ScopeRequest,) -> anyhow::Result<String> {+ Ok(Self::report_scoped(graph, shapes_ttl, request)?.to_json_string())+ }++ /// [`validate_scoped`](Self::validate_scoped), returned as a+ /// [`ShaclReport`] so the caller can choose the serialisation (#318) and+ /// read the verdict without parsing whichever one it chose.+ pub fn report_scoped(+ graph: &Arc<GraphStore>,+ shapes_ttl: &str,+ request: &ScopeRequest,+ ) -> anyhow::Result<ShaclReport> {let (scope, manifest) = crate::temporal::resolve(graph, request)?;Self::validate_in_scope(graph, shapes_ttl, &scope, &manifest)}@@ -100,7 +161,7 @@ impl ShaclValidator {shapes_ttl: &str,scope: &ReadScope,manifest: &ScopeManifest,- ) -> anyhow::Result<String> {+ ) -> anyhow::Result<ShaclReport> {// 1. Parse shapes Turtle into a temporary storelet shapes_store = Store::new()?;let reader = Cursor::new(shapes_ttl.as_bytes());@@ -474,6 +535,10 @@ impl ShaclValidator {}).unwrap_or_else(|| "Violation".to_string());let own_flags = pick("flags").map(|f| strip_quotes(&f));+ let own_rdf = RdfTerms::new(+ pick("severity"),+ pick("message").filter(|_| !own_message.is_empty()),+ );// (constraint, SPARQL test that is TRUE for a violating focus node, default message)let mut checks: Vec<(String, String, String)> = Vec::new();@@ -602,12 +667,21 @@ impl ShaclValidator {for row in &graph_sparql_select(graph, scope, &query)? {if let Some(focus) = row.get("focus") {let msg = if own_message.is_empty() { default_msg.clone() } else { own_message.clone() };- violations.push(attribute(&shape_iri, &shape_iri, serde_json::json!({+ let mut v = serde_json::json!({"severity": own_severity,"focus_node": strip_angle_brackets(focus),"constraint": constraint,"message": msg,- })));+ });+ // The value node of a node shape is the focus node+ // (SHACL 2.1.2), so every result here names it as+ // `value`, except `sh:hasValue`: SHACL 4.8.2 reports the+ // ABSENCE of a term and gives the result no value,+ // and W3C core/node/hasValue-001 expects none.+ if constraint != "hasValue" {+ v["value"] = serde_json::json!(strip_angle_brackets(focus));+ }+ violations.push(attribute(&shape_iri, &shape_iri, &own_rdf, v));}}}@@ -1019,7 +1093,7 @@ impl ShaclValidator {.collect();members.sort();let disjunction = members.join(" || ");- let node_message = query_solutions(+ let node_message_term = query_solutions(&shapes_store,&format!(r#"PREFIX sh: <http://www.w3.org/ns/shacl#>@@ -1028,8 +1102,13 @@ impl ShaclValidator {),)?.first()- .and_then(|r| r.get("m").map(|m| strip_quotes(m)))- .unwrap_or_default();+ .and_then(|r| r.get("m").cloned());+ let node_message =+ node_message_term.as_deref().map(strip_quotes).unwrap_or_default();+ let node_or_rdf = RdfTerms::new(+ None,+ node_message_term.filter(|_| !node_message.is_empty()),+ );let query = format!(r#"SELECT DISTINCT ?focus WHERE {{{focus_pattern}@@ -1043,9 +1122,10 @@ impl ShaclValidator {} else {node_message.clone()};- violations.push(attribute(&shape_iri, &shape_iri, serde_json::json!({+ violations.push(attribute(&shape_iri, &shape_iri, &node_or_rdf, serde_json::json!({"severity": "Violation","focus_node": strip_angle_brackets(focus),+ "value": strip_angle_brackets(focus),"constraint": "or","message": msg,})));@@ -1111,6 +1191,10 @@ impl ShaclValidator {.to_string()}).unwrap_or_else(|| "Violation".to_string());+ let q_rdf = RdfTerms::new(+ row.get("severity").cloned(),+ row.get("message").cloned().filter(|_| !q_message.is_empty()),+ );let clause = if row.get("other").is_some() {None@@ -1170,7 +1254,7 @@ impl ShaclValidator {} else {q_message.clone()};- violations.push(attribute(&q_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&q_shape, &shape_iri, &q_rdf, serde_json::json!({"severity": q_severity,"focus_node": strip_angle_brackets(focus),"path": q_path,@@ -1260,6 +1344,10 @@ impl ShaclValidator {s.rsplit('#').next().unwrap_or("Violation").to_string()}).unwrap_or_else(|| "Violation".to_string());+ let rdf = RdfTerms::new(+ prop.get("severity").cloned(),+ prop.get("message").cloned().filter(|_| !message.is_empty()),+ );// sh:minCountif let Some(min_count_str) = prop.get("minCount") {@@ -1284,7 +1372,7 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),"path": path,@@ -1318,7 +1406,7 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),"path": path,@@ -1353,9 +1441,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": "class","message": msg,@@ -1424,9 +1513,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": "datatype","message": msg,@@ -1456,9 +1546,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": "pattern","message": msg,@@ -1498,9 +1589,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": "or","message": msg,@@ -1544,9 +1636,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": constraint,"message": msg,@@ -1587,7 +1680,7 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),"path": path,@@ -1623,7 +1716,7 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),"path": path,@@ -1665,9 +1758,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": "not","message": msg,@@ -1696,9 +1790,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": "in","message": msg,@@ -1741,9 +1836,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": "nodeKind","message": msg,@@ -1780,7 +1876,7 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),"path": path,@@ -1824,9 +1920,10 @@ impl ShaclValidator {} else {message.clone()};- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ violations.push(attribute(&constraint_shape, &shape_iri, &rdf, serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(focus),+ "value": row.get("val").map(|v| strip_angle_brackets(v)),"path": path,"constraint": key,"message": msg,@@ -2029,17 +2126,22 @@ impl ShaclValidator {// 5.3.2 again: a bound ?message overrides// sh:message, ?path is sh:resultPath and// ?value is sh:value.- let msg = row+ let bound_message = row.get("message")- .map(|m| strip_quotes(m))- .filter(|m| !m.is_empty())- .unwrap_or_else(|| {- if message.is_empty() {- "SPARQL constraint violated".to_string()- } else {- message.clone()- }- });+ .filter(|m| !strip_quotes(m).is_empty());+ let msg = bound_message.map(|m| strip_quotes(m)).unwrap_or_else(|| {+ if message.is_empty() {+ "SPARQL constraint violated".to_string()+ } else {+ message.clone()+ }+ });+ let rdf = RdfTerms::new(+ constraint.get("severity").cloned(),+ bound_message.cloned().or_else(|| {+ constraint.get("message").cloned().filter(|_| !message.is_empty())+ }),+ );let mut v = serde_json::json!({"severity": severity,"focus_node": strip_angle_brackets(&focus_str),@@ -2052,7 +2154,7 @@ impl ShaclValidator {if let Some(val) = row.get("value") {v["value"] = serde_json::json!(strip_angle_brackets(val));}- violations.push(attribute(&shape_iri, &shape_iri, v));+ violations.push(attribute(&shape_iri, &shape_iri, &rdf, v));}}}@@ -2162,7 +2264,7 @@ impl ShaclValidator {if !skipped.is_empty() {report["skipped_constraints"] = serde_json::Value::Array(skipped);}- return Ok(report.to_string());+ return Ok(ShaclReport { report });}if nothing_matched && skipped.is_empty() {// Every shape targeted a class with no instances in the data, so@@ -2195,7 +2297,7 @@ impl ShaclValidator {});}- Ok(report.to_string())+ Ok(ShaclReport { report })}/// Structural dry-run check on proposed SHACL shapes.@@ -3046,7 +3148,16 @@ fn prebinding_violation(query: &str, var: &str) -> Option<String> {/// here, and this now agrees with it. The enclosing node shape is still/// reported, under `node_shape`, because it is what selected the focus node/// and a consumer that wants to group by rule set needs it.-fn attribute(source_shape: &str, node_shape: &str, mut v: serde_json::Value) -> serde_json::Value {+fn attribute(+ source_shape: &str,+ node_shape: &str,+ rdf: &RdfTerms,+ mut v: serde_json::Value,+) -> serde_json::Value {+ v[crate::shacl_report::RDF_TERMS_KEY] = serde_json::json!({+ "severity": rdf.severity,+ "message": rdf.message,+ });v["source_shape"] = serde_json::Value::String(strip_angle_brackets(source_shape));v["node_shape"] = serde_json::Value::String(strip_angle_brackets(node_shape));let constraint = v["constraint"].as_str().unwrap_or("").to_string();@@ -3060,6 +3171,34 @@ fn attribute(source_shape: &str, node_shape: &str, mut v: serde_json::Value) ->v}+/// The shapes-graph terms a result was built from, in the N-Triples form the+/// store printed them, for the RDF report and for nothing else.+///+/// The JSON report keeps a reduced form of both and cannot be changed without+/// breaking its readers: `severity` is the IRI's local name and `message` is+/// the literal's lexical value. Neither reduction is reversible. W3C+/// `core/misc/severity-002` declares `sh:severity ex:MySeverity`, which the+/// JSON carries as `"MySeverity"` and a writer reading it back can only guess+/// the namespace of; `core/misc/message-001` declares `"Test message"@en`, and+/// the language tag is gone. SHACL 3.6.2 makes `sh:resultSeverity` the shape's+/// `sh:severity` and `sh:resultMessage` a copy of its `sh:message`, so the+/// writer needs the terms as written. They travel inside each violation under+/// [`crate::shacl_report::RDF_TERMS_KEY`] and the JSON renderer removes them.+///+/// `message` is `None` whenever the result carries this engine's default text,+/// which is then written as a plain string. `severity` is `None` where SHACL's+/// default `sh:Violation` applies.+struct RdfTerms {+ severity: Option<String>,+ message: Option<String>,+}++impl RdfTerms {+ fn new(severity: Option<String>, message: Option<String>) -> Self {+ Self { severity, message }+ }+}+/// The `sh:*ConstraintComponent` IRI for the short constraint name a violation/// carries in `constraint`. Every W3C core component is the parameter name with/// its first letter capitalised, except SPARQL.diff --git a/src/shacl_report.rs b/src/shacl_report.rsnew file mode 100644index 00000000..66984923--- /dev/null+++ b/src/shacl_report.rs@@ -0,0 +1,231 @@+//! The W3C `sh:ValidationReport` graph for a SHACL run (#318).+//!+//! `onto_shacl` answered only in its own JSON. pyshacl, Jena and TopBraid all+//! read and write the report graph SHACL 3.6 defines, so a JSON report could+//! not be loaded into a store, queried, or compared with another engine's+//! report, and the W3C suite's full-compliance level (a report isomorphic to+//! the expected one) could not be measured at all. This module writes that+//! graph from the report [`crate::shacl::ShaclValidator`] already builds; it+//! evaluates nothing itself.+//!+//! Each result carries `sh:focusNode`, `sh:resultPath`, `sh:value`,+//! `sh:sourceShape`, `sh:sourceConstraintComponent`, `sh:resultSeverity` and+//! `sh:resultMessage`, wherever the JSON violation has the corresponding field.+//! `sh:value` is absent for the components SHACL defines without one+//! (`sh:minCount`, `sh:maxCount`, `sh:hasValue`, the qualified counts) and for+//! the two whose query does not project the value node (`sh:lessThan`,+//! `sh:lessThanOrEquals`, `sh:node`), which select `DISTINCT ?focus` and would+//! change how many results they emit if they projected it.++use oxigraph::io::{RdfFormat, RdfSerializer};+use oxigraph::model::{BlankNode, Literal, NamedNode, NamedOrBlankNode, Term, Triple};++const SH: &str = "http://www.w3.org/ns/shacl#";+const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";+const XSD: &str = "http://www.w3.org/2001/XMLSchema#";++/// The namespace of the two non-standard terms an undetermined run carries.+pub const OO_SHACL: &str = "https://open-ontologies.org/shacl#";++/// Key, inside each JSON violation, of the shapes-graph terms only this writer+/// reads. See `RdfTerms` in `src/shacl.rs` for why they cannot be recovered+/// from the JSON fields; `ShaclReport::to_json_string` removes the key.+pub(crate) const RDF_TERMS_KEY: &str = "_rdf_terms";++/// How a SHACL report is written out.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ReportFormat {+ /// The engine's own JSON, unchanged apart from `value` (#318).+ Json,+ /// A W3C `sh:ValidationReport` graph in Turtle.+ Turtle,+ /// The same graph in N-Triples.+ NTriples,+}++impl ReportFormat {+ /// Read `report_format` as `onto_shacl` and the `shacl` command take it.+ /// Absent means JSON, which is what every caller got before the option+ /// existed. Anything else is refused by name rather than defaulted, since+ /// a misspelt `"tutle"` answered in JSON is a caller parsing the wrong+ /// format without being told.+ pub fn parse(value: Option<&str>) -> Result<Self, String> {+ match value {+ None | Some("json") => Ok(Self::Json),+ Some("turtle") => Ok(Self::Turtle),+ Some("ntriples") => Ok(Self::NTriples),+ Some(other) => Err(format!(+ "report_format must be \"json\", \"turtle\" or \"ntriples\"; got {other:?}"+ )),+ }+ }+}++/// Write `report` (the validator's JSON, with its `_rdf_terms` still attached)+/// as a `sh:ValidationReport` graph.+///+/// # `conforms: null` is written `sh:conforms false` plus `oo:undetermined true`+///+/// The engine has three answers and the report vocabulary has two. The two+/// alternatives the ticket allowed were refusing the RDF form, or writing+/// `sh:conforms false` with a named marker. This writes the marker, for these+/// reasons:+///+/// * `sh:conforms true` is ruled out: it is the false clean the third answer+/// exists to prevent, and a consumer reading only `sh:conforms` would see a+/// pass for constraints that never ran.+/// * Leaving `sh:conforms` out, or giving it a non-boolean, is not a report.+/// SHACL 3.6.1 requires exactly one `sh:conforms` of type `xsd:boolean`, and+/// a strict reader rejects the graph, which is a refusal with a worse message.+/// * Refusing throws away results that WERE found. An undetermined run is not+/// an empty one: a skipped `sh:closed` on one shape suppresses the verdict+/// while another shape's `sh:datatype` violations stand, and those are what+/// someone repairing the data needs. It would also make the RDF form fail on+/// exactly the runs the CLI answers with exit code 2 and a full report.+/// * `false` fails closed. Every consumer that reads `sh:conforms` alone+/// (dashboards, pyshacl-shaped CI checks) treats the run as not passing,+/// which agrees with the non-zero exit code. The cost is stated rather than+/// hidden: SHACL defines `false` as "there are results", and an undetermined+/// run with no results breaks that reading. `oo:undetermined true` and+/// `oo:undeterminedReason` (the JSON `warning`) say so in the graph, so a+/// reader that knows to look can tell "failed" from "not decided".+pub fn to_rdf(report: &serde_json::Value, format: ReportFormat) -> anyhow::Result<String> {+ let rdf_format = match format {+ ReportFormat::Turtle => RdfFormat::Turtle,+ ReportFormat::NTriples => RdfFormat::NTriples,+ ReportFormat::Json => anyhow::bail!("to_rdf writes an RDF format; JSON is the report itself"),+ };+ let triples = report_triples(report)?;+ let mut serializer = RdfSerializer::from_format(rdf_format);+ if rdf_format == RdfFormat::Turtle {+ serializer = serializer+ .with_prefix("sh", SH)?+ .with_prefix("xsd", XSD)?+ .with_prefix("oo", OO_SHACL)?;+ }+ let mut writer = serializer.for_writer(Vec::new());+ for t in &triples {+ writer.serialize_triple(t)?;+ }+ Ok(String::from_utf8(writer.finish()?)?)+}++fn sh(local: &str) -> NamedNode {+ NamedNode::new_unchecked(format!("{SH}{local}"))+}++/// A term from the JSON report. The validator strips the angle brackets off+/// IRIs and leaves blank nodes (`_:id`) and literals (`"lex"^^<dt>`) in+/// N-Triples form, and an absolute IRI can start with neither `"` nor `_:`+/// (its scheme starts with a letter), so the three are told apart without+/// guessing.+fn term(s: &str) -> anyhow::Result<Term> {+ let s = s.trim();+ if s.starts_with('"') || s.starts_with("_:") || s.starts_with('<') {+ s.parse::<Term>()+ .map_err(|e| anyhow::anyhow!("report term {s:?} does not read back as RDF: {e}"))+ } else {+ Ok(NamedNode::new(s)+ .map_err(|e| anyhow::anyhow!("report IRI {s:?} is not an IRI: {e}"))?+ .into())+ }+}++fn report_triples(report: &serde_json::Value) -> anyhow::Result<Vec<Triple>> {+ let mut out = Vec::new();+ let node: NamedOrBlankNode = BlankNode::default().into();+ out.push(Triple::new(node.clone(), NamedNode::new_unchecked(RDF_TYPE), sh("ValidationReport")));++ let conforms = report["conforms"].as_bool();+ // `None` is written as `false`: see `to_rdf` for the decision and why.+ out.push(Triple::new(node.clone(), sh("conforms"), Literal::from(conforms == Some(true))));+ if conforms.is_none() {+ out.push(Triple::new(+ node.clone(),+ NamedNode::new_unchecked(format!("{OO_SHACL}undetermined")),+ Literal::from(true),+ ));+ if let Some(reason) = report["warning"].as_str() {+ out.push(Triple::new(+ node.clone(),+ NamedNode::new_unchecked(format!("{OO_SHACL}undeterminedReason")),+ Literal::new_simple_literal(reason),+ ));+ }+ }++ for v in report["violations"].as_array().map(Vec::as_slice).unwrap_or_default() {+ let r: NamedOrBlankNode = BlankNode::default().into();+ out.push(Triple::new(node.clone(), sh("result"), r.clone()));+ out.push(Triple::new(r.clone(), NamedNode::new_unchecked(RDF_TYPE), sh("ValidationResult")));+ if let Some(f) = v["focus_node"].as_str() {+ out.push(Triple::new(r.clone(), sh("focusNode"), term(f)?));+ }+ if let Some(p) = v["result_path"].as_str() {+ // `^p` is how the validator prints `sh:inversePath p`, and SHACL+ // 2.3.1 writes it as a blank node carrying that one triple.+ match p.strip_prefix('^') {+ Some(inv) => {+ let path: NamedOrBlankNode = BlankNode::default().into();+ out.push(Triple::new(r.clone(), sh("resultPath"), path.clone()));+ out.push(Triple::new(path, sh("inversePath"), term(inv)?));+ }+ None => out.push(Triple::new(r.clone(), sh("resultPath"), term(p)?)),+ }+ }+ if let Some(val) = v["value"].as_str() {+ out.push(Triple::new(r.clone(), sh("value"), term(val)?));+ }+ if let Some(s) = v["source_shape"].as_str() {+ out.push(Triple::new(r.clone(), sh("sourceShape"), term(s)?));+ }+ if let Some(c) = v["source_constraint_component"].as_str() {+ out.push(Triple::new(r.clone(), sh("sourceConstraintComponent"), term(c)?));+ }+ let terms = &v[RDF_TERMS_KEY];+ let severity = match terms["severity"].as_str() {+ Some(s) => term(s)?,+ None => sh("Violation").into(),+ };+ out.push(Triple::new(r.clone(), sh("resultSeverity"), severity));+ let message = match (terms["message"].as_str(), v["message"].as_str()) {+ (Some(written), _) => Some(term(written)?),+ (None, Some(default)) => Some(Literal::new_simple_literal(default).into()),+ (None, None) => None,+ };+ if let Some(m) = message {+ out.push(Triple::new(r, sh("resultMessage"), m));+ }+ }+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn an_unknown_format_is_refused_by_name() {+ let e = ReportFormat::parse(Some("tutle")).unwrap_err();+ assert!(e.contains("tutle") && e.contains("turtle"), "{e}");+ assert_eq!(ReportFormat::parse(None), Ok(ReportFormat::Json));+ assert_eq!(ReportFormat::parse(Some("ntriples")), Ok(ReportFormat::NTriples));+ }++ #[test]+ fn an_inverse_path_is_written_as_sh_inverse_path() {+ let report = serde_json::json!({+ "conforms": false,+ "violations": [{+ "focus_node": "http://ex/a",+ "result_path": "^http://ex/p",+ "source_shape": "http://ex/S",+ "source_constraint_component": "http://www.w3.org/ns/shacl#MinCountConstraintComponent",+ "message": "m",+ "_rdf_terms": {"severity": null, "message": null},+ }],+ });+ let nt = to_rdf(&report, ReportFormat::NTriples).unwrap();+ assert!(nt.contains("<http://www.w3.org/ns/shacl#inversePath> <http://ex/p>"), "{nt}");+ }+}diff --git a/tests/shacl_validation_report_test.rs b/tests/shacl_validation_report_test.rsnew file mode 100644index 00000000..dd011228--- /dev/null+++ b/tests/shacl_validation_report_test.rs@@ -0,0 +1,430 @@+//! `onto_shacl` and `shacl` write a W3C `sh:ValidationReport` graph (#318).+//!+//! Three things were missing. The default path's results had no value node:+//! the `sh:class`, `sh:datatype`, `sh:nodeKind` and `sh:pattern` queries+//! selected the offending value and dropped it, so someone repairing the data+//! had to query the store again for what the validator already knew. There was+//! no RDF form of the report at all, so it could not be loaded into a store or+//! compared with pyshacl's. And there was no decision about what an+//! undetermined run (`conforms: null`) becomes in a vocabulary whose+//! `sh:conforms` is a boolean: the one wrong answer is `true`.+//!+//! The W3C half of the acceptance is `tests/shacl_validation_report_w3c_test.rs`.++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::shacl::ShaclValidator;+use open_ontologies::shacl_report::ReportFormat;+use open_ontologies::temporal::ScopeRequest;+use oxigraph::io::{RdfFormat, RdfParser};+use oxigraph::sparql::{QueryResults, SparqlEvaluator};+use oxigraph::store::Store;+use serde_json::{Value, json};+use std::io::{BufRead, BufReader, Cursor, Write};+use std::path::Path;+use std::process::{Child, ChildStdin, Command, Stdio};+use std::sync::Arc;+use std::sync::mpsc::{Receiver, channel};+use std::time::Duration;++const PREFIXES: &str = "PREFIX sh: <http://www.w3.org/ns/shacl#> \+ PREFIX oo: <https://open-ontologies.org/shacl#> \+ PREFIX ex: <http://ex.org/> \+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> ";++const DATA: &str = r#"+@prefix ex: <http://ex.org/> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .+ex:alice a ex:Person ;+ ex:age "forty" ;+ ex:knows ex:rock ;+ ex:home "Leeds" ;+ ex:code "ab-1" .+ex:rock a ex:Stone .+"#;++/// One property shape per component, so each result is attributable.+const FOUR_COMPONENTS: &str = r#"+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix ex: <http://ex.org/> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .+ex:PersonShape a sh:NodeShape ;+ sh:targetClass ex:Person ;+ sh:property [ sh:path ex:age ; sh:datatype xsd:integer ] ;+ sh:property [ sh:path ex:knows ; sh:class ex:Person ] ;+ sh:property [ sh:path ex:home ; sh:nodeKind sh:IRI ] ;+ sh:property [ sh:path ex:code ; sh:pattern "^[0-9]+$" ] .+"#;++fn store(data: &str) -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(data, None).unwrap();+ g+}++fn json_report(data: &str, shapes: &str) -> Value {+ serde_json::from_str(&ShaclValidator::validate(&store(data), shapes).unwrap()).unwrap()+}++fn rdf_report(data: &str, shapes: &str, format: ReportFormat) -> String {+ ShaclValidator::report_scoped(&store(data), shapes, &ScopeRequest::Unscoped)+ .unwrap()+ .render(format)+ .unwrap()+}++fn parsed(text: &str, format: RdfFormat) -> Store {+ let s = Store::new().unwrap();+ for q in RdfParser::from_format(format).for_reader(Cursor::new(text.as_bytes())) {+ s.insert(&q.unwrap()).unwrap();+ }+ s+}++fn ask(s: &Store, pattern: &str) -> bool {+ let q = format!("{PREFIXES} ASK {{ {pattern} }}");+ match SparqlEvaluator::new().parse_query(&q).unwrap().on_store(s).execute().unwrap() {+ QueryResults::Boolean(b) => b,+ _ => unreachable!(),+ }+}++fn value_for(report: &Value, constraint: &str) -> Option<String> {+ report["violations"]+ .as_array()+ .unwrap()+ .iter()+ .find(|v| v["constraint"] == constraint)+ .and_then(|v| v["value"].as_str().map(str::to_string))+}++#[test]+fn value_is_reported_for_datatype_class_node_kind_and_pattern() {+ let r = json_report(DATA, FOUR_COMPONENTS);+ assert_eq!(r["violation_count"], 4, "{r}");+ assert_eq!(value_for(&r, "datatype").as_deref(), Some("\"forty\""), "{r}");+ assert_eq!(value_for(&r, "class").as_deref(), Some("http://ex.org/rock"), "{r}");+ assert_eq!(value_for(&r, "nodeKind").as_deref(), Some("\"Leeds\""), "{r}");+ assert_eq!(value_for(&r, "pattern").as_deref(), Some("\"ab-1\""), "{r}");+}++#[test]+fn a_node_shape_result_carries_the_focus_node_as_its_value() {+ // SHACL 2.1.2: the value node of a node shape is the focus node itself.+ let shapes = r#"+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix ex: <http://ex.org/> .+ex:S a sh:NodeShape ; sh:targetNode ex:alice ; sh:nodeKind sh:Literal .+"#;+ let r = json_report(DATA, shapes);+ assert_eq!(value_for(&r, "nodeKind").as_deref(), Some("http://ex.org/alice"), "{r}");+}++#[test]+fn the_json_report_changes_only_by_the_value_key() {+ let r = json_report(DATA, FOUR_COMPONENTS);+ let mut keys: Vec<String> = r["violations"][0].as_object().unwrap().keys().cloned().collect();+ keys.sort();+ assert_eq!(+ keys,+ [+ "constraint",+ "focus_node",+ "message",+ "node_shape",+ "path",+ "result_path",+ "severity",+ "source_constraint_component",+ "source_shape",+ "value",+ ],+ "the RDF writer's terms must not leak into the JSON: {r}"+ );+}++#[test]+fn the_turtle_report_carries_every_result_predicate() {+ let s = parsed(&rdf_report(DATA, FOUR_COMPONENTS, ReportFormat::Turtle), RdfFormat::Turtle);+ assert!(ask(&s, "?r a sh:ValidationReport ; sh:conforms false"));+ assert!(!ask(&s, "?r oo:undetermined ?u"), "a decided run carries no marker");+ assert!(ask(+ &s,+ r#"?r sh:result ?x . ?x a sh:ValidationResult ;+ sh:focusNode ex:alice ; sh:resultPath ex:age ; sh:value "forty" ;+ sh:sourceShape ?shape ;+ sh:sourceConstraintComponent sh:DatatypeConstraintComponent ;+ sh:resultSeverity sh:Violation ; sh:resultMessage ?m"#+ ));+ let n = parsed(&rdf_report(DATA, FOUR_COMPONENTS, ReportFormat::NTriples), RdfFormat::NTriples);+ assert!(ask(&n, "?x sh:value ex:rock ; sh:sourceConstraintComponent sh:ClassConstraintComponent"));+}++#[test]+fn a_conforming_run_is_sh_conforms_true() {+ let shapes = r#"+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix ex: <http://ex.org/> .+ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:knows ; sh:minCount 1 ] .+"#;+ let s = parsed(&rdf_report(DATA, shapes, ReportFormat::Turtle), RdfFormat::Turtle);+ assert!(ask(&s, "?r a sh:ValidationReport ; sh:conforms true"));+ assert!(!ask(&s, "?r sh:result ?x"));+}++/// A skipped constraint suppresses the verdict while another shape's+/// violation stands. The graph must not say `true`, must say why, and must+/// keep the violation that was found.+#[test]+fn an_undetermined_run_is_written_false_with_the_marker_and_keeps_its_results() {+ let shapes = r#"+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix ex: <http://ex.org/> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .+ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:age ; sh:datatype xsd:integer ] ;+ sh:property [ sh:path ex:home ; sh:minLength "three" ] .+"#;+ let j = json_report(DATA, shapes);+ assert!(j["conforms"].is_null(), "precondition: {j}");+ let s = parsed(&rdf_report(DATA, shapes, ReportFormat::Turtle), RdfFormat::Turtle);+ assert!(!ask(&s, "?r sh:conforms true"), "undetermined must never read as a pass");+ assert!(ask(&s, "?r sh:conforms false ; oo:undetermined true ; oo:undeterminedReason ?why"));+ assert!(ask(&s, r#"?r sh:result ?x . ?x sh:value "forty""#));+}++#[test]+fn an_undetermined_run_with_no_results_is_still_not_a_pass() {+ let shapes = r#"+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix ex: <http://ex.org/> .+ex:S a sh:NodeShape ; sh:targetClass ex:Nobody ;+ sh:property [ sh:path ex:age ; sh:minCount 1 ] .+"#;+ assert!(json_report(DATA, shapes)["conforms"].is_null());+ let s = parsed(&rdf_report(DATA, shapes, ReportFormat::NTriples), RdfFormat::NTriples);+ assert!(ask(&s, "?r sh:conforms false ; oo:undetermined true"));+ assert!(!ask(&s, "?r sh:conforms true"));+}++#[test]+fn a_custom_severity_iri_and_a_language_tag_survive_into_the_graph() {+ // The JSON keeps `"MySeverity"` and `"Too old"`; the graph needs the terms.+ let shapes = r#"+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix ex: <http://ex.org/> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .+@prefix sev: <http://ex.org/sev#> .+ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:age ; sh:datatype xsd:integer ;+ sh:severity sev:MySeverity ; sh:message "Too old"@en ] .+"#;+ let j = json_report(DATA, shapes);+ assert_eq!(j["violations"][0]["severity"], "MySeverity", "{j}");+ assert_eq!(j["violations"][0]["message"], "Too old", "{j}");+ let s = parsed(&rdf_report(DATA, shapes, ReportFormat::Turtle), RdfFormat::Turtle);+ assert!(ask(+ &s,+ r#"?x sh:resultSeverity <http://ex.org/sev#MySeverity> ; sh:resultMessage "Too old"@en"#+ ));+}++// ─────────────────────────────────────────────────────────────────────────────+// The command line+// ─────────────────────────────────────────────────────────────────────────────++fn run(dir: &Path, args: &[&str]) -> (i32, String) {+ let out = {+ let _gate = common::exec_gate();+ Command::new(env!("CARGO_BIN_EXE_open-ontologies"))+ .env("OPEN_ONTOLOGIES_STORAGE_MODE", "persistent")+ .arg("--data-dir")+ .arg(dir.join("data"))+ .arg("--no-connect")+ .args(args)+ .output()+ .expect("binary should run")+ };+ (+ out.status.code().unwrap_or(-1),+ format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)),+ )+}++fn write(dir: &Path, name: &str, body: &str) -> String {+ let p = dir.join(name);+ std::fs::write(&p, body).unwrap();+ p.to_str().unwrap().to_string()+}++fn loaded_store() -> tempfile::TempDir {+ let d = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(d.path().join("data")).unwrap();+ std::fs::write(d.path().join("data").join("config.toml"), "[storage]\nmode = 'persistent'\n")+ .unwrap();+ let data = write(d.path(), "data.ttl", DATA);+ let (code, out) = run(d.path(), &["load", &data]);+ assert_eq!(code, 0, "load failed: {out}");+ d+}++/// The exit code is the verdict's (#329) in every format. `sh:conforms false`+/// is written for both a failing and an undetermined run, so a code read off+/// the graph could not tell 1 from 2.+#[test]+fn cli_turtle_report_keeps_the_verdict_exit_codes() {+ let d = loaded_store();+ let failing = write(d.path(), "f.ttl", FOUR_COMPONENTS);+ let passing = write(+ d.path(),+ "p.ttl",+ "@prefix sh: <http://www.w3.org/ns/shacl#> . @prefix ex: <http://ex.org/> .+ ex:S a sh:NodeShape ; sh:targetNode ex:alice ; sh:property [ sh:path ex:knows ; sh:minCount 1 ] .",+ );+ let undetermined = write(+ d.path(),+ "u.ttl",+ "@prefix sh: <http://www.w3.org/ns/shacl#> . @prefix ex: <http://ex.org/> .+ ex:S a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:home ; sh:minLength \"three\" ] .",+ );+ for (shapes, format, rdf, code, conforms) in [+ (&failing, "turtle", RdfFormat::Turtle, 1, "false"),+ (&passing, "turtle", RdfFormat::Turtle, 0, "true"),+ (&undetermined, "turtle", RdfFormat::Turtle, 2, "false"),+ (&failing, "ntriples", RdfFormat::NTriples, 1, "false"),+ (&undetermined, "ntriples", RdfFormat::NTriples, 2, "false"),+ ] {+ let (got, out) = run(d.path(), &["shacl", shapes, "--report-format", format]);+ assert_eq!(got, code, "{format} over {shapes}: {out}");+ let s = parsed(&out, rdf);+ assert!(ask(&s, &format!("?r a sh:ValidationReport ; sh:conforms {conforms}")), "{out}");+ assert_eq!(ask(&s, "?r oo:undetermined true"), code == 2, "{out}");+ }+}++#[test]+fn cli_refuses_an_unknown_format_and_the_verified_combination() {+ let d = loaded_store();+ let shapes = write(d.path(), "f.ttl", FOUR_COMPONENTS);+ let (code, out) = run(d.path(), &["shacl", &shapes, "--report-format", "tutle"]);+ assert_eq!(code, 1, "{out}");+ assert!(out.contains("report_format must be"), "{out}");+ let (code, out) = run(d.path(), &["shacl", &shapes, "--verified", "--report-format", "turtle"]);+ assert_eq!(code, 1, "{out}");+ assert!(out.contains("cannot be combined"), "{out}");+}++#[tokio::test]+async fn a_batch_refuses_an_rdf_format_rather_than_answering_in_json() {+ let dir = tempfile::tempdir().unwrap();+ let shapes = write(dir.path(), "s.ttl", FOUR_COMPONENTS);+ let db = open_ontologies::state::StateDb::open(&dir.path().join("state.db")).unwrap();+ let runner = open_ontologies::batch::BatchRunner::new(db, store(DATA), false);+ let payload =+ json!([{"command": "shacl", "args": [shapes, "--report-format", "turtle"]}]).to_string();+ let (results, _) = runner.run_collect(&payload, false).await;+ let err = results[0]["result"]["error"].as_str().unwrap_or_default();+ assert!(err.contains("not available in a batch"), "{}", results[0]);+}++// ─────────────────────────────────────────────────────────────────────────────+// MCP+// ─────────────────────────────────────────────────────────────────────────────++struct McpChild {+ child: Child,+ input: ChildStdin,+ lines: Receiver<String>,+}++impl McpChild {+ fn start(state: &Path) -> Self {+ let mut child = Command::new(env!("CARGO_BIN_EXE_open-ontologies"))+ .args(["--no-connect", "--data-dir"])+ .arg(state)+ .arg("serve")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();+ let input = child.stdin.take().unwrap();+ let stdout = child.stdout.take().unwrap();+ let (send, lines) = channel();+ std::thread::spawn(move || {+ for line in BufReader::new(stdout).lines().map_while(Result::ok) {+ if send.send(line).is_err() {+ break;+ }+ }+ });+ Self { child, input, lines }+ }++ fn send(&mut self, message: Value) {+ writeln!(self.input, "{message}").unwrap();+ self.input.flush().unwrap();+ }++ fn request(&mut self, id: u64, method: &str, params: Value) -> Value {+ self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));+ loop {+ let line = self.lines.recv_timeout(Duration::from_secs(20)).expect("MCP response");+ let response: Value = serde_json::from_str(&line).unwrap();+ if response["id"] == id {+ assert!(response.get("error").is_none(), "{response}");+ return response["result"].clone();+ }+ }+ }++ fn tool_text(&mut self, id: u64, name: &str, arguments: Value) -> String {+ let r = self.request(id, "tools/call", json!({"name": name, "arguments": arguments}));+ r["content"][0]["text"].as_str().unwrap().to_string()+ }+}++impl Drop for McpChild {+ fn drop(&mut self) {+ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++#[test]+fn mcp_onto_shacl_exposes_report_format() {+ let dir = tempfile::tempdir().unwrap();+ let mut mcp = McpChild::start(&dir.path().join("state"));+ mcp.request(+ 1,+ "initialize",+ json!({"protocolVersion": "2025-03-26", "capabilities": {},+ "clientInfo": {"name": "shacl-report-test", "version": "1"}}),+ );+ mcp.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));+ let tools = mcp.request(2, "tools/list", json!({}));+ let shacl = tools["tools"].as_array().unwrap().iter().find(|t| t["name"] == "onto_shacl").unwrap();+ assert!(shacl["inputSchema"]["properties"]["report_format"].is_object(), "{shacl}");++ mcp.tool_text(3, "onto_load", json!({"turtle": DATA}));+ let ttl = mcp.tool_text(+ 4,+ "onto_shacl",+ json!({"shapes": FOUR_COMPONENTS, "inline": true, "report_format": "turtle"}),+ );+ let s = parsed(&ttl, RdfFormat::Turtle);+ assert!(ask(&s, r#"?r sh:conforms false ; sh:result ?x . ?x sh:value "forty""#), "{ttl}");++ let json_text = mcp.tool_text(5, "onto_shacl", json!({"shapes": FOUR_COMPONENTS, "inline": true}));+ let j: Value = serde_json::from_str(&json_text).unwrap();+ assert_eq!(j["conforms"], false, "the default is still JSON: {j}");++ let bad = mcp.tool_text(+ 6,+ "onto_shacl",+ json!({"shapes": FOUR_COMPONENTS, "inline": true, "report_format": "rdfxml"}),+ );+ assert!(bad.contains("report_format must be"), "{bad}");+}diff --git a/tests/shacl_validation_report_w3c_test.rs b/tests/shacl_validation_report_w3c_test.rsnew file mode 100644index 00000000..37cd1e55--- /dev/null+++ b/tests/shacl_validation_report_w3c_test.rs@@ -0,0 +1,377 @@+//! The Turtle validation report against the W3C suite's expected reports (#318).+//!+//! `tests/w3c_shacl_conformance_test.rs` compares the JSON report on the+//! verdict and the SET of (focus node, source shape, component) triples, and+//! says why it ignores `sh:resultPath`, `sh:value`, `sh:resultSeverity` and+//! multiplicity: comparing them needs graph isomorphism. This file is that+//! comparison. For every `core/` case the baseline records as PASS, the engine+//! writes `report_format: "turtle"`, the graph is parsed back, and both it and+//! the suite's `mf:result` are projected onto+//!+//! the report's `sh:conforms` and `sh:result`, and per result+//! `sh:focusNode`, `sh:resultPath` (with the blank-node path structure under+//! it), `sh:value`, `sh:sourceShape`, `sh:sourceConstraintComponent`,+//! `sh:resultSeverity` and `sh:resultMessage`,+//!+//! canonicalised with RDFC-1.0 (`src/canon.rs`) and compared as strings. Every+//! result is its own blank node, so a result emitted twice is two results and+//! multiplicity IS compared here.+//!+//! One rule comes from the suite rather than from this file. `sh:resultMessage`+//! is free text that the suite only pins where the expected report names it+//! (`core/misc/message-001` says so in its own comment: the harness "needs to+//! preserve all sh:resultMessage triples that are mentioned in the 'expected'+//! results graph"). So an actual message is kept when that same literal is an+//! expected `sh:resultMessage` in the test, and dropped otherwise. An expected+//! message the engine does not produce still fails.+//!+//! `rdf:type` on the report and on each result is not compared: it is not on+//! the ticket's predicate list and the writer always emits both.+//!+//! The gate is a floor on the number of matching cases, measured and+//! committed. It may rise; lowering it is a deliberate, reviewable edit.++mod common;++use open_ontologies::canon::{self, HashAlgorithm};+use open_ontologies::graph::GraphStore;+use open_ontologies::shacl::ShaclValidator;+use open_ontologies::shacl_report::ReportFormat;+use open_ontologies::temporal::ScopeRequest;+use oxigraph::io::{RdfFormat, RdfParser};+use oxigraph::model::{GraphName, NamedNode, NamedOrBlankNode, Quad, Term, Triple};+use std::collections::{BTreeSet, HashMap, HashSet};+use std::io::Cursor;+use std::path::{Path, PathBuf};+use std::sync::Arc;++/// Measured on 24 Oct 2026, suite commit 94d8bc2: 48 of the 56 core/ cases the+/// conformance baseline records as PASS produce a report that matches the+/// expected one on every compared predicate. The other eight are named below.+const MATCHED_FLOOR: usize = 48;++/// The PASS cases whose full report differs, each with the measured cause.+/// None is a defect of the report writer: each graph says what the JSON+/// already said. They are the gaps the set comparison in+/// `w3c_shacl_conformance_test.rs` cannot see, which is why this file exists.+/// A case not listed here that stops matching fails by name.+const KNOWN_DIFFERENCES: [(&str, &str); 8] = [+ (+ "core/node/class-003",+ "ex:John is selected by sh:targetClass AND sh:targetNode and reported once per target \+ declaration, the documented non-deduplication in src/shacl.rs: 6 results for 5",+ ),+ (+ "core/targets/targetSubjectsOf-002",+ "same cause: InvalidInstance1 is selected by sh:targetClass and sh:targetSubjectsOf and \+ reported twice, 3 results for 2",+ ),+ (+ "core/node/maxExclusive-001",+ "the store keeps xsd:decimal by value, so the data's \"4.0\"^^xsd:decimal comes back as \+ \"4\"^^xsd:decimal in sh:focusNode and sh:value",+ ),+ ("core/node/minExclusive-001", "same cause as maxExclusive-001"),+ (+ "core/property/lessThan-001",+ "the query selects DISTINCT ?focus, so results carry no sh:value; projecting it changes \+ the result count, which the JSON contract fixes",+ ),+ (+ "core/property/lessThanOrEquals-001",+ "same cause, and visible in the count: two failing values on one focus node give one \+ result where SHACL gives two",+ ),+ ("core/property/node-002", "sh:node selects DISTINCT ?focus, so no sh:value"),+ (+ "core/property/or-datatypes-001",+ "an ENGINE false negative: of the three sh:or violations only the integer is reported. \+ DATATYPE(owl:Thing) is a type error that drops the row inside FILTER, and \+ \"none\"^^xsd:boolean satisfies DATATYPE() = xsd:boolean though it is ill-typed. The \+ set comparison passes it because all three share one (focus, shape, component)",+ ),+];++const SUITE_BASE: &str = "https://w3c.github.io/data-shapes/data-shapes-test-suite/tests/";+const SH: &str = "http://www.w3.org/ns/shacl#";+const MF: &str = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#";+const SHT: &str = "http://www.w3.org/ns/shacl-test#";++const RESULT_PREDICATES: [&str; 7] = [+ "focusNode",+ "resultPath",+ "value",+ "sourceShape",+ "sourceConstraintComponent",+ "resultSeverity",+ "resultMessage",+];++fn suite_root() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests").join("w3c-shacl")+}++fn base_of(path: &Path) -> String {+ let rel = path.strip_prefix(suite_root()).unwrap().to_string_lossy().replace('\\', "/");+ format!("{SUITE_BASE}{rel}")+}++fn path_of(iri: &str) -> PathBuf {+ suite_root().join(iri.strip_prefix(SUITE_BASE).expect("graph inside the vendored suite"))+}++fn parse(text: &str, format: RdfFormat, base: Option<&str>) -> Vec<Triple> {+ let mut parser = RdfParser::from_format(format);+ if let Some(b) = base {+ parser = parser.with_base_iri(b).unwrap();+ }+ parser+ .for_reader(Cursor::new(text.as_bytes()))+ .map(|q| Triple::from(q.unwrap()))+ .collect()+}++/// Index of a triple set by subject, for walking out from the report node.+struct Graph {+ by_subject: HashMap<NamedOrBlankNode, Vec<Triple>>,+}++impl Graph {+ fn new(triples: Vec<Triple>) -> Self {+ let mut by_subject: HashMap<NamedOrBlankNode, Vec<Triple>> = HashMap::new();+ for t in triples {+ by_subject.entry(t.subject.clone()).or_default().push(t);+ }+ Self { by_subject }+ }++ fn objects(&self, s: &NamedOrBlankNode, p: &str) -> Vec<Term> {+ self.by_subject+ .get(s)+ .map(|ts| ts.iter().filter(|t| t.predicate.as_str() == p).map(|t| t.object.clone()).collect())+ .unwrap_or_default()+ }++ /// Every triple reachable from `node` through blank-node objects: the+ /// structure of a property path such as `[ sh:inversePath ex:p ]`.+ fn closure(&self, node: &Term, out: &mut Vec<Triple>, seen: &mut HashSet<NamedOrBlankNode>) {+ let Term::BlankNode(b) = node else { return };+ let s = NamedOrBlankNode::from(b.clone());+ if !seen.insert(s.clone()) {+ return;+ }+ for t in self.by_subject.get(&s).into_iter().flatten() {+ out.push(t.clone());+ self.closure(&t.object, out, seen);+ }+ }+}++fn as_subject(t: &Term) -> Option<NamedOrBlankNode> {+ match t {+ Term::NamedNode(n) => Some(n.clone().into()),+ Term::BlankNode(b) => Some(b.clone().into()),+ _ => None,+ }+}++/// The compared projection of the report rooted at `report`. `keep_message`+/// decides which `sh:resultMessage` objects survive (see the module docs).+fn project(g: &Graph, report: &NamedOrBlankNode, keep_message: &dyn Fn(&Term) -> bool) -> Vec<Triple> {+ let mut out = Vec::new();+ for c in g.objects(report, &format!("{SH}conforms")) {+ out.push(Triple::new(report.clone(), NamedNode::new_unchecked(format!("{SH}conforms")), c));+ }+ for r in g.objects(report, &format!("{SH}result")) {+ let Some(rs) = as_subject(&r) else { continue };+ out.push(Triple::new(report.clone(), NamedNode::new_unchecked(format!("{SH}result")), r.clone()));+ for p in RESULT_PREDICATES {+ let iri = format!("{SH}{p}");+ for o in g.objects(&rs, &iri) {+ if p == "resultMessage" && !keep_message(&o) {+ continue;+ }+ if p == "resultPath" {+ g.closure(&o, &mut out, &mut HashSet::new());+ }+ out.push(Triple::new(rs.clone(), NamedNode::new_unchecked(iri.clone()), o));+ }+ }+ }+ out+}++fn canonical(triples: Vec<Triple>) -> String {+ let quads: Vec<Quad> = triples.into_iter().map(|t| t.in_graph(GraphName::DefaultGraph)).collect();+ canon::canonical_nquads(&quads, canon::DEFAULT_CALL_BUDGET, HashAlgorithm::Sha256).unwrap()+}++/// The core/ cases the conformance baseline records as PASS.+fn pass_cases() -> Vec<String> {+ let text = std::fs::read_to_string(+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests").join("w3c_shacl_baseline.json"),+ )+ .unwrap();+ let baseline: serde_json::Value = serde_json::from_str(&text).unwrap();+ let mut out: Vec<String> = baseline["outcomes"]+ .as_object()+ .unwrap()+ .iter()+ .filter(|(name, outcome)| name.starts_with("core/") && *outcome == "PASS")+ .map(|(name, _)| name.clone())+ .collect();+ out.sort();+ out+}++enum Verdict {+ Match,+ Differs { missing: Vec<String>, extra: Vec<String> },+}++fn run_case(name: &str) -> Verdict {+ // Every core/ PASS case is a single file holding its own manifest entry.+ assert!(!name.contains("::"), "{name}: multi-entry manifests are not handled here");+ let file = suite_root().join(format!("{name}.ttl"));+ let base = base_of(&file);+ let manifest = Graph::new(parse(&std::fs::read_to_string(&file).unwrap(), RdfFormat::Turtle, Some(&base)));++ let entry = manifest+ .by_subject+ .iter()+ .find(|(_, ts)| {+ ts.iter().any(|t| {+ t.predicate.as_str().ends_with("#type")+ && t.object == Term::from(NamedNode::new_unchecked(format!("{SHT}Validate")))+ })+ })+ .map(|(s, _)| s.clone())+ .unwrap_or_else(|| panic!("{name}: no sht:Validate entry"));+ let action = as_subject(&manifest.objects(&entry, &format!("{MF}action"))[0]).unwrap();+ let iri = |p: &str| match &manifest.objects(&action, &format!("{SHT}{p}"))[0] {+ Term::NamedNode(n) => n.as_str().to_string(),+ other => panic!("{name}: {p} is {other}"),+ };+ let (data_path, shapes_path) = (path_of(&iri("dataGraph")), path_of(&iri("shapesGraph")));+ let expected_root = as_subject(&manifest.objects(&entry, &format!("{MF}result"))[0]).unwrap();++ // Loaded exactly as the conformance harness loads them: data with its own+ // base, shapes through a store and out as absolute N-Triples, because the+ // public entry point takes no base IRI.+ let data = Arc::new(GraphStore::new());+ data.load_turtle(&std::fs::read_to_string(&data_path).unwrap(), Some(&base_of(&data_path))).unwrap();+ let shapes = GraphStore::new();+ shapes+ .load_turtle(&std::fs::read_to_string(&shapes_path).unwrap(), Some(&base_of(&shapes_path)))+ .unwrap();+ let ttl = ShaclValidator::report_scoped(&data, &shapes.serialize("ntriples").unwrap(), &ScopeRequest::Unscoped)+ .unwrap()+ .render(ReportFormat::Turtle)+ .unwrap();+ let actual = Graph::new(parse(&ttl, RdfFormat::Turtle, None));+ let actual_root = actual+ .by_subject+ .iter()+ .find(|(_, ts)| ts.iter().any(|t| t.object.to_string() == format!("<{SH}ValidationReport>")))+ .map(|(s, _)| s.clone())+ .unwrap_or_else(|| panic!("{name}: the Turtle has no sh:ValidationReport:\n{ttl}"));++ let expected_messages: HashSet<Term> = manifest+ .by_subject+ .values()+ .flatten()+ .filter(|t| t.predicate.as_str() == format!("{SH}resultMessage"))+ .map(|t| t.object.clone())+ .collect();+ let want = canonical(project(&manifest, &expected_root, &|_| true));+ let got = canonical(project(&actual, &actual_root, &|m| expected_messages.contains(m)));+ if want == got {+ return Verdict::Match;+ }+ let w: BTreeSet<&str> = want.lines().collect();+ let g: BTreeSet<&str> = got.lines().collect();+ Verdict::Differs {+ missing: w.difference(&g).map(|s| s.to_string()).collect(),+ extra: g.difference(&w).map(|s| s.to_string()).collect(),+ }+}++#[test]+fn turtle_reports_match_the_w3c_expected_reports() {+ if common::skip_unless(+ suite_root().join("manifest.ttl").is_file(),+ "the vendored W3C SHACL test suite at tests/w3c-shacl/",+ "see tests/w3c-shacl/README.md",+ ) {+ return;+ }+ let cases = pass_cases();+ assert!(!cases.is_empty(), "the baseline lists no core/ PASS case");+ let mut matched = 0;+ let mut differing: Vec<String> = Vec::new();+ for name in &cases {+ match run_case(name) {+ Verdict::Match => matched += 1,+ Verdict::Differs { missing, extra } => {+ // Canonical blank-node labels are not stable across two+ // different graphs, so a line can differ only by its label;+ // both sides are printed whole rather than summarised.+ differing.push(format!(+ "{name}\n expected, not produced:\n {}\n produced, not expected:\n {}",+ missing.join("\n "),+ extra.join("\n ")+ ));+ }+ }+ }+ eprintln!(+ "W3C full-report match: {matched} of {} core/ PASS cases ({} differ)",+ cases.len(),+ differing.len()+ );+ for d in &differing {+ eprintln!(" {d}");+ }+ let known: HashSet<&str> = KNOWN_DIFFERENCES.iter().map(|(n, _)| *n).collect();+ let regressed: Vec<&String> =+ differing.iter().filter(|d| !known.contains(d.lines().next().unwrap_or_default())).collect();+ assert!(+ regressed.is_empty(),+ "these cases no longer match the expected report and are not known differences:\n{}",+ regressed.iter().map(|s| s.as_str()).collect::<Vec<_>>().join("\n")+ );+ assert!(+ matched >= MATCHED_FLOOR,+ "{matched} of {} core/ PASS cases match the expected report, below the floor of \+ {MATCHED_FLOOR}:\n{}",+ cases.len(),+ differing.join("\n")+ );+}++#[test]+fn the_comparison_can_fail() {+ // A gate that cannot fail measures nothing. Dropping one result from the+ // engine's graph must change the canonical form.+ let name = "core/property/datatype-001";+ let file = suite_root().join(format!("{name}.ttl"));+ if !file.is_file() {+ return;+ }+ let base = base_of(&file);+ let manifest = Graph::new(parse(&std::fs::read_to_string(&file).unwrap(), RdfFormat::Turtle, Some(&base)));+ let root = manifest+ .by_subject+ .iter()+ .find(|(_, ts)| ts.iter().any(|t| t.object.to_string() == format!("<{SH}ValidationReport>")))+ .map(|(s, _)| s.clone())+ .unwrap();+ let full = project(&manifest, &root, &|_| true);+ let first_result = full+ .iter()+ .find(|t| t.predicate.as_str() == format!("{SH}result"))+ .map(|t| t.object.clone())+ .unwrap();+ let fewer: Vec<Triple> = full.iter().filter(|t| t.object != first_result).cloned().collect();+ assert_ne!(canonical(full), canonical(fewer));+}