Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat(shacl): evaluate sh:or over leaf alternatives

FABIOTESSc1fc9cca5d6e
diff --git a/src/shacl.rs b/src/shacl.rs
index 8032caec..6c2f9b2c 100644
--- a/src/shacl.rs
+++ b/src/shacl.rs
@@ -277,6 +277,7 @@ impl ShaclValidator {
sh:class, sh:pattern, sh:hasValue, sh:message, sh:severity,
sh:minInclusive, sh:maxInclusive,
sh:minExclusive, sh:maxExclusive,
+ sh:or,
sh:name, sh:description, sh:order, sh:group,
<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
))
@@ -295,6 +296,73 @@ impl ShaclValidator {
}
}
+ // sh:or alternatives for this shape, collected once and keyed by path.
+ //
+ // They cannot be looked up per property shape the obvious way: a
+ // property shape is almost always a blank node, and a blank-node
+ // label written into a SPARQL query is a fresh variable rather than
+ // a reference to that node, so `?prop sh:or ...` with the label
+ // substituted matches every property shape in the file instead of
+ // one. Keying by path avoids naming the blank node at all.
+ let mut or_alternatives: HashMap<String, Vec<String>> = HashMap::new();
+ let mut or_unsupported: HashSet<String> = HashSet::new();
+ let or_rows = query_solutions(
+ &shapes_store,
+ &format!(
+ r#"
+ PREFIX sh: <http://www.w3.org/ns/shacl#>
+ PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
+ SELECT ?path ?datatype ?class ?hasValue ?other WHERE {{
+ {} sh:property ?prop .
+ ?prop sh:path ?path .
+ ?prop sh:or/rdf:rest*/rdf:first ?member .
+ OPTIONAL {{ ?member sh:datatype ?datatype }}
+ OPTIONAL {{ ?member sh:class ?class }}
+ OPTIONAL {{ ?member sh:hasValue ?hasValue }}
+ OPTIONAL {{
+ ?member ?other ?_v .
+ FILTER(?other NOT IN (sh:datatype, sh:class, sh:hasValue, rdf:type))
+ }}
+ }}
+ "#,
+ shape_iri
+ ),
+ )?;
+ for row in &or_rows {
+ let p = match row.get("path") {
+ Some(p) => strip_angle_brackets(p),
+ None => continue,
+ };
+ if row.get("other").is_some() {
+ or_unsupported.insert(p);
+ continue;
+ }
+ let clause = if let Some(dt) = row.get("datatype") {
+ format!("DATATYPE(?val) = <{}>", strip_angle_brackets(dt))
+ } else if let Some(c) = row.get("class") {
+ format!(
+ "EXISTS {{ ?val <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{}> }}",
+ strip_angle_brackets(c)
+ )
+ } else if let Some(hv) = row.get("hasValue") {
+ format!("?val = {}", hv.trim())
+ } else {
+ or_unsupported.insert(p);
+ continue;
+ };
+ or_alternatives.entry(p).or_default().push(clause);
+ }
+ for p in &or_unsupported {
+ or_alternatives.remove(p);
+ skipped.push(serde_json::json!({
+ "shape": strip_angle_brackets(&shape_iri),
+ "constraint": "sh:or",
+ "path": p,
+ "reason": "sh:or members use a constraint form that is not implemented; \
+ the disjunction was not evaluated",
+ }));
+ }
+
// 4. For each constraint, run SPARQL queries against the main graph
for prop in &props {
let raw_path = match prop.get("path") {
@@ -503,6 +571,48 @@ impl ShaclValidator {
}
}
+ // sh:or over a property shape: each value on the path must
+ // satisfy at least one member of the list. The alternatives were
+ // collected for this shape above and are keyed by path.
+ //
+ // The general form nests arbitrary shapes and is not attempted.
+ // What is evaluated is the form that occurs in practice, a list
+ // of leaf alternatives each carrying exactly one of sh:datatype,
+ // sh:class or sh:hasValue. The motivating case is a date recorded
+ // at day, month or year precision: three sh:datatype members that
+ // no single constraint can express. A list containing any other
+ // form was sent to `skipped` above rather than evaluated, because
+ // a disjunction evaluated over only the alternatives that happened
+ // to be understood is not the disjunction that was written, and
+ // would report a violation for a value the shape permits.
+ if let Some(clauses) = or_alternatives.get(&path) {
+ let disjunction = clauses.join(" || ");
+ 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(!({disjunction}))
+ }}"#
+ );
+ let results = graph_sparql_select(graph, &query)?;
+ for row in &results {
+ if let Some(focus) = row.get("focus") {
+ let msg = if message.is_empty() {
+ "Value satisfies none of the sh:or alternatives".to_string()
+ } else {
+ message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": path,
+ "constraint": "or",
+ "message": msg,
+ }));
+ }
+ }
+ }
+
// sh:hasValue: every focus node must carry the exact term at
// least once on the path. The term arrives from the shapes
// store in N-Triples form (`<iri>` or `"lit"^^<dt>`), which is
diff --git a/tests/shacl_or_test.rs b/tests/shacl_or_test.rs
new file mode 100644
index 00000000..059834f7
--- /dev/null
+++ b/tests/shacl_or_test.rs
@@ -0,0 +1,135 @@
+//! `sh:or` on a property shape: each value must satisfy at least one alternative.
+//!
+//! Before this, `sh:or` reached `skipped` and suppressed the verdict, so a shapes
+//! graph using it could never return `conforms: true`. That mattered beyond the
+//! feature gap: the NAPH heritage-aerial standard states its date-precision policy
+//! (ADR-0009) as three `sh:datatype` alternatives — day, month or year — because
+//! real archive holdings include year-only frames. Its own README and tutorials
+//! document `conforms: true` as the expected output, while every run over the
+//! shipped samples returned `conforms: null` with that one constraint unevaluated.
+//! The single most domain-specific rule in the standard was the one not checked.
+//!
+//! Only the leaf form is evaluated: a list whose members each carry exactly one of
+//! `sh:datatype`, `sh:class` or `sh:hasValue`. A member using anything else sends
+//! the whole disjunction to `skipped`, because evaluating only the alternatives
+//! that happened to be understood is not the disjunction that was written, and
+//! would report a violation for a value the shape permits.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn validate(data: &str, shapes: &str) -> serde_json::Value {
+ let g = Arc::new(GraphStore::new());
+ g.load_turtle(data, None).expect("data should parse");
+ let out = ShaclValidator::validate(&g, shapes).expect("validation should run");
+ serde_json::from_str(&out).expect("report should be JSON")
+}
+
+const DATE_SHAPE: &str = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix : <http://ex.org/> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+:PhotoShape a sh:NodeShape ; sh:targetClass :Photo ;
+ sh:property [ sh:path :capturedOn ;
+ sh:or ( [ sh:datatype xsd:date ] [ sh:datatype xsd:gYearMonth ] [ sh:datatype xsd:gYear ] ) ] .
+"#;
+
+/// The ADR-0009 case: all three precisions are admitted, and nothing is skipped.
+#[test]
+fn all_three_date_precisions_conform() {
+ let data = r#"
+@prefix : <http://ex.org/> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+:day a :Photo ; :capturedOn "1944-06-06"^^xsd:date .
+:month a :Photo ; :capturedOn "1944-06"^^xsd:gYearMonth .
+:year a :Photo ; :capturedOn "1944"^^xsd:gYear .
+"#;
+ let r = validate(data, DATE_SHAPE);
+ assert_eq!(r["violation_count"], 0, "report: {r}");
+ assert_eq!(
+ r["conforms"], true,
+ "sh:or must now yield a verdict, not null: {r}"
+ );
+ let skipped_empty = r["skipped_constraints"]
+ .as_array()
+ .map(|a| a.is_empty())
+ .unwrap_or(true); // the key is omitted entirely when nothing was skipped
+ assert!(skipped_empty, "nothing should be skipped: {r}");
+}
+
+/// A value matching no alternative is a violation.
+#[test]
+fn value_matching_no_alternative_violates() {
+ let data = r#"
+@prefix : <http://ex.org/> .
+:freetext a :Photo ; :capturedOn "summer 1944" .
+"#;
+ let r = validate(data, DATE_SHAPE);
+ assert_eq!(r["violation_count"], 1, "report: {r}");
+ assert_eq!(r["violations"][0]["constraint"], "or");
+ assert_eq!(r["conforms"], false);
+}
+
+/// The bug this test exists for. A property shape is a blank node, and a
+/// blank-node label written into a SPARQL query is a fresh variable rather than
+/// a reference to that node. Looking `sh:or` up that way matched EVERY property
+/// shape in the file, so a shape with no `sh:or` at all inherited another
+/// shape's alternatives and reported violations on unrelated paths.
+#[test]
+fn or_does_not_leak_to_other_property_shapes() {
+ let shapes = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix : <http://ex.org/> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+:S a sh:NodeShape ; sh:targetClass :Photo ;
+ sh:property [ sh:path :capturedOn ;
+ sh:or ( [ sh:datatype xsd:date ] [ sh:datatype xsd:gYear ] ) ] ;
+ sh:property [ sh:path :title ; sh:minCount 1 ] .
+"#;
+ let data = r#"
+@prefix : <http://ex.org/> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+:p a :Photo ; :capturedOn "1944"^^xsd:gYear ; :title "a plain string title" .
+"#;
+ let r = validate(data, shapes);
+ assert_eq!(
+ r["violation_count"], 0,
+ ":title has no sh:or and must not be judged against :capturedOn's alternatives: {r}"
+ );
+}
+
+/// A member form that is not implemented must skip the whole disjunction and
+/// suppress the verdict, never silently narrow it.
+#[test]
+fn unsupported_member_form_skips_rather_than_narrowing() {
+ let shapes = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix : <http://ex.org/> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+:S a sh:NodeShape ; sh:targetClass :Photo ;
+ sh:property [ sh:path :capturedOn ;
+ sh:or ( [ sh:datatype xsd:date ] [ sh:minLength 4 ] ) ] .
+"#;
+ let data = r#"
+@prefix : <http://ex.org/> .
+:p a :Photo ; :capturedOn "1944" .
+"#;
+ let r = validate(data, shapes);
+ let skipped = r["skipped_constraints"]
+ .as_array()
+ .cloned()
+ .unwrap_or_default();
+ assert!(
+ skipped.iter().any(|s| s["constraint"] == "sh:or"),
+ "an unsupported member must send sh:or to skipped: {r}"
+ );
+ assert!(
+ r["conforms"].is_null(),
+ "a skipped constraint must suppress the verdict: {r}"
+ );
+ assert_eq!(
+ r["violation_count"], 0,
+ "a skipped disjunction must not report violations: {r}"
+ );
+}