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
feat(shacl): implement sh:minInclusive, sh:maxInclusive, sh:minExclusive, sh:maxExclusive
Fabio Rovaia44f668312f8
diff --git a/src/shacl.rs b/src/shacl.rsindex a70cc917..3f42d99c 100644--- a/src/shacl.rs+++ b/src/shacl.rs@@ -237,7 +237,7 @@ impl ShaclValidator {&format!(r#"PREFIX sh: <http://www.w3.org/ns/shacl#>- SELECT ?prop ?path ?invPath ?minCount ?maxCount ?datatype ?class ?pattern ?hasValue ?message ?severity WHERE {{+ SELECT ?prop ?path ?invPath ?minCount ?maxCount ?datatype ?class ?pattern ?hasValue ?minInclusive ?maxInclusive ?minExclusive ?maxExclusive ?message ?severity WHERE {{{} sh:property ?prop .?prop sh:path ?path .OPTIONAL {{ ?path sh:inversePath ?invPath }}@@ -247,6 +247,10 @@ impl ShaclValidator {OPTIONAL {{ ?prop sh:datatype ?datatype }}OPTIONAL {{ ?prop sh:pattern ?pattern }}OPTIONAL {{ ?prop sh:hasValue ?hasValue }}+ OPTIONAL {{ ?prop sh:minInclusive ?minInclusive }}+ OPTIONAL {{ ?prop sh:maxInclusive ?maxInclusive }}+ OPTIONAL {{ ?prop sh:minExclusive ?minExclusive }}+ OPTIONAL {{ ?prop sh:maxExclusive ?maxExclusive }}OPTIONAL {{ ?prop sh:message ?message }}OPTIONAL {{ ?prop sh:severity ?severity }}}}@@ -271,6 +275,8 @@ impl ShaclValidator {FILTER(?pred NOT IN (sh:path, sh:minCount, sh:maxCount, sh:datatype,sh:class, sh:pattern, sh:hasValue, sh:message, sh:severity,+ sh:minInclusive, sh:maxInclusive,+ sh:minExclusive, sh:maxExclusive,sh:name, sh:description, sh:order, sh:group,<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>))@@ -527,6 +533,46 @@ impl ShaclValidator {}}}++ // sh:minInclusive, sh:maxInclusive, sh:minExclusive and+ // sh:maxExclusive. Each value node on the path must satisfy the+ // comparison; a value that fails is one violation. The bound+ // arrives from the shapes store in N-Triples form, which is+ // valid SPARQL as-is, exactly as for sh:hasValue above.+ for (key, op, label) in [+ ("minInclusive", "<", "sh:minInclusive"),+ ("maxInclusive", ">", "sh:maxInclusive"),+ ("minExclusive", "<=", "sh:minExclusive"),+ ("maxExclusive", ">=", "sh:maxExclusive"),+ ] {+ if let Some(bound_raw) = prop.get(key) {+ let bound = bound_raw.trim();+ let query = format!(+ r#"SELECT ?focus ?val WHERE {{+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .+ ?focus {path_expr} ?val .+ FILTER(?val {op} {bound})+ }}"#+ );+ let results = graph_sparql_select(graph, &query)?;+ for row in &results {+ if let Some(focus) = row.get("focus") {+ let msg = if message.is_empty() {+ format!("Value violates {} {}", label, bound)+ } else {+ message.clone()+ };+ violations.push(serde_json::json!({+ "severity": severity,+ "focus_node": strip_angle_brackets(focus),+ "path": path,+ "constraint": key,+ "message": msg,+ }));+ }+ }+ }+ }}}diff --git a/tests/shacl_test.rs b/tests/shacl_test.rsindex d0e39872..dc580c7a 100644--- a/tests/shacl_test.rs+++ b/tests/shacl_test.rs@@ -847,3 +847,90 @@ fn test_the_report_names_the_scope_it_selected_over() {let v: serde_json::Value = serde_json::from_str(&report).unwrap();assert_eq!(v["scope"], "all_graphs", "report: {v}");}++// Range constraints. Before these were implemented, a shape carrying+// sh:minInclusive or sh:maxInclusive was reported in skipped_constraints and+// suppressed `conforms` to null, so a validator run could neither pass nor fail+// on a numeric bound. Found while validating the trade remedy ontology, where a+// resolution-cardinality bound was the whole point of the shape.++fn store_with_numbers() -> Arc<GraphStore> {+ let store = Arc::new(GraphStore::new());+ let ttl = r#"+ @prefix ex: <http://example.org/> .+ ex:a a ex:Thing ; ex:n 0 .+ ex:b a ex:Thing ; ex:n 1 .+ ex:c a ex:Thing ; ex:n 2 .+ ex:d a ex:Thing ; ex:n 5 .+ ex:e a ex:Thing ; ex:n -3 .+ "#;+ store.load_turtle(ttl, None).unwrap();+ store+}++const RANGE_SHAPE: &str = r#"+ @prefix sh: <http://www.w3.org/ns/shacl#> .+ @prefix ex: <http://example.org/> .+ ex:RangeShape a sh:NodeShape ;+ sh:targetClass ex:Thing ;+ sh:property [+ sh:path ex:n ;+ sh:minInclusive 1 ;+ sh:maxInclusive 2 ;+ sh:message "n must be between 1 and 2 inclusive" ;+ ] .+"#;++#[test]+fn test_shacl_inclusive_range_matches_pyshacl() {+ let store = store_with_numbers();+ let result = ShaclValidator::validate(&store, RANGE_SHAPE).unwrap();+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();++ // pyshacl 0.40.1 flags exactly a, d and e on this fixture.+ assert_eq!(parsed["conforms"], false);+ assert_eq!(parsed["violation_count"].as_u64().unwrap(), 3);+ let v = parsed["violations"].as_array().unwrap();+ for expected in ["a", "d", "e"] {+ assert!(+ v.iter().any(|x| x["focus_node"].as_str().unwrap().ends_with(expected)),+ "expected {} to violate the range", expected+ );+ }+ assert!(!v.iter().any(|x| x["focus_node"].as_str().unwrap().ends_with("b")));+ assert!(!v.iter().any(|x| x["focus_node"].as_str().unwrap().ends_with("c")));+}++#[test]+fn test_shacl_range_constraints_are_no_longer_skipped() {+ let store = store_with_numbers();+ let result = ShaclValidator::validate(&store, RANGE_SHAPE).unwrap();+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();+ let skipped = parsed["skipped_constraints"].as_array();+ if let Some(s) = skipped {+ for item in s {+ let c = item["constraint"].as_str().unwrap_or("");+ assert!(!c.contains("Inclusive"), "range constraint still skipped: {}", c);+ assert!(!c.contains("Exclusive"), "range constraint still skipped: {}", c);+ }+ }+ // conforms must be a real boolean, never null, once nothing is skipped.+ assert!(parsed["conforms"].is_boolean());+}++#[test]+fn test_shacl_exclusive_range() {+ let store = store_with_numbers();+ let shapes = r#"+ @prefix sh: <http://www.w3.org/ns/shacl#> .+ @prefix ex: <http://example.org/> .+ ex:ExShape a sh:NodeShape ;+ sh:targetClass ex:Thing ;+ sh:property [ sh:path ex:n ; sh:minExclusive 1 ; sh:maxExclusive 5 ] .+ "#;+ let result = ShaclValidator::validate(&store, shapes).unwrap();+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();+ // Violations: 0, 1 (not > 1), 5 (not < 5) and -3. Passing: 2.+ assert_eq!(parsed["conforms"], false);+ assert_eq!(parsed["violation_count"].as_u64().unwrap(), 4);+}