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): more constraint components, all four target forms, and a differential oracle against pyshacl

FABIOTESS3eb230904d8b
diff --git a/docs/UPSTREAM_ISSUES.md b/docs/UPSTREAM_ISSUES.md
new file mode 100644
index 00000000..d5c080fb
--- /dev/null
+++ b/docs/UPSTREAM_ISSUES.md
@@ -0,0 +1,118 @@
+# Upstream issues
+
+Reproducible defects found in dependencies while working on this repository.
+Nothing here has been filed. Each entry is a minimal case, staged for a human to
+send.
+
+---
+
+## 1. Twelve XSD integer-derived datatypes, and `xsd:dateTimeStamp`, are not preserved
+
+**Two independent defects, in two crates.** They were first reported here as one,
+blamed on storage. That was wrong, and the correction matters for anyone acting
+on it: fixing the storage encoder alone leaves `DATATYPE()` still returning the
+wrong IRI, because the expression evaluator collapses the same set again.
+
+**Repository:** `oxigraph/oxigraph` · **Version:** 0.5.9 · **Severity: high.**
+The store returns a literal with a different datatype IRI from the one it was
+given. RDF 1.1 makes the datatype IRI part of a literal's identity, so this is a
+change to the data, not a representation detail.
+
+### Reproduction
+
+```turtle
+@prefix ex: <http://example.org/> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ex:s ex:p "0"^^xsd:nonNegativeInteger .
+```
+
+```sparql
+SELECT (DATATYPE(?v) AS ?dt) WHERE { ?s ?p ?v }
+```
+
+Observed: `xsd:integer`. Expected: `xsd:nonNegativeInteger`, which is what
+rdflib returns for the same input.
+
+### Scope, measured
+
+Affected, all collapsing to `xsd:integer`:
+
+`byte`, `short`, `int`, `long`, `unsignedByte`, `unsignedShort`, `unsignedInt`,
+`unsignedLong`, `positiveInteger`, `negativeInteger`, `nonPositiveInteger`,
+`nonNegativeInteger`
+
+`xsd:dateTimeStamp` collapses into `xsd:dateTime` the same way.
+
+Not affected: `integer`, `decimal`, `float`, `double`, `boolean`, `string`,
+`token`, `normalizedString`, `Name`, `NCName`, `language`, `anyURI`, `date`,
+`dateTime`, `gYear`, `duration`, `yearMonthDuration`, `dayTimeDuration`.
+
+### 1a. oxigraph storage: the datatype is dropped on insert
+
+`oxigraph` 0.5.9, `src/storage/numeric_encoder.rs`. Twelve datatype IRIs share one
+match arm calling `parse_integer_str`, which yields `EncodedTerm::IntegerLiteral`:
+a single variant carrying no datatype IRI, so read-back can only reconstruct
+`xsd:integer`.
+
+The parser is not at fault. Parsing the document above and inspecting the quad
+before insertion gives the correct datatype every time; the loss happens at
+storage encoding. Demonstrated by a load-then-serialise round trip, which does
+not involve the query evaluator at all: `"0"^^xsd:nonNegativeInteger` is written
+back out as bare `0`.
+
+### 1b. spareval evaluator: `DATATYPE()` collapses the same set again
+
+`spareval` 0.2.6, `src/dataset.rs` maps the same twelve IRIs to
+`ExpressionTerm::IntegerLiteral`, and `src/expression.rs` answers `DATATYPE()` on
+that variant with `xsd:integer`.
+
+This is independent of storage. A literal typed in the query text, never stored,
+loses its datatype just the same:
+
+```sparql
+SELECT (DATATYPE("0"^^xsd:nonNegativeInteger) AS ?dt) WHERE { }
+```
+
+Observed `xsd:integer`; rdflib answers `xsd:nonNegativeInteger`. In the same
+query `DATATYPE("abc"^^xsd:token)` correctly answers `xsd:token`, so the
+behaviour is specific to this set and not a general canonicalisation policy.
+
+SPARQL 1.1 defines `DATATYPE` as returning the datatype IRI of the literal, so
+this is a conformance defect and not only a fidelity one.
+
+### Why this reads as a defect rather than a deliberate simplification
+
+`xsd:yearMonthDuration` and `xsd:dayTimeDuration` are derived types too, and they
+have their own encodings and survive intact. The treatment of derived types is
+inconsistent, and the inconsistency is not documented.
+
+### Consequences seen in practice
+
+1. A SHACL `sh:datatype xsd:nonNegativeInteger` constraint cannot be decided
+ against the store: a conforming literal and a widened one are the same term by
+ the time the query runs. Answering anyway reported a violation against every
+ value that satisfied the shape, nine of them in one repository, which is how
+ this was found.
+2. A load-then-serialise round trip rewrites the published file.
+ `"0"^^xsd:nonNegativeInteger` comes back out as bare `0`.
+
+### Suggested fix
+
+Both layers need the datatype IRI carried alongside the numeric value.
+
+Declining the native encoding and falling through to the generic typed-literal
+path fixes fidelity but costs numeric semantics: these types are in the SPARQL
+numeric hierarchy, so arithmetic and ordering over them must keep working. That
+makes the honest fix a datatype slot on the numeric variants of both
+`EncodedTerm` and `ExpressionTerm`, rather than a re-routing of the match arms.
+
+Neither enum has such a slot today, so this is a coordinated change across the
+two crates, and it wants their conformance suites run against it. It is written
+up here rather than attempted blind.
+
+### Our workaround
+
+`datatype_is_indistinguishable_in_store` in `src/shacl.rs` records a
+`sh:datatype` constraint naming one of these as unevaluated rather than answering
+it wrongly. `tests/datatype_preservation_test.rs` pins the exact affected set and
+fails in both directions, so the workaround is removed when this is fixed.
diff --git a/src/shacl.rs b/src/shacl.rs
index a7797153..9b38d96c 100644
--- a/src/shacl.rs
+++ b/src/shacl.rs
@@ -11,15 +11,22 @@ use std::sync::Arc;
/// Shapes are parsed from inline Turtle into a temporary Oxigraph store.
/// Constraints are translated into SPARQL queries run against the main graph.
/// Supports the core constraints `sh:minCount`, `sh:maxCount`, `sh:datatype`,
-/// `sh:pattern` and `sh:hasValue`, and SPARQL-based constraints via `sh:sparql`.
+/// `sh:class`, `sh:pattern`, `sh:hasValue`, `sh:in`, `sh:nodeKind`, `sh:or`,
+/// `sh:not`, the inclusive and exclusive range bounds, and SPARQL-based
+/// constraints via `sh:sparql`.
+///
+/// All four target forms select focus nodes: `sh:targetClass` (including the
+/// implicit class target), `sh:targetNode`, `sh:targetSubjectsOf` and
+/// `sh:targetObjectsOf`.
///
/// Any constraint the validator cannot execute is recorded in
/// `skipped_constraints` and suppresses the conformance verdict: `conforms`
-/// becomes null rather than true. That holds wherever the constraint sits:
-/// on a property shape (`sh:not`), on the node shape itself (`sh:closed`,
-/// `sh:nodeKind`, `sh:deactivated`) or in a target form that is not selected
-/// (`sh:targetNode`). Reporting success for rules that were never run is the
-/// one failure mode this validator must not have.
+/// becomes null rather than true. That holds wherever the constraint sits: on a
+/// property shape (`sh:minLength`, `sh:xone`, a `sh:not` nesting a form that is
+/// not evaluated), or on the node shape itself (`sh:closed`, `sh:deactivated`).
+/// A target that selects no nodes reaches the same null verdict by the other
+/// route, `unmatched_shapes`. Reporting success for rules that were never run is
+/// the one failure mode this validator must not have.
pub struct ShaclValidator;
impl ShaclValidator {
@@ -60,29 +67,42 @@ impl ShaclValidator {
let mut violations: Vec<serde_json::Value> = Vec::new();
let mut skipped: Vec<serde_json::Value> = Vec::new();
- // Target forms this implementation does not support. Previously a shapes
- // graph using only these produced no shapes at all, the validation loop
- // never ran, and the report said `conforms: true` having checked nothing.
- // Recording them as skipped suppresses the verdict instead.
- for (pred, label) in [
- ("sh:targetNode", "sh:targetNode"),
- ("sh:targetSubjectsOf", "sh:targetSubjectsOf"),
- ("sh:targetObjectsOf", "sh:targetObjectsOf"),
+ // All four target forms, each reduced to a SPARQL pattern that binds one
+ // focus variable. Reducing them to a pattern rather than to a class keeps
+ // every constraint below written once: the constraint queries do not know
+ // which form selected the node they are checking.
+ //
+ // `sh:targetClass` selects SHACL instances, which is rdf:type followed by
+ // zero or more rdfs:subClassOf steps, not a direct rdf:type.
+ //
+ // The other three are explicit. `sh:targetNode` names its focus node
+ // outright and selects it whether or not that node appears anywhere in
+ // the data: checked against pyshacl, which reports a MinCount violation
+ // on a targetNode absent from the data rather than an empty target. A
+ // VALUES clause reproduces that, where a triple pattern would not.
+ //
+ // Until this existed the three explicit forms were recorded as skipped,
+ // which was honest but empty: a shapes graph written to the specification
+ // got no verdict at all.
+ let mut targets: Vec<(String, &'static str, String)> = Vec::new();
+ for row in &shapes {
+ if let (Some(shape), Some(tc)) = (row.get("shape"), row.get("targetClass")) {
+ targets.push((shape.clone(), "class", strip_angle_brackets(tc)));
+ }
+ }
+ for (pred, kind) in [
+ ("sh:targetNode", "node"),
+ ("sh:targetSubjectsOf", "subjectsOf"),
+ ("sh:targetObjectsOf", "objectsOf"),
] {
let q = format!(
r#"PREFIX sh: <http://www.w3.org/ns/shacl#>
- SELECT ?shape WHERE {{ ?shape {} ?t . }}"#,
+ SELECT DISTINCT ?shape ?t WHERE {{ ?shape {} ?t . }}"#,
pred
);
- if let Ok(rows) = query_solutions(&shapes_store, &q) {
- for row in &rows {
- skipped.push(serde_json::json!({
- "shape": strip_angle_brackets(
- row.get("shape").map(|s| s.as_str()).unwrap_or_default()
- ),
- "constraint": label,
- "reason": "target form not implemented; focus nodes could not be selected",
- }));
+ for row in &query_solutions(&shapes_store, &q)? {
+ if let (Some(shape), Some(t)) = (row.get("shape"), row.get("t")) {
+ targets.push((shape.clone(), kind, t.trim().to_string()));
}
}
}
@@ -107,15 +127,14 @@ impl ShaclValidator {
// and a node constraint belongs to the shape, so running the
// complement per row recorded `sh:closed` once per target class. It
// is restricted to discovered shapes, like the property complement:
- // a shape using a target form this validator lacks is already
- // recorded as skipped, and a shape with no target selects no focus
- // nodes under SHACL, so its constraints not running is what the
- // specification asks for, not a gap.
+ // a shape with no target selects no focus nodes under SHACL, so its
+ // constraints not running is what the specification asks for, not a
+ // gap. (This clause used to also except shapes using a target form the
+ // validator lacked. There are none left: all four core forms select.)
//
// The whitelist is the predicates the validator reads on the shape
- // node (the four target forms, of which the three not implemented
- // are already recorded as skipped above and must not be counted
- // twice, sh:property and sh:sparql) plus the annotation predicates,
+ // node (the four target forms, all of which now select focus nodes,
+ // plus sh:property and sh:sparql) and the annotation predicates,
// which are never constraints. Any other sh: predicate lands in
// skipped, even one a later change starts to evaluate, because a
// whitelist that tracks what is implemented drifts the first time
@@ -181,7 +200,7 @@ impl ShaclValidator {
?shape a sh:NodeShape ; ?pred ?o .
FILTER(STRSTARTS(STR(?pred), "http://www.w3.org/ns/shacl#") && ?pred NOT IN (
sh:targetClass, sh:targetNode, sh:targetSubjectsOf,
- sh:targetObjectsOf, sh:property, sh:sparql,
+ sh:targetObjectsOf, sh:property, sh:sparql, sh:or,
sh:message, sh:severity, sh:name, sh:description,
sh:order, sh:group
) && !(?pred IN (sh:closed, sh:deactivated)
@@ -204,40 +223,40 @@ impl ShaclValidator {
}));
}
- for shape in &shapes {
- let target_class = match shape.get("targetClass") {
- Some(tc) => strip_angle_brackets(tc),
- None => continue,
- };
+ for (shape_term, kind, target_value) in &targets {
+ let kind = *kind;
+ let focus_pattern = format!("{} .", target_pattern(kind, target_value, "focus"));
// How many nodes does this shape actually apply to? A shape whose
- // target class appears nowhere in the data evaluates every one of
- // its constraints against the empty set and contributes no
- // violations, which is indistinguishable in the report from a shape
- // that checked its nodes and found them sound.
- let focus_count = count_focus_nodes(graph, &target_class)?;
+ // target appears nowhere in the data evaluates every one of its
+ // constraints against the empty set and contributes no violations,
+ // which is indistinguishable in the report from a shape that checked
+ // its nodes and found them sound.
+ let focus_count = count_focus_nodes(graph, &focus_pattern)?;
focus_nodes_total += focus_count;
if focus_count == 0 {
- unmatched.push(serde_json::json!({
- "shape": strip_angle_brackets(
- shape.get("shape").map(|s| s.as_str()).unwrap_or_default()
- ),
- "target_class": target_class,
- }));
+ let mut entry = serde_json::json!({
+ "shape": strip_angle_brackets(shape_term),
+ "target_form": kind,
+ "target": strip_angle_brackets(target_value),
+ });
+ // `target_class` is the key callers already read for the common
+ // form. Keep emitting it rather than renaming it under them.
+ if kind == "class" {
+ entry["target_class"] = serde_json::json!(target_value);
+ }
+ unmatched.push(entry);
}
// 3. Find property constraints for this shape
- let shape_iri = match shape.get("shape") {
- Some(s) => s.clone(),
- None => continue,
- };
+ let shape_iri = shape_term.clone();
let props = query_solutions(
&shapes_store,
&format!(
r#"
PREFIX sh: <http://www.w3.org/ns/shacl#>
- SELECT ?prop ?path ?invPath ?minCount ?maxCount ?datatype ?class ?pattern ?hasValue ?nodeKind ?minInclusive ?maxInclusive ?minExclusive ?maxExclusive ?message ?severity WHERE {{
+ SELECT ?prop ?path ?invPath ?minCount ?maxCount ?datatype ?class ?pattern ?hasValue ?nodeKind ?minInclusive ?maxInclusive ?minExclusive ?maxExclusive ?minLength ?maxLength ?lessThan ?lessThanOrEquals ?node ?message ?severity WHERE {{
{} sh:property ?prop .
?prop sh:path ?path .
OPTIONAL {{ ?path sh:inversePath ?invPath }}
@@ -252,6 +271,11 @@ impl ShaclValidator {
OPTIONAL {{ ?prop sh:maxInclusive ?maxInclusive }}
OPTIONAL {{ ?prop sh:minExclusive ?minExclusive }}
OPTIONAL {{ ?prop sh:maxExclusive ?maxExclusive }}
+ OPTIONAL {{ ?prop sh:minLength ?minLength }}
+ OPTIONAL {{ ?prop sh:maxLength ?maxLength }}
+ OPTIONAL {{ ?prop sh:lessThan ?lessThan }}
+ OPTIONAL {{ ?prop sh:lessThanOrEquals ?lessThanOrEquals }}
+ OPTIONAL {{ ?prop sh:node ?node }}
OPTIONAL {{ ?prop sh:message ?message }}
OPTIONAL {{ ?prop sh:severity ?severity }}
}}
@@ -278,7 +302,12 @@ impl ShaclValidator {
sh:class, sh:pattern, sh:hasValue, sh:message, sh:severity,
sh:minInclusive, sh:maxInclusive,
sh:minExclusive, sh:maxExclusive,
- sh:or, sh:in, sh:nodeKind,
+ sh:or, sh:in, sh:nodeKind, sh:not,
+ sh:minLength, sh:maxLength,
+ sh:lessThan, sh:lessThanOrEquals,
+ sh:qualifiedValueShape, sh:qualifiedMinCount,
+ sh:qualifiedMaxCount,
+ sh:node,
sh:name, sh:description, sh:order, sh:group,
<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
))
@@ -297,14 +326,21 @@ impl ShaclValidator {
}
}
- // sh:or alternatives for this shape, collected once and keyed by path.
+ // sh:or alternatives for this shape, collected once and keyed by the
+ // property shape's own printed term.
//
// 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.
+ // one. Binding ?prop and matching on the printed term avoids naming
+ // the blank node in query text while still telling two blocks apart.
+ //
+ // This was keyed by sh:path, which merged every property shape
+ // sharing a path into one constraint. Two blocks became one
+ // conjunction that no value could satisfy, so both reported nothing
+ // and the run came back CLEAN. Same defect in sh:in and sh:not.
let mut or_alternatives: HashMap<String, Vec<String>> = HashMap::new();
let mut or_unsupported: HashSet<String> = HashSet::new();
let or_rows = query_solutions(
@@ -313,7 +349,7 @@ impl ShaclValidator {
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 {{
+ SELECT ?prop ?path ?datatype ?class ?hasValue ?other WHERE {{
{} sh:property ?prop .
?prop sh:path ?path .
?prop sh:or/rdf:rest*/rdf:first ?member .
@@ -329,11 +365,16 @@ impl ShaclValidator {
shape_iri
),
)?;
+ let mut or_paths: HashMap<String, String> = HashMap::new();
for row in &or_rows {
- let p = match row.get("path") {
- Some(p) => strip_angle_brackets(p),
+ let p = match row.get("prop") {
+ Some(p) => p.clone(),
None => continue,
};
+ or_paths.insert(
+ p.clone(),
+ row.get("path").map(|x| strip_angle_brackets(x)).unwrap_or_default(),
+ );
if row.get("other").is_some() {
or_unsupported.insert(p);
continue;
@@ -358,12 +399,393 @@ impl ShaclValidator {
skipped.push(serde_json::json!({
"shape": strip_angle_brackets(&shape_iri),
"constraint": "sh:or",
- "path": p,
+ "path": or_paths.get(p).cloned().unwrap_or_default(),
"reason": "sh:or members use a constraint form that is not implemented; \
the disjunction was not evaluated",
}));
}
+ // sh:not over a property shape, keyed by path for the same
+ // blank-node reason as sh:or above.
+ //
+ // The nested shape is applied to each value node of the path, so a
+ // violation is a value that CONFORMS to it. That inverts the sense
+ // of every clause: where sh:or reports the values satisfying none of
+ // its members, sh:not reports the values satisfying its one member.
+ //
+ // Only the leaf forms already evaluated in their positive sense are
+ // attempted. Anything else goes to `skipped` and suppresses the
+ // verdict, because a negation that never ran is precisely the false
+ // clean this validator exists to prevent: in the Scottish land
+ // register build a layer-2 shapes graph expressed its rule this way,
+ // and 198 real violations were reported as a clean run.
+ let mut not_clauses: HashMap<String, Vec<String>> = HashMap::new();
+ let mut not_unsupported: HashSet<String> = HashSet::new();
+ let not_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 ?prop ?path ?datatype ?class ?hasValue ?pattern ?other WHERE {{
+ {} sh:property ?prop .
+ ?prop sh:path ?path .
+ ?prop sh:not ?inner .
+ OPTIONAL {{ ?inner sh:datatype ?datatype }}
+ OPTIONAL {{ ?inner sh:class ?class }}
+ OPTIONAL {{ ?inner sh:hasValue ?hasValue }}
+ OPTIONAL {{ ?inner sh:pattern ?pattern }}
+ OPTIONAL {{
+ ?inner ?other ?_v .
+ FILTER(?other NOT IN (
+ sh:datatype, sh:class, sh:hasValue, sh:pattern, rdf:type
+ ))
+ }}
+ }}
+ "#,
+ shape_iri
+ ),
+ )?;
+ let mut not_paths: HashMap<String, String> = HashMap::new();
+ for row in &not_rows {
+ let p = match row.get("prop") {
+ Some(p) => p.clone(),
+ None => continue,
+ };
+ not_paths.insert(
+ p.clone(),
+ row.get("path").map(|x| strip_angle_brackets(x)).unwrap_or_default(),
+ );
+ if row.get("other").is_some() {
+ not_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 if let Some(pattern_raw) = row.get("pattern") {
+ let escaped = strip_quotes(pattern_raw)
+ .replace('\\', "\\\\")
+ .replace('"', "\\\"");
+ format!("REGEX(STR(?val), \"{escaped}\")")
+ } else {
+ // `sh:not` present with no readable nested constraint. Not
+ // evaluable, so not silently dropped.
+ not_unsupported.insert(p);
+ continue;
+ };
+ not_clauses.entry(p).or_default().push(clause);
+ }
+ for p in &not_unsupported {
+ not_clauses.remove(p);
+ skipped.push(serde_json::json!({
+ "shape": strip_angle_brackets(&shape_iri),
+ "constraint": "sh:not",
+ "path": not_paths.get(p).cloned().unwrap_or_default(),
+ "reason": "sh:not nests a constraint form that is not implemented; \
+ the negation was not evaluated",
+ }));
+ }
+
+ // sh:or asserted on the node shape itself, over member SHAPES rather
+ // than leaf constraints: the focus node must conform to at least one.
+ // The per-property sh:or below handles the other form, a list of leaf
+ // alternatives for the values of one path.
+ //
+ // The Italian register vertical expresses a rule this way to keep its
+ // layer core-only: either the assertion is conformant, or it records
+ // why not.
+ //
+ // The members are written inline, so they are blank nodes, and the
+ // shape compiler cannot be pointed at them: a blank-node label inside
+ // a SPARQL query is a fresh variable, not a reference to that node.
+ // Their contents are therefore read through the parent in one query
+ // and grouped by the member's printed term, the same way property
+ // shapes are handled. That confines this form to one level: a member
+ // that itself nests sh:node is not compiled, and says so.
+ let node_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 ?member ?path ?minCount ?maxCount ?class ?datatype ?nodeKind ?hasValue ?other WHERE {{
+ {} sh:or/rdf:rest*/rdf:first ?member .
+ ?member sh:property ?prop .
+ ?prop sh:path ?path .
+ OPTIONAL {{ ?prop sh:minCount ?minCount }}
+ OPTIONAL {{ ?prop sh:maxCount ?maxCount }}
+ OPTIONAL {{ ?prop sh:class ?class }}
+ OPTIONAL {{ ?prop sh:datatype ?datatype }}
+ OPTIONAL {{ ?prop sh:nodeKind ?nodeKind }}
+ OPTIONAL {{ ?prop sh:hasValue ?hasValue }}
+ OPTIONAL {{
+ ?prop ?other ?_v .
+ FILTER(?other NOT IN (
+ sh:path, sh:minCount, sh:maxCount, sh:class,
+ sh:datatype, sh:nodeKind, sh:hasValue,
+ sh:name, sh:description, sh:message, sh:severity,
+ sh:order, sh:group,
+ <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
+ ))
+ }}
+ }}
+ "#,
+ shape_term
+ ),
+ )?;
+ if !node_or_rows.is_empty() {
+ let mut per_member: HashMap<String, Vec<String>> = HashMap::new();
+ let mut uncompilable = false;
+ for (i, row) in node_or_rows.iter().enumerate() {
+ let (Some(member), Some(path_raw)) = (row.get("member"), row.get("path")) else {
+ uncompilable = true;
+ break;
+ };
+ if row.get("other").is_some() || !path_raw.trim().starts_with('<') {
+ uncompilable = true;
+ break;
+ }
+ let path = strip_angle_brackets(path_raw);
+ let v = format!("orv{i}");
+ let mut clauses: Vec<String> = Vec::new();
+ if let Some(min) = row.get("minCount") {
+ match strip_quotes(min).parse::<u64>().ok() {
+ Some(0) => {}
+ Some(1) => clauses.push(format!("EXISTS {{ ?focus <{path}> ?{v} }}")),
+ _ => {
+ uncompilable = true;
+ break;
+ }
+ }
+ }
+ if let Some(max) = row.get("maxCount") {
+ match strip_quotes(max).parse::<u64>().ok() {
+ Some(0) => clauses.push(format!("NOT EXISTS {{ ?focus <{path}> ?{v} }}")),
+ Some(1) => clauses.push(format!(
+ "NOT EXISTS {{ ?focus <{path}> ?{v}a . ?focus <{path}> ?{v}b . FILTER(?{v}a != ?{v}b) }}"
+ )),
+ _ => {
+ uncompilable = true;
+ break;
+ }
+ }
+ }
+ if let Some(hv) = row.get("hasValue") {
+ clauses.push(format!("EXISTS {{ ?focus <{path}> {} }}", hv.trim()));
+ }
+ if let Some(c) = row.get("class") {
+ clauses.push(format!(
+ "NOT EXISTS {{ ?focus <{path}> ?{v} . FILTER NOT EXISTS {{ ?{v} <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{}> }} }}",
+ strip_angle_brackets(c)
+ ));
+ }
+ if let Some(dt) = row.get("datatype") {
+ let dt = strip_angle_brackets(dt);
+ if datatype_is_indistinguishable_in_store(&dt) {
+ uncompilable = true;
+ break;
+ }
+ clauses.push(format!(
+ "NOT EXISTS {{ ?focus <{path}> ?{v} . FILTER(DATATYPE(?{v}) != <{dt}>) }}"
+ ));
+ }
+ if let Some(nk) = row.get("nodeKind") {
+ match node_kind_test(&strip_angle_brackets(nk), &v) {
+ Some(test) => clauses.push(format!(
+ "NOT EXISTS {{ ?focus <{path}> ?{v} . FILTER(!({test})) }}"
+ )),
+ None => {
+ uncompilable = true;
+ break;
+ }
+ }
+ }
+ if clauses.is_empty() {
+ uncompilable = true;
+ break;
+ }
+ per_member.entry(member.clone()).or_default().extend(clauses);
+ }
+ if uncompilable || per_member.is_empty() {
+ skipped.push(serde_json::json!({
+ "shape": strip_angle_brackets(shape_term),
+ "constraint": "sh:or",
+ "reason": "a member shape uses a form that cannot be compiled; \
+ the disjunction was not evaluated",
+ }));
+ } else {
+ let mut members: Vec<String> = per_member
+ .values()
+ .map(|c| format!("({})", c.join(" && ")))
+ .collect();
+ members.sort();
+ let disjunction = members.join(" || ");
+ let node_message = query_solutions(
+ &shapes_store,
+ &format!(
+ r#"PREFIX sh: <http://www.w3.org/ns/shacl#>
+ SELECT ?m WHERE {{ {} sh:message ?m }}"#,
+ shape_term
+ ),
+ )?
+ .first()
+ .and_then(|r| r.get("m").map(|m| strip_quotes(m)))
+ .unwrap_or_default();
+ let query = format!(
+ r#"SELECT DISTINCT ?focus WHERE {{
+ {focus_pattern}
+ FILTER(!({disjunction}))
+ }}"#
+ );
+ for row in &graph_sparql_select(graph, &query)? {
+ if let Some(focus) = row.get("focus") {
+ let msg = if node_message.is_empty() {
+ "Node conforms to none of the sh:or member shapes".to_string()
+ } else {
+ node_message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": "Violation",
+ "focus_node": strip_angle_brackets(focus),
+ "constraint": "or",
+ "message": msg,
+ }));
+ }
+ }
+ }
+ }
+
+ // sh:qualifiedValueShape with sh:qualifiedMinCount / sh:qualifiedMaxCount:
+ // how many of a path's value nodes conform to a nested shape.
+ //
+ // Collected as independent entries, deliberately NOT keyed by path the
+ // way sh:or, sh:in and sh:not are. One shape may carry several qualified
+ // constraints on the same path, each with its own nested shape, bounds
+ // and message: the investment-fund vertical requires exactly one SEC
+ // series identifier and at least one LEI, both on ifo:identifiedBy.
+ // Keying by path merges the two into one rule and drops a bound.
+ //
+ // Binding ?prop keeps two blocks distinct even when they share a path
+ // and a nested class, which DISTINCT over the other columns would fold
+ // together.
+ let qualified_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 ?prop ?path ?class ?datatype ?hasValue ?other ?qmin ?qmax ?message ?severity WHERE {{
+ {} sh:property ?prop .
+ ?prop sh:path ?path ; sh:qualifiedValueShape ?q .
+ OPTIONAL {{ ?q sh:class ?class }}
+ OPTIONAL {{ ?q sh:datatype ?datatype }}
+ OPTIONAL {{ ?q sh:hasValue ?hasValue }}
+ OPTIONAL {{
+ ?q ?other ?_v .
+ FILTER(?other NOT IN (sh:class, sh:datatype, sh:hasValue, rdf:type))
+ }}
+ OPTIONAL {{ ?prop sh:qualifiedMinCount ?qmin }}
+ OPTIONAL {{ ?prop sh:qualifiedMaxCount ?qmax }}
+ OPTIONAL {{ ?prop sh:message ?message }}
+ OPTIONAL {{ ?prop sh:severity ?severity }}
+ }}
+ "#,
+ shape_iri
+ ),
+ )?;
+ for row in &qualified_rows {
+ let Some(path_raw) = row.get("path") else {
+ continue;
+ };
+ let q_path = strip_angle_brackets(path_raw);
+ let q_message = row.get("message").map(|m| strip_quotes(m)).unwrap_or_default();
+ let q_severity = row
+ .get("severity")
+ .map(|s| {
+ strip_angle_brackets(s)
+ .rsplit('#')
+ .next()
+ .unwrap_or("Violation")
+ .to_string()
+ })
+ .unwrap_or_else(|| "Violation".to_string());
+
+ let clause = if row.get("other").is_some() {
+ None
+ } else if let Some(c) = row.get("class") {
+ Some(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(dt) = row.get("datatype") {
+ Some(format!("DATATYPE(?val) = <{}>", strip_angle_brackets(dt)))
+ } else {
+ row.get("hasValue").map(|hv| format!("?val = {}", hv.trim()))
+ };
+ let Some(clause) = clause else {
+ skipped.push(serde_json::json!({
+ "shape": strip_angle_brackets(&shape_iri),
+ "constraint": "sh:qualifiedValueShape",
+ "path": q_path,
+ "reason": "the nested shape uses a form that cannot be evaluated; \
+ the qualified count was not taken",
+ }));
+ continue;
+ };
+ let q_min = row.get("qmin").and_then(|v| strip_quotes(v).parse::<i64>().ok());
+ let q_max = row.get("qmax").and_then(|v| strip_quotes(v).parse::<i64>().ok());
+ if q_min.is_none() && q_max.is_none() {
+ continue;
+ }
+ // OPTIONAL, so a focus node matching nothing still returns a row
+ // with a count of zero. An inner join would hide exactly the nodes
+ // a minimum count exists to catch.
+ let query = format!(
+ r#"SELECT ?focus (COUNT(DISTINCT ?val) AS ?n) WHERE {{
+ {focus_pattern}
+ OPTIONAL {{ ?focus <{q_path}> ?val . FILTER({clause}) }}
+ }} GROUP BY ?focus"#
+ );
+ for result in &graph_sparql_select(graph, &query)? {
+ let (Some(focus), Some(n_raw)) = (result.get("focus"), result.get("n")) else {
+ continue;
+ };
+ let Ok(n) = strip_quotes(n_raw).parse::<i64>() else {
+ continue;
+ };
+ for (bound, breached, constraint, wording) in [
+ (q_min, q_min.is_some_and(|m| n < m), "qualifiedMinCount", "fewer than"),
+ (q_max, q_max.is_some_and(|m| n > m), "qualifiedMaxCount", "more than"),
+ ] {
+ if !breached {
+ continue;
+ }
+ let msg = if q_message.is_empty() {
+ format!(
+ "{n} value(s) conform to the qualified shape, {wording} the required {}",
+ bound.unwrap_or_default()
+ )
+ } else {
+ q_message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": q_severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": q_path,
+ "constraint": constraint,
+ "message": msg,
+ }));
+ }
+ }
+ }
+
// sh:in alternatives, collected per shape and keyed by path for the
// same blank-node reason as sh:or above.
let mut in_alternatives: HashMap<String, Vec<String>> = HashMap::new();
@@ -373,7 +795,7 @@ impl ShaclValidator {
r#"
PREFIX sh: <http://www.w3.org/ns/shacl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
- SELECT ?path ?member WHERE {{
+ SELECT ?prop ?path ?member WHERE {{
{} sh:property ?prop .
?prop sh:path ?path .
?prop sh:in/rdf:rest*/rdf:first ?member .
@@ -383,9 +805,9 @@ impl ShaclValidator {
),
)?;
for row in &in_rows {
- if let (Some(p), Some(m)) = (row.get("path"), row.get("member")) {
+ if let (Some(p), Some(m)) = (row.get("prop"), row.get("member")) {
in_alternatives
- .entry(strip_angle_brackets(p))
+ .entry(p.clone())
.or_default()
.push(m.trim().to_string());
}
@@ -393,6 +815,11 @@ impl ShaclValidator {
// 4. For each constraint, run SPARQL queries against the main graph
for prop in &props {
+ // Identifies THIS property shape among any that share its path.
+ // sh:or, sh:in and sh:not are collected per shape and looked up
+ // by this term; keying them by path merged sibling blocks into
+ // one and returned a clean run over data that broke both.
+ let prop_key = prop.get("prop").cloned();
let raw_path = match prop.get("path") {
Some(p) => strip_angle_brackets(p),
None => continue,
@@ -439,10 +866,10 @@ impl ShaclValidator {
.unwrap_or(0);
if min_count > 0 {
let query = format!(
- r#"SELECT ?focus (COUNT(?val) AS ?cnt) WHERE {{
- ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
+ r#"SELECT ?focus (COUNT(DISTINCT ?val) AS ?cnt) WHERE {{
+ {focus_pattern}
OPTIONAL {{ ?focus {path_expr} ?val }}
- }} GROUP BY ?focus HAVING (COUNT(?val) < {min_count})"#
+ }} GROUP BY ?focus HAVING (COUNT(DISTINCT ?val) < {min_count})"#
);
let results = graph_sparql_select(graph, &query)?;
for row in &results {
@@ -473,10 +900,10 @@ impl ShaclValidator {
.parse::<u64>()
.unwrap_or(u64::MAX);
let query = format!(
- r#"SELECT ?focus (COUNT(?val) AS ?cnt) WHERE {{
- ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
+ r#"SELECT ?focus (COUNT(DISTINCT ?val) AS ?cnt) WHERE {{
+ {focus_pattern}
?focus {path_expr} ?val .
- }} GROUP BY ?focus HAVING (COUNT(?val) > {max_count})"#
+ }} GROUP BY ?focus HAVING (COUNT(DISTINCT ?val) > {max_count})"#
);
let results = graph_sparql_select(graph, &query)?;
for row in &results {
@@ -509,7 +936,7 @@ impl ShaclValidator {
let cls = strip_angle_brackets(cls_str);
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_pattern}
?focus {path_expr} ?val .
FILTER NOT EXISTS {{
?val <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{cls}> .
@@ -538,9 +965,26 @@ impl ShaclValidator {
// sh:datatype
if let Some(dt_str) = prop.get("datatype") {
let dt = strip_angle_brackets(dt_str);
+ // The store cannot tell these apart from the type they are
+ // derived from, so the constraint is not decidable here and
+ // must not be answered. Asking anyway produced a violation
+ // for every value that satisfied the shape: nine of them in
+ // jsonld-escaping-conformance, which is how this was found.
+ if datatype_is_indistinguishable_in_store(&dt) {
+ skipped.push(serde_json::json!({
+ "shape": strip_angle_brackets(&shape_iri),
+ "constraint": "sh:datatype",
+ "path": path,
+ "datatype": dt,
+ "reason": "the store does not preserve this datatype IRI, so a value \
+ carrying it is indistinguishable from one carrying the type \
+ it derives from; the constraint was not evaluated",
+ }));
+ continue;
+ }
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_pattern}
?focus {path_expr} ?val .
FILTER(DATATYPE(?val) != <{dt}>)
}}"#
@@ -575,7 +1019,7 @@ impl ShaclValidator {
let escaped = pattern.replace('\\', "\\\\").replace('"', "\\\"");
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_pattern}
?focus {path_expr} ?val .
FILTER(!REGEX(STR(?val), "{escaped}"))
}}"#
@@ -613,11 +1057,11 @@ impl ShaclValidator {
// 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) {
+ if let Some(clauses) = prop_key.as_ref().and_then(|k| or_alternatives.get(k)) {
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_pattern}
?focus {path_expr} ?val .
FILTER(!({disjunction}))
}}"#
@@ -641,14 +1085,181 @@ impl ShaclValidator {
}
}
+ // sh:minLength / sh:maxLength over the string form of each value
+ // node. SHACL measures the lexical form of a literal and the
+ // string of an IRI, and makes a blank node a violation of either
+ // bound because it has no string form to measure. Both bounds are
+ // inclusive.
+ for (key, constraint, cmp, wording) in [
+ ("minLength", "minLength", "<", "shorter than"),
+ ("maxLength", "maxLength", ">", "longer than"),
+ ] {
+ let Some(bound_raw) = prop.get(key) else {
+ continue;
+ };
+ let Ok(bound) = strip_quotes(bound_raw).parse::<u64>() else {
+ skipped.push(serde_json::json!({
+ "shape": strip_angle_brackets(&shape_iri),
+ "constraint": format!("sh:{constraint}"),
+ "path": path,
+ "reason": "bound is not a non-negative integer; it was not evaluated",
+ }));
+ continue;
+ };
+ let query = format!(
+ r#"SELECT ?focus ?val WHERE {{
+ {focus_pattern}
+ ?focus {path_expr} ?val .
+ FILTER(isBlank(?val) || STRLEN(STR(?val)) {cmp} {bound})
+ }}"#
+ );
+ for row in &graph_sparql_select(graph, &query)? {
+ if let Some(focus) = row.get("focus") {
+ let msg = if message.is_empty() {
+ format!("Value is {wording} {bound} characters")
+ } else {
+ message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": path,
+ "constraint": constraint,
+ "message": msg,
+ }));
+ }
+ }
+ }
+
+ // sh:lessThan / sh:lessThanOrEquals compare the values of this
+ // path against the values of another property on the SAME focus
+ // node, which is why they take a predicate and not a value. A
+ // pair that cannot be ordered (comparing a string to an integer)
+ // makes the SPARQL comparison an error rather than false, and an
+ // error inside FILTER is dropped, so such a pair goes unreported
+ // instead of counting as a violation. That is the one place these
+ // two are weaker than pyshacl, and it is stated here rather than
+ // discovered later.
+ for (key, constraint, ok_cmp) in [
+ ("lessThan", "lessThan", "<"),
+ ("lessThanOrEquals", "lessThanOrEquals", "<="),
+ ] {
+ let Some(other_raw) = prop.get(key) else {
+ continue;
+ };
+ let other = strip_angle_brackets(other_raw);
+ let query = format!(
+ r#"SELECT DISTINCT ?focus WHERE {{
+ {focus_pattern}
+ ?focus {path_expr} ?val .
+ ?focus <{other}> ?otherVal .
+ FILTER(!(?val {ok_cmp} ?otherVal))
+ }}"#
+ );
+ for row in &graph_sparql_select(graph, &query)? {
+ if let Some(focus) = row.get("focus") {
+ let msg = if message.is_empty() {
+ format!("Value is not {ok_cmp} the value of <{other}>")
+ } else {
+ message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": path,
+ "constraint": constraint,
+ "message": msg,
+ }));
+ }
+ }
+ }
+
+ // sh:node: every value on the path must conform to another
+ // node shape. The referenced shape is compiled into a boolean
+ // expression over the value node; if any part of it cannot be
+ // compiled the whole constraint is recorded as unevaluated,
+ // because a half-checked nested shape reads as a clean one.
+ if let Some(node_ref) = prop.get("node") {
+ match compile_node_shape(&shapes_store, node_ref.trim(), "nodeval", 0) {
+ Some(expr) => {
+ let query = format!(
+ r#"SELECT DISTINCT ?focus WHERE {{
+ {focus_pattern}
+ ?focus {path_expr} ?nodeval .
+ FILTER(!({expr}))
+ }}"#
+ );
+ for row in &graph_sparql_select(graph, &query)? {
+ if let Some(focus) = row.get("focus") {
+ let msg = if message.is_empty() {
+ format!(
+ "Value does not conform to <{}>",
+ strip_angle_brackets(node_ref)
+ )
+ } else {
+ message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": path,
+ "constraint": "node",
+ "message": msg,
+ }));
+ }
+ }
+ }
+ None => skipped.push(serde_json::json!({
+ "shape": strip_angle_brackets(&shape_iri),
+ "constraint": "sh:node",
+ "path": path,
+ "node_shape": strip_angle_brackets(node_ref),
+ "reason": "the referenced shape uses a form that cannot be compiled, \
+ or nests deeper than the bound; it was not evaluated",
+ })),
+ }
+ }
+
+ // sh:not: no value on the path may satisfy the nested shape.
+ // The clauses were collected for this shape above and keyed by
+ // path; a value matching one of them is the violation, which is
+ // the sh:or filter with the negation removed rather than added.
+ if let Some(clauses) = prop_key.as_ref().and_then(|k| not_clauses.get(k)) {
+ let conjunction = clauses.join(" && ");
+ let query = format!(
+ r#"SELECT ?focus ?val WHERE {{
+ {focus_pattern}
+ ?focus {path_expr} ?val .
+ FILTER({conjunction})
+ }}"#
+ );
+ 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 a shape forbidden by sh:not".to_string()
+ } else {
+ message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": path,
+ "constraint": "not",
+ "message": msg,
+ }));
+ }
+ }
+ }
+
// sh:in: the value must be one of an enumerated list of terms.
// Members arrive from the shapes store in N-Triples form, which is
// valid SPARQL as written, so no term needs rebuilding.
- if let Some(members) = in_alternatives.get(&path) {
+ if let Some(members) = prop_key.as_ref().and_then(|k| in_alternatives.get(k)) {
let list = members.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_pattern}
?focus {path_expr} ?val .
FILTER(?val NOT IN ({list}))
}}"#
@@ -693,7 +1304,7 @@ impl ShaclValidator {
Some(t) => {
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_pattern}
?focus {path_expr} ?val .
FILTER(!{t})
}}"#
@@ -733,7 +1344,7 @@ impl ShaclValidator {
let term = has_value_term.trim();
let query = format!(
r#"SELECT ?focus 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_pattern}
FILTER NOT EXISTS {{ ?focus {path_expr} {term} }}
}}"#
);
@@ -776,7 +1387,7 @@ impl ShaclValidator {
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_pattern}
?focus {path_expr} ?val .
FILTER(!COALESCE(?val {satisfy_op} {bound}, false))
}}"#
@@ -810,15 +1421,9 @@ impl ShaclValidator {
// A validator that reports success on rules it never ran is worse than
// one that refuses, so every constraint here is either executed or
// recorded in skipped_constraints, and skipping suppresses `conforms`.
- for shape in &shapes {
- let target_class = match shape.get("targetClass") {
- Some(tc) => strip_angle_brackets(tc),
- None => continue,
- };
- let shape_iri = match shape.get("shape") {
- Some(s) => s.clone(),
- None => continue,
- };
+ for (shape_term, kind, target_value) in &targets {
+ let this_pattern = target_pattern(kind, target_value, "this");
+ let shape_iri = shape_term.clone();
let constraints = query_solutions(
&shapes_store,
@@ -844,7 +1449,7 @@ impl ShaclValidator {
// rather than assumed harmless.
let focus_rows = graph_sparql_select(
graph,
- &format!("SELECT ?this WHERE {{ ?this <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> }}"),
+ &format!("SELECT ?this WHERE {{ {this_pattern} }}"),
)?;
let focus_nodes: Vec<String> = focus_rows
.iter()
@@ -893,9 +1498,14 @@ impl ShaclValidator {
// wrapping the author's SELECT as a subquery so that nothing is
// spliced into the middle of their query text.
let inner = select_raw.replace("$this", "?this");
+ // The author's own PREFIX and BASE declarations have to be lifted
+ // out of the subquery position and put where SPARQL allows them,
+ // or the wrapper cannot parse at all. See split_sparql_prologue.
+ let (author_prologue, inner_body) = split_sparql_prologue(&inner);
let values = focus_nodes.join(" ");
let wrapped = format!(
- "{prefix_block}SELECT ?this WHERE {{ VALUES ?this {{ {values} }} {{ {inner} }} }}"
+ "{prefix_block}{author_prologue}SELECT ?this WHERE \
+ {{ VALUES ?this {{ {values} }} {{ {inner_body} }} }}"
);
match graph_sparql_select(graph, &wrapped) {
@@ -951,8 +1561,15 @@ impl ShaclValidator {
)
.map(|r| !r.is_empty())
.unwrap_or(false);
- let nothing_matched =
- (!shapes.is_empty() && focus_nodes_total == 0) || (shapes.is_empty() && declared_any_shape);
+ // Counted over targets, not over class-targeted shapes. While
+ // `sh:targetClass` was the only form that selected anything, a shapes
+ // graph declaring a NodeShape and yielding no class target had selected
+ // nothing, and that is what this measured. It no longer follows: such a
+ // graph may target by node, by subjects-of or by objects-of and select
+ // plenty. Left on `shapes`, the guard suppressed the verdict of every
+ // run whose targets were all explicit, however many nodes they checked.
+ let nothing_matched = (!targets.is_empty() && focus_nodes_total == 0)
+ || (targets.is_empty() && declared_any_shape);
let mut report = serde_json::json!({
"violation_count": violations.len(),
@@ -974,8 +1591,8 @@ impl ShaclValidator {
// same lie as reporting it for a constraint that never ran.
report["conforms"] = serde_json::Value::Null;
report["warning"] = serde_json::Value::String(format!(
- "no focus nodes matched: all {} shape(s) target classes absent from the data, so conformance is undetermined. See unmatched_shapes.",
- shapes.len()
+ "no focus nodes matched: all {} target(s) selected nothing in the data, so conformance is undetermined. See unmatched_shapes.",
+ targets.len()
));
} else if skipped.is_empty() {
report["conforms"] = serde_json::Value::Bool(violations.is_empty());
@@ -1298,9 +1915,346 @@ fn is_recognised_xsd_datatype(iri: &str) -> bool {
///
/// Used to tell "checked and clean" apart from "checked nothing": a shape whose
/// target class has no instances passes every constraint vacuously.
-fn count_focus_nodes(graph: &Arc<GraphStore>, target_class: &str) -> anyhow::Result<u64> {
+/// How deep `sh:node` is followed before the compiler gives up.
+///
+/// A shapes graph may reference itself, directly or around a cycle, and a
+/// compiler that follows it has no natural stopping point. Bounding it and
+/// reporting the bound is the only honest option: an unbounded compile does not
+/// return, and a silent cutoff would produce a filter that checks less than the
+/// shape says.
+const MAX_NESTED_SHAPE_DEPTH: usize = 5;
+
+/// Compile a node shape into a SPARQL boolean expression that is true when the
+/// term bound to `var` conforms to it.
+///
+/// Returns `None` if any constraint in the shape, or in a shape it references,
+/// cannot be compiled. That is deliberately all-or-nothing. A partially compiled
+/// nested shape would answer for the constraints it understood and stay silent on
+/// the rest, which reads to the caller as conformance with the whole shape: the
+/// false clean this validator must not produce. The caller records the whole
+/// `sh:node` as unevaluated instead.
+///
+/// The supported forms are the ones the HealthDCAT-AP shapes use, which is what
+/// the health-dataset-catalogue vertical validates against: `sh:minCount` and
+/// `sh:maxCount` of 0 or 1, `sh:class`, `sh:datatype`, `sh:nodeKind`,
+/// `sh:hasValue`, and `sh:node` for the recursion. A count other than 0 or 1
+/// needs an aggregate, which SPARQL will not evaluate inside a FILTER, so it is
+/// not compiled rather than approximated.
+fn compile_node_shape(
+ shapes_store: &Store,
+ shape_term: &str,
+ var: &str,
+ depth: usize,
+) -> Option<String> {
+ if depth > MAX_NESTED_SHAPE_DEPTH {
+ return None;
+ }
+ let mut clauses: Vec<String> = Vec::new();
+
+ // Constraints asserted on the shape node itself apply to the value node.
+ let node_level = query_solutions(
+ shapes_store,
+ &format!(
+ r#"
+ PREFIX sh: <http://www.w3.org/ns/shacl#>
+ SELECT ?pred ?obj WHERE {{
+ {shape_term} ?pred ?obj .
+ FILTER(?pred NOT IN (
+ sh:property, sh:name, sh:description, sh:message, sh:severity,
+ sh:order, sh:group, sh:targetClass, sh:targetNode,
+ sh:targetSubjectsOf, sh:targetObjectsOf,
+ <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>,
+ <http://www.w3.org/2000/01/rdf-schema#label>,
+ <http://www.w3.org/2000/01/rdf-schema#comment>
+ ))
+ }}
+ "#
+ ),
+ )
+ .ok()?;
+ for row in &node_level {
+ let (Some(pred), Some(obj)) = (row.get("pred"), row.get("obj")) else {
+ return None;
+ };
+ let pred = strip_angle_brackets(pred);
+ let local = pred.rsplit('#').next().unwrap_or_default();
+ match local {
+ "class" => clauses.push(format!(
+ "EXISTS {{ ?{var} <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{}> }}",
+ strip_angle_brackets(obj)
+ )),
+ "datatype" => clauses.push(format!(
+ "DATATYPE(?{var}) = <{}>",
+ strip_angle_brackets(obj)
+ )),
+ "nodeKind" => clauses.push(node_kind_test(&strip_angle_brackets(obj), var)?),
+ _ => return None,
+ }
+ }
+
+ // Property shapes. `?prop` is bound rather than spliced, for the same reason
+ // it is elsewhere: a property shape is almost always a blank node, and a
+ // blank-node label inside a query is a fresh variable, not a reference.
+ let props = query_solutions(
+ shapes_store,
+ &format!(
+ r#"
+ PREFIX sh: <http://www.w3.org/ns/shacl#>
+ SELECT ?prop ?path ?minCount ?maxCount ?class ?datatype ?nodeKind ?hasValue ?node ?other WHERE {{
+ {shape_term} sh:property ?prop .
+ ?prop sh:path ?path .
+ OPTIONAL {{ ?prop sh:minCount ?minCount }}
+ OPTIONAL {{ ?prop sh:maxCount ?maxCount }}
+ OPTIONAL {{ ?prop sh:class ?class }}
+ OPTIONAL {{ ?prop sh:datatype ?datatype }}
+ OPTIONAL {{ ?prop sh:nodeKind ?nodeKind }}
+ OPTIONAL {{ ?prop sh:hasValue ?hasValue }}
+ OPTIONAL {{ ?prop sh:node ?node }}
+ OPTIONAL {{
+ ?prop ?other ?_v .
+ FILTER(?other NOT IN (
+ sh:path, sh:minCount, sh:maxCount, sh:class, sh:datatype,
+ sh:nodeKind, sh:hasValue, sh:node,
+ sh:name, sh:description, sh:message, sh:severity,
+ sh:order, sh:group,
+ <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
+ ))
+ }}
+ }}
+ "#
+ ),
+ )
+ .ok()?;
+ for (i, row) in props.iter().enumerate() {
+ if row.get("other").is_some() {
+ return None;
+ }
+ let path = strip_angle_brackets(row.get("path")?);
+ // A blank-node path is a property-path expression, which this compiler
+ // does not read. Not compiled rather than guessed at.
+ if !row.get("path")?.trim().starts_with('<') {
+ return None;
+ }
+ let inner = format!("{var}_{depth}_{i}");
+
+ if let Some(min) = row.get("minCount") {
+ match strip_quotes(min).parse::<u64>().ok()? {
+ 0 => {}
+ 1 => clauses.push(format!("EXISTS {{ ?{var} <{path}> ?{inner} }}")),
+ _ => return None,
+ }
+ }
+ if let Some(max) = row.get("maxCount") {
+ match strip_quotes(max).parse::<u64>().ok()? {
+ 0 => clauses.push(format!("NOT EXISTS {{ ?{var} <{path}> ?{inner} }}")),
+ 1 => clauses.push(format!(
+ "NOT EXISTS {{ ?{var} <{path}> ?{inner}a . ?{var} <{path}> ?{inner}b . FILTER(?{inner}a != ?{inner}b) }}"
+ )),
+ _ => return None,
+ }
+ }
+ if let Some(hv) = row.get("hasValue") {
+ clauses.push(format!("EXISTS {{ ?{var} <{path}> {} }}", hv.trim()));
+ }
+ // The value-level constraints hold for EVERY value on the path, so each
+ // is written as the absence of a counterexample.
+ if let Some(c) = row.get("class") {
+ clauses.push(format!(
+ "NOT EXISTS {{ ?{var} <{path}> ?{inner} . FILTER NOT EXISTS {{ ?{inner} <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{}> }} }}",
+ strip_angle_brackets(c)
+ ));
+ }
+ if let Some(dt) = row.get("datatype") {
+ let dt = strip_angle_brackets(dt);
+ // The store cannot tell these apart from the type they derive from,
+ // so a nested shape resting on one is not decidable either.
+ if datatype_is_indistinguishable_in_store(&dt) {
+ return None;
+ }
+ clauses.push(format!(
+ "NOT EXISTS {{ ?{var} <{path}> ?{inner} . FILTER(DATATYPE(?{inner}) != <{dt}>) }}"
+ ));
+ }
+ if let Some(nk) = row.get("nodeKind") {
+ let test = node_kind_test(&strip_angle_brackets(nk), &inner)?;
+ clauses.push(format!(
+ "NOT EXISTS {{ ?{var} <{path}> ?{inner} . FILTER(!({test})) }}"
+ ));
+ }
+ if let Some(node) = row.get("node") {
+ let nested = compile_node_shape(shapes_store, node.trim(), &inner, depth + 1)?;
+ clauses.push(format!(
+ "NOT EXISTS {{ ?{var} <{path}> ?{inner} . FILTER(!({nested})) }}"
+ ));
+ }
+ }
+
+ if clauses.is_empty() {
+ // Nothing to check. That is only meaningful if the shapes graph actually
+ // declares this shape: an empty conjunction is `true`, so a reference to
+ // a shape defined in some other file would otherwise be satisfied by
+ // every value node, a false clean produced by absence rather than by a
+ // wrong answer. The HealthDCAT-AP shapes reference three DCAT-AP shapes
+ // that live elsewhere, so this is the ordinary case.
+ let declared = query_solutions(
+ shapes_store,
+ &format!(
+ r#"PREFIX sh: <http://www.w3.org/ns/shacl#>
+ ASK_SUBSTITUTE
+ SELECT ?p WHERE {{ {shape_term} a ?type . FILTER(?type IN (sh:NodeShape, sh:PropertyShape)) }}"#
+ )
+ .replace("ASK_SUBSTITUTE\n ", ""),
+ )
+ .ok()?;
+ if declared.is_empty() {
+ return None;
+ }
+ return Some("true".to_string());
+ }
+ Some(clauses.join(" && "))
+}
+
+/// The SPARQL test for one `sh:nodeKind` value, or None for a value this
+/// compiler does not know, so an unfamiliar node kind is never treated as passing.
+fn node_kind_test(node_kind: &str, var: &str) -> Option<String> {
+ Some(match node_kind.rsplit('#').next().unwrap_or_default() {
+ "IRI" => format!("isIRI(?{var})"),
+ "Literal" => format!("isLiteral(?{var})"),
+ "BlankNode" => format!("isBlank(?{var})"),
+ "BlankNodeOrIRI" => format!("(isBlank(?{var}) || isIRI(?{var}))"),
+ "BlankNodeOrLiteral" => format!("(isBlank(?{var}) || isLiteral(?{var}))"),
+ "IRIOrLiteral" => format!("(isIRI(?{var}) || isLiteral(?{var}))"),
+ _ => return None,
+ })
+}
+
+/// Datatype IRIs the storage layer does not preserve.
+///
+/// oxigraph 0.5 encodes a literal by value, and in `numeric_encoder.rs` twelve
+/// XSD integer-derived datatype IRIs all route to `parse_integer_str`, which
+/// yields `EncodedTerm::IntegerLiteral` — one variant, carrying no datatype IRI.
+/// Reading back can only reconstruct `xsd:integer`. `xsd:dateTimeStamp` collapses
+/// into `xsd:dateTime` the same way. The Turtle parser is correct; the loss is at
+/// storage. That it is a defect rather than a deliberate simplification is settled
+/// by `xsd:yearMonthDuration` and `xsd:dayTimeDuration`, equally derived, which
+/// have their own encodings and survive intact.
+///
+/// A `sh:datatype` constraint naming one of these cannot be decided against the
+/// store: a conforming value and a widened one are the same term by the time the
+/// query runs. Answering anyway reports a violation for every value that in fact
+/// satisfies the shape.
+fn datatype_is_indistinguishable_in_store(datatype: &str) -> bool {
+ const XSD: &str = "http://www.w3.org/2001/XMLSchema#";
+ let Some(local) = datatype.strip_prefix(XSD) else {
+ return false;
+ };
+ matches!(
+ local,
+ "byte"
+ | "short"
+ | "int"
+ | "long"
+ | "unsignedByte"
+ | "unsignedShort"
+ | "unsignedInt"
+ | "unsignedLong"
+ | "positiveInteger"
+ | "negativeInteger"
+ | "nonPositiveInteger"
+ | "nonNegativeInteger"
+ | "dateTimeStamp"
+ )
+}
+
+/// Split a SPARQL query into its prologue (PREFIX and BASE declarations, with any
+/// leading comments) and the body that follows.
+///
+/// SPARQL permits PREFIX and BASE only in the prologue, at the very start of a
+/// query. SHACL pre-binds `$this`, and this validator binds it by wrapping the
+/// author's SELECT as a subquery under a VALUES clause, which puts any prologue
+/// the author wrote into a position where it cannot parse and takes the whole
+/// query down with it. Hoisting it to the front of the wrapper is the fix.
+///
+/// Declaring prefixes inside `sh:select` is the portable way to write a SPARQL
+/// constraint and is what pyshacl accepts. All seven `sh:sparql` constraints in
+/// the banking vertical were being reported as unrunnable for this reason alone,
+/// found by the differential run against pyshacl rather than by any unit test.
+fn split_sparql_prologue(query: &str) -> (String, &str) {
+ let mut prologue = String::new();
+ let mut rest = query;
+ loop {
+ let trimmed = rest.trim_start();
+ if let Some(line) = trimmed.strip_prefix('#') {
+ // A comment carries no meaning to the parser but may carry a lot to
+ // a reader, so it is moved rather than dropped.
+ let end = line.find('\n').map(|i| i + 2).unwrap_or(trimmed.len());
+ prologue.push_str(&trimmed[..end]);
+ rest = &trimmed[end..];
+ continue;
+ }
+ let lower = trimmed.to_ascii_lowercase();
+ let keyword_len = if lower.starts_with("prefix") {
+ 6
+ } else if lower.starts_with("base") {
+ 4
+ } else {
+ return (prologue, trimmed);
+ };
+ // Require a separator after the keyword so an identifier merely starting
+ // with those letters is not mistaken for a declaration.
+ match trimmed[keyword_len..].chars().next() {
+ Some(c) if c.is_whitespace() || c == '<' => {}
+ _ => return (prologue, trimmed),
+ }
+ // Every declaration ends at the closing '>' of its IRI.
+ match trimmed.find('>') {
+ Some(i) => {
+ prologue.push_str(&trimmed[..=i]);
+ prologue.push('\n');
+ rest = &trimmed[i + 1..];
+ }
+ None => return (prologue, trimmed),
+ }
+ }
+}
+
+/// The SPARQL pattern selecting the focus nodes of one target, bound to `var`.
+///
+/// Note for anyone counting over the result: the class selector binds a focus
+/// node ONCE PER PATH to the target class, so a node typed two ways under one
+/// class is bound twice. Every count taken over this pattern must therefore
+/// count DISTINCT value nodes. Counting rows instead inflated maxCount into 258
+/// false violations on the investment-fund vertical, which loads a FIBO
+/// alignment supplying the extra subclass paths, and would equally have hidden
+/// a minCount breach.
+///
+/// One function, so the two passes that need focus nodes — property constraints
+/// and `sh:sparql` constraints — cannot drift apart on what a target means. That
+/// drift is not hypothetical: the two passes each had their own copy of the class
+/// selector, and a fix to one would silently have left the other behind.
+///
+/// `sh:targetClass` selects SHACL instances: rdf:type followed by zero or more
+/// rdfs:subClassOf steps. The other three forms are explicit, and `sh:targetNode`
+/// uses VALUES rather than a triple pattern because it must select its node even
+/// when that node appears in no triple.
+fn target_pattern(kind: &str, value: &str, var: &str) -> String {
+ match kind {
+ "class" => format!(
+ "?{var} <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{value}>"
+ ),
+ "node" => format!("VALUES ?{var} {{ {value} }}"),
+ "subjectsOf" => format!("?{var} {value} ?_target_object"),
+ _ => format!("?_target_subject {value} ?{var}"),
+ }
+}
+
+/// Count the focus nodes a target selects, given the SPARQL pattern that binds
+/// `?focus`. Taking the pattern rather than a class is what lets all four target
+/// forms share one counter, and keeps `focus_nodes` in the report meaning the
+/// same thing whichever form selected them.
+fn count_focus_nodes(graph: &Arc<GraphStore>, focus_pattern: &str) -> anyhow::Result<u64> {
let query = format!(
- r#"SELECT (COUNT(DISTINCT ?focus) AS ?cnt) WHERE {{ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> }}"#
+ r#"SELECT (COUNT(DISTINCT ?focus) AS ?cnt) WHERE {{ {focus_pattern} }}"#
);
let rows = graph_sparql_select(graph, &query)?;
Ok(rows
diff --git a/tests/datatype_preservation_test.rs b/tests/datatype_preservation_test.rs
new file mode 100644
index 00000000..b3c604d9
--- /dev/null
+++ b/tests/datatype_preservation_test.rs
@@ -0,0 +1,199 @@
+//! Derived XSD datatypes must survive a load.
+//!
+//! RDF 1.1 makes the datatype IRI part of a literal's identity: `"0"^^xsd:integer`
+//! and `"0"^^xsd:nonNegativeInteger` are different terms. A store that returns the
+//! first when given the second has changed the data, and two things break at once.
+//!
+//! 1. Every `sh:datatype` constraint naming a derived integer type reports a
+//! violation against data that satisfies it. Nine such false violations in
+//! `jsonld-escaping-conformance` were the first sign, found by the
+//! differential run against pyshacl.
+//! 2. Anything written back out carries the widened type, so a published file
+//! no longer says what its author said.
+//!
+//! These tests separate the two places the loss could happen — the parser or the
+//! store — because the fix is in a different codebase depending on the answer.
+
+use open_ontologies::graph::GraphStore;
+use oxigraph::io::{RdfFormat, RdfParser};
+use oxigraph::model::Term;
+use oxigraph::sparql::{QueryResults, SparqlEvaluator};
+use oxigraph::store::Store;
+use std::io::Cursor;
+use std::sync::Arc;
+
+const XSD: &str = "http://www.w3.org/2001/XMLSchema#";
+
+/// One literal per datatype the SHACL corpus actually uses.
+const DOC: &str = r#"
+@prefix ex: <http://example.org/> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ex:s
+ ex:nonNegativeInteger "0"^^xsd:nonNegativeInteger ;
+ ex:positiveInteger "1"^^xsd:positiveInteger ;
+ ex:negativeInteger "-1"^^xsd:negativeInteger ;
+ ex:nonPositiveInteger "0"^^xsd:nonPositiveInteger ;
+ ex:long "5"^^xsd:long ;
+ ex:int "5"^^xsd:int ;
+ ex:short "5"^^xsd:short ;
+ ex:byte "5"^^xsd:byte ;
+ ex:unsignedLong "5"^^xsd:unsignedLong ;
+ ex:unsignedInt "5"^^xsd:unsignedInt ;
+ ex:unsignedShort "5"^^xsd:unsignedShort ;
+ ex:unsignedByte "5"^^xsd:unsignedByte ;
+ ex:integer "5"^^xsd:integer ;
+ ex:decimal "5.5"^^xsd:decimal ;
+ ex:token "abc"^^xsd:token ;
+ ex:anyURI "http://x.example/"^^xsd:anyURI ;
+ ex:date "2026-01-01"^^xsd:date .
+"#;
+
+/// The predicate local name is the datatype local name, so a mismatch names itself.
+fn expected_from_predicate(p: &str) -> String {
+ p.rsplit('/').next().unwrap_or_default().to_string()
+}
+
+#[test]
+fn the_parser_preserves_every_declared_datatype() {
+ let parser = RdfParser::from_format(RdfFormat::Turtle);
+ let mut wrong = Vec::new();
+ for quad in parser.for_reader(Cursor::new(DOC.as_bytes())) {
+ let quad = quad.expect("the document parses");
+ let want = expected_from_predicate(quad.predicate.as_str());
+ if let Term::Literal(lit) = &quad.object {
+ let got = lit.datatype().as_str().trim_start_matches(XSD).to_string();
+ if got != want {
+ wrong.push(format!("{want} parsed as {got}"));
+ }
+ }
+ }
+ assert!(
+ wrong.is_empty(),
+ "the Turtle parser changed {} datatype(s): {wrong:?}",
+ wrong.len()
+ );
+}
+
+fn datatypes_after_insert(store: &Store) -> Vec<String> {
+ let mut wrong = Vec::new();
+ let results = SparqlEvaluator::new()
+ .parse_query("SELECT ?p (DATATYPE(?v) AS ?dt) WHERE { ?s ?p ?v }")
+ .unwrap()
+ .on_store(store)
+ .execute()
+ .unwrap();
+ if let QueryResults::Solutions(solutions) = results {
+ for solution in solutions {
+ let solution = solution.unwrap();
+ let (Some(p), Some(dt)) = (solution.get("p"), solution.get("dt")) else {
+ continue;
+ };
+ let want = expected_from_predicate(&p.to_string().replace(['<', '>'], ""));
+ let got = dt
+ .to_string()
+ .replace(['<', '>'], "")
+ .trim_start_matches(XSD)
+ .to_string();
+ if got != want {
+ wrong.push(format!("{want} stored as {got}"));
+ }
+ }
+ }
+ wrong.sort();
+ wrong
+}
+
+/// The exact set of datatypes oxigraph 0.5 does not preserve.
+///
+/// This is a characterisation test, not an aspiration: it pins current upstream
+/// behaviour so the guard in `shacl.rs` can be trusted to cover exactly the right
+/// IRIs and no others. It fails in both directions on purpose. If oxigraph starts
+/// preserving these, it fails and the guard should be removed. If it starts losing
+/// something new, it fails and the guard is missing a case.
+const COLLAPSES_TO_INTEGER: [&str; 12] = [
+ "byte", "short", "int", "long",
+ "unsignedByte", "unsignedShort", "unsignedInt", "unsignedLong",
+ "positiveInteger", "negativeInteger", "nonPositiveInteger", "nonNegativeInteger",
+];
+
+#[test]
+fn the_store_loses_exactly_the_known_datatypes_and_no_others() {
+ let store = Store::new().unwrap();
+ let parser = RdfParser::from_format(RdfFormat::Turtle);
+ for quad in parser.for_reader(Cursor::new(DOC.as_bytes())) {
+ store.insert(quad.unwrap().as_ref()).unwrap();
+ }
+ let mut lost: Vec<String> = datatypes_after_insert(&store)
+ .iter()
+ .filter_map(|line| line.split(" stored as ").next().map(str::to_string))
+ .collect();
+ lost.sort();
+ let mut want: Vec<String> = COLLAPSES_TO_INTEGER.iter().map(|s| s.to_string()).collect();
+ want.sort();
+ assert_eq!(
+ lost, want,
+ "the set of datatypes oxigraph drops has changed. If it shrank, remove the \
+ matching arm from datatype_is_indistinguishable_in_store. If it grew, add one."
+ );
+}
+
+/// The same set, through the path the tools actually take, so a regression is
+/// attributed to the right layer rather than to whichever test runs first.
+#[test]
+fn graph_store_load_loses_exactly_the_same_set() {
+ let graph = Arc::new(GraphStore::new());
+ graph.load_turtle(DOC, None).unwrap();
+ let json = graph
+ .sparql_select("SELECT ?p (DATATYPE(?v) AS ?dt) WHERE { ?s ?p ?v }")
+ .unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
+ let mut lost = Vec::new();
+ for row in parsed["results"].as_array().cloned().unwrap_or_default() {
+ let p = row["p"].as_str().unwrap_or_default().replace(['<', '>'], "");
+ let dt = row["dt"].as_str().unwrap_or_default().replace(['<', '>'], "");
+ let want = expected_from_predicate(&p);
+ if dt.trim_start_matches(XSD) != want {
+ lost.push(want);
+ }
+ }
+ lost.sort();
+ let mut want: Vec<String> = COLLAPSES_TO_INTEGER.iter().map(|s| s.to_string()).collect();
+ want.sort();
+ assert_eq!(lost, want, "the loss through load_turtle no longer matches the raw store");
+}
+
+/// The evaluator collapses the same set, independently of storage.
+///
+/// A literal typed in the query text is never stored, so this isolates
+/// `spareval` from `oxigraph`'s encoder. It is why the SHACL guard cannot be
+/// lifted by fixing storage alone: `DATATYPE()` would still answer wrongly.
+///
+/// `xsd:token` is checked alongside as a control. It is a derived type too, and
+/// it survives, so the behaviour is specific to this set rather than a general
+/// canonicalisation policy.
+#[test]
+fn the_evaluator_collapses_the_same_set_without_any_storage() {
+ let graph = Arc::new(GraphStore::new());
+ let json = graph
+ .sparql_select(
+ r#"SELECT
+ (DATATYPE("0"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger>) AS ?derived)
+ (DATATYPE("abc"^^<http://www.w3.org/2001/XMLSchema#token>) AS ?control)
+ WHERE { }"#,
+ )
+ .unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
+ let row = &parsed["results"][0];
+ assert_eq!(
+ row["derived"].as_str().unwrap_or_default().replace(['<', '>'], ""),
+ format!("{XSD}integer"),
+ "if this now answers nonNegativeInteger the evaluator is fixed; \
+ check the storage layer too before lifting the SHACL guard"
+ );
+ assert_eq!(
+ row["control"].as_str().unwrap_or_default().replace(['<', '>'], ""),
+ format!("{XSD}token"),
+ "the control must keep its datatype; if it does not, the defect is wider \
+ than the recorded set"
+ );
+}
diff --git a/tests/shacl_datatype_indistinguishable_test.rs b/tests/shacl_datatype_indistinguishable_test.rs
new file mode 100644
index 00000000..e8152f8f
--- /dev/null
+++ b/tests/shacl_datatype_indistinguishable_test.rs
@@ -0,0 +1,111 @@
+//! `sh:datatype` naming a type the store does not preserve.
+//!
+//! oxigraph 0.5 encodes twelve XSD integer-derived datatypes, and
+//! `xsd:dateTimeStamp`, into the encoding of the type they derive from, dropping
+//! the datatype IRI. See `datatype_is_indistinguishable_in_store`, and
+//! `datatype_preservation_test` for the isolation showing the parser is correct
+//! and the store is not.
+//!
+//! The consequence for validation is that a `sh:datatype xsd:nonNegativeInteger`
+//! constraint cannot be decided: by the time the query runs, a conforming literal
+//! and a widened one are the same term. Asking anyway reported a violation
+//! against every value that satisfied the shape — nine of them in
+//! `jsonld-escaping-conformance`, which is how the storage defect was found.
+//!
+//! A wrong answer is worse than no answer, so the constraint is recorded as
+//! unevaluated and the verdict is suppressed, exactly as for any other constraint
+//! this validator cannot execute.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+fn store() -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ ex:a a ex:Profile ; ex:passes "0"^^xsd:nonNegativeInteger ; ex:name "extruct" .
+ ex:b a ex:Profile ; ex:passes "1"^^xsd:nonNegativeInteger ; ex:name "nodejs" .
+ "#,
+ None,
+ )
+ .unwrap();
+ store
+}
+
+#[test]
+fn a_datatype_the_store_cannot_preserve_is_not_answered() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Profile ;
+ sh:property [ sh:path ex:passes ; sh:datatype xsd:nonNegativeInteger ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(
+ r["violation_count"],
+ serde_json::json!(0),
+ "the data satisfies this shape; reporting a violation is the bug: {r}"
+ );
+ assert!(
+ r["conforms"].is_null(),
+ "the constraint could not be decided, so there is no verdict to give: {r}"
+ );
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert_eq!(skipped.len(), 1, "{r}");
+ assert_eq!(skipped[0]["constraint"], "sh:datatype");
+ assert_eq!(
+ skipped[0]["datatype"],
+ "http://www.w3.org/2001/XMLSchema#nonNegativeInteger"
+ );
+}
+
+/// The datatypes the store does keep must still be checked, and still catch a
+/// real mismatch. Suppressing the whole constraint family would trade a false
+/// violation for a blind spot.
+#[test]
+fn a_datatype_the_store_preserves_is_still_evaluated() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Profile ;
+ sh:property [ sh:path ex:name ; sh:datatype xsd:string ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(true), "{r}");
+
+ let wrong = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Profile ;
+ sh:property [ sh:path ex:name ; sh:datatype xsd:date ] .
+ "#;
+ let r = report(&store(), wrong);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(2), "{r}");
+}
+
+/// `xsd:integer` itself is the type the others collapse into, so it is decidable
+/// and must not be caught by the guard.
+#[test]
+fn plain_integer_is_still_evaluated() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Profile ;
+ sh:property [ sh:path ex:passes ; sh:datatype xsd:integer ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert!(!r["conforms"].is_null(), "must give a verdict: {r}");
+}
diff --git a/tests/shacl_multipath_target_count_test.rs b/tests/shacl_multipath_target_count_test.rs
new file mode 100644
index 00000000..b3b58e3b
--- /dev/null
+++ b/tests/shacl_multipath_target_count_test.rs
@@ -0,0 +1,109 @@
+//! Counting when a focus node reaches its target class by more than one path.
+//!
+//! `sh:targetClass` selects SHACL instances, which is `rdf:type` followed by zero
+//! or more `rdfs:subClassOf` steps. That pattern binds a focus node once per
+//! distinct path, so a node typed two ways under one class, or typed at two
+//! levels of one chain, is bound twice. `COUNT(?val)` over that join then counts
+//! every value once per binding.
+//!
+//! It breaks both count constraints, in opposite and equally bad directions:
+//!
+//! * `sh:maxCount` fires on data that satisfies it. 258 such violations on the
+//! investment-fund vertical, which loads a FIBO alignment supplying the extra
+//! subclass paths. Found by the differential run against pyshacl.
+//! * `sh:minCount` is hidden by the same inflation: a node with one value and
+//! two bindings counts two, so `minCount 2` passes on data that breaks it.
+//! A false clean, which is the failure this validator must not have.
+//!
+//! Counting distinct value nodes is the fix, and it is what pyshacl reports.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+/// `ex:a` is both an `ex:Equity` and an `ex:Bond`, and both are subclasses of
+/// `ex:Instrument`, so it reaches the target class twice. It carries exactly one
+/// `ex:isin`.
+fn store() -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ ex:Equity rdfs:subClassOf ex:Instrument .
+ ex:Bond rdfs:subClassOf ex:Instrument .
+ ex:a a ex:Equity, ex:Bond ; ex:isin "GB0000000001" .
+ "#,
+ None,
+ )
+ .unwrap();
+ store
+}
+
+#[test]
+fn max_count_does_not_fire_on_a_node_reached_by_two_paths() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Instrument ;
+ sh:property [ sh:path ex:isin ; sh:maxCount 1 ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(
+ r["conforms"],
+ serde_json::json!(true),
+ "ex:a has one isin; counting it twice is the bug: {r}"
+ );
+ assert_eq!(r["violation_count"], serde_json::json!(0), "{r}");
+}
+
+#[test]
+fn min_count_still_fires_on_a_node_reached_by_two_paths() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Instrument ;
+ sh:property [ sh:path ex:isin ; sh:minCount 2 ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(
+ r["conforms"],
+ serde_json::json!(false),
+ "one value cannot satisfy minCount 2, however many times the node is bound: {r}"
+ );
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/a");
+}
+
+/// Two genuinely distinct values must still break `maxCount 1`, so the fix does
+/// not simply silence the constraint.
+#[test]
+fn max_count_still_fires_on_two_real_values() {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ ex:Equity rdfs:subClassOf ex:Instrument .
+ ex:Bond rdfs:subClassOf ex:Instrument .
+ ex:a a ex:Equity, ex:Bond ; ex:isin "GB0000000001", "GB0000000002" .
+ "#,
+ None,
+ )
+ .unwrap();
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Instrument ;
+ sh:property [ sh:path ex:isin ; sh:maxCount 1 ] .
+ "#;
+ let r = report(&store, shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+}
diff --git a/tests/shacl_nested_shape_test.rs b/tests/shacl_nested_shape_test.rs
new file mode 100644
index 00000000..dc489c26
--- /dev/null
+++ b/tests/shacl_nested_shape_test.rs
@@ -0,0 +1,313 @@
+//! `sh:node`: every value node must conform to another node shape.
+//!
+//! This is the first constraint here that is genuinely recursive. A referenced
+//! shape carries its own property shapes, which may themselves carry `sh:node`,
+//! and the HealthDCAT-AP shapes the health-dataset-catalogue vertical validates
+//! against do exactly that, nine times.
+//!
+//! The nested shape is compiled into a SPARQL boolean expression over the value
+//! node. Any constraint form inside it that cannot be compiled makes the whole
+//! expression unavailable, and the `sh:node` is then recorded as unevaluated:
+//! a nested shape that is half-checked would report conformance on rules that
+//! never ran, which is the failure mode this validator must not have.
+//!
+//! Bounds are taken from what those shapes actually use: `sh:minCount` and
+//! `sh:maxCount` of 0 or 1, `sh:nodeKind` of IRI, Literal or BlankNodeOrIRI,
+//! plus `sh:class`, `sh:datatype` and `sh:hasValue`. A count other than 0 or 1
+//! is not compiled, and says so.
+//!
+//! Every expectation is pyshacl's answer for the same input.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+fn store_with(ttl: &str) -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(ttl, None).unwrap();
+ store
+}
+
+/// ex:good has a distribution carrying an access URL; ex:bad has one without.
+const DATA: &str = r#"
+ @prefix ex: <http://example.org/> .
+ ex:d1 a ex:Distribution ; ex:accessURL <http://x.example/1> .
+ ex:d2 a ex:Distribution .
+ ex:good a ex:Dataset ; ex:distribution ex:d1 .
+ ex:bad a ex:Dataset ; ex:distribution ex:d2 .
+"#;
+
+const NODE_SHAPE: &str = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:DistributionShape a sh:NodeShape ;
+ sh:property [ sh:path ex:accessURL ; sh:minCount 1 ; sh:nodeKind sh:IRI ] .
+ ex:DatasetShape a sh:NodeShape ;
+ sh:targetClass ex:Dataset ;
+ sh:property [
+ sh:path ex:distribution ;
+ sh:node ex:DistributionShape ;
+ sh:message "distribution must carry an access URL" ;
+ ] .
+"#;
+
+#[test]
+fn sh_node_reports_the_value_that_breaks_the_referenced_shape() {
+ let r = report(&store_with(DATA), NODE_SHAPE);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/bad");
+ assert_eq!(r["violations"][0]["constraint"], "node");
+ assert_eq!(
+ r["violations"][0]["message"],
+ "distribution must carry an access URL"
+ );
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(skipped.is_empty(), "nothing should be skipped: {r}");
+}
+
+#[test]
+fn data_conforming_to_the_referenced_shape_passes() {
+ let data = r#"
+ @prefix ex: <http://example.org/> .
+ ex:d1 a ex:Distribution ; ex:accessURL <http://x.example/1> .
+ ex:good a ex:Dataset ; ex:distribution ex:d1 .
+ "#;
+ let r = report(&store_with(data), NODE_SHAPE);
+ assert_eq!(r["conforms"], serde_json::json!(true), "{r}");
+}
+
+/// A referenced shape that itself references another. HealthDCAT-AP nests this
+/// way, so one level of compilation is not enough.
+#[test]
+fn a_referenced_shape_may_itself_reference_a_shape() {
+ let data = r#"
+ @prefix ex: <http://example.org/> .
+ ex:a1 a ex:Agent ; ex:name "ONS" .
+ ex:a2 a ex:Agent .
+ ex:d1 a ex:Distribution ; ex:publisher ex:a1 .
+ ex:d2 a ex:Distribution ; ex:publisher ex:a2 .
+ ex:good a ex:Dataset ; ex:distribution ex:d1 .
+ ex:bad a ex:Dataset ; ex:distribution ex:d2 .
+ "#;
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:AgentShape a sh:NodeShape ;
+ sh:property [ sh:path ex:name ; sh:minCount 1 ] .
+ ex:DistributionShape a sh:NodeShape ;
+ sh:property [ sh:path ex:publisher ; sh:node ex:AgentShape ] .
+ ex:DatasetShape a sh:NodeShape ;
+ sh:targetClass ex:Dataset ;
+ sh:property [ sh:path ex:distribution ; sh:node ex:DistributionShape ] .
+ "#;
+ let r = report(&store_with(data), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/bad");
+}
+
+/// `sh:maxCount 0` and `sh:maxCount 1` inside a referenced shape, both used by
+/// the HealthDCAT-AP shapes.
+#[test]
+fn max_counts_inside_a_referenced_shape_are_compiled() {
+ let data = r#"
+ @prefix ex: <http://example.org/> .
+ ex:d1 a ex:Distribution ; ex:title "one" .
+ ex:d2 a ex:Distribution ; ex:title "one", "two" .
+ ex:ok a ex:Dataset ; ex:distribution ex:d1 .
+ ex:two a ex:Dataset ; ex:distribution ex:d2 .
+ "#;
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:DistributionShape a sh:NodeShape ;
+ sh:property [ sh:path ex:title ; sh:maxCount 1 ] .
+ ex:DatasetShape a sh:NodeShape ;
+ sh:targetClass ex:Dataset ;
+ sh:property [ sh:path ex:distribution ; sh:node ex:DistributionShape ] .
+ "#;
+ let r = report(&store_with(data), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/two");
+}
+
+/// A form inside the referenced shape that cannot be compiled must take the
+/// whole `sh:node` to `skipped_constraints`, not silently pass the rest.
+#[test]
+fn an_uncompilable_referenced_shape_is_recorded_as_skipped() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:DistributionShape a sh:NodeShape ;
+ sh:property [ sh:path ex:accessURL ; sh:minCount 3 ] .
+ ex:DatasetShape a sh:NodeShape ;
+ sh:targetClass ex:Dataset ;
+ sh:property [ sh:path ex:distribution ; sh:node ex:DistributionShape ] .
+ "#;
+ let r = report(&store_with(DATA), shapes);
+ assert!(r["conforms"].is_null(), "must not claim a verdict: {r}");
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(
+ skipped.iter().any(|s| s["constraint"] == "sh:node"),
+ "the sh:node must be named as unevaluated: {r}"
+ );
+}
+
+/// A shape that references itself must not spin. It is bounded and reported.
+#[test]
+fn a_self_referencing_shape_terminates_and_is_reported() {
+ let data = r#"
+ @prefix ex: <http://example.org/> .
+ ex:a a ex:Dataset ; ex:related ex:a .
+ "#;
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:DatasetShape a sh:NodeShape ;
+ sh:targetClass ex:Dataset ;
+ sh:property [ sh:path ex:related ; sh:node ex:DatasetShape ] .
+ "#;
+ let r = report(&store_with(data), shapes);
+ // Either a verdict or an honest null, but it must return.
+ assert!(r["violation_count"].is_number(), "{r}");
+}
+
+/// A `sh:node` pointing at a shape the shapes graph never defines.
+///
+/// The compiler builds a conjunction of the referenced shape's constraints. An
+/// undefined shape has none, and an empty conjunction is `true`, so without an
+/// explicit check every value node would conform to a shape nobody wrote. That
+/// is a false clean produced by absence.
+///
+/// The HealthDCAT-AP shapes reference three DCAT-AP 3.0.0 shapes that live in
+/// another file, so this is the ordinary case, not a contrived one.
+#[test]
+fn a_reference_to_an_undefined_shape_is_not_treated_as_satisfied() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:DatasetShape a sh:NodeShape ;
+ sh:targetClass ex:Dataset ;
+ sh:property [ sh:path ex:distribution ; sh:node ex:ShapeInAnotherFile ] .
+ "#;
+ let r = report(&store_with(DATA), shapes);
+ assert!(
+ r["conforms"].is_null(),
+ "an undefined shape cannot be satisfied or broken; it must suppress the verdict: {r}"
+ );
+ assert_eq!(r["violation_count"], serde_json::json!(0), "{r}");
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(
+ skipped.iter().any(|s| s["constraint"] == "sh:node"),
+ "the unresolvable reference must be named: {r}"
+ );
+}
+
+/// `sh:or` asserted on the node shape, over member shapes rather than leaf
+/// constraints: the focus node must conform to at least one member.
+///
+/// Taken from the Italian register vertical, which uses it to keep a layer
+/// core-only: either the assertion is conformant, or it records why not. The
+/// members are written inline, so they are blank nodes and cannot be addressed
+/// by term; their contents are read through the parent instead.
+#[test]
+fn node_level_or_over_member_shapes_is_evaluated() {
+ let data = r#"
+ @prefix it: <http://example.org/it#> .
+ it:ok a it:Assertion ; it:conformant true .
+ it:also a it:Assertion ; it:conformant false ; it:reason "truncated" .
+ it:bad a it:Assertion ; it:conformant false .
+ "#;
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix it: <http://example.org/it#> .
+ it:S a sh:NodeShape ;
+ sh:targetClass it:Assertion ;
+ sh:message "non-conformant without a recorded reason" ;
+ sh:or (
+ [ sh:property [ sh:path it:conformant ; sh:hasValue true ] ]
+ [ sh:property [ sh:path it:reason ; sh:minCount 1 ] ]
+ ) .
+ "#;
+ let r = report(&store_with(data), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/it#bad");
+ assert_eq!(
+ r["violations"][0]["message"],
+ "non-conformant without a recorded reason"
+ );
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(skipped.is_empty(), "{r}");
+}
+
+/// A member shape using a form the one-level reader cannot compile must take the
+/// whole disjunction to skipped, not pass on the members it did understand.
+#[test]
+fn an_uncompilable_or_member_suppresses_the_verdict() {
+ let data = r#"
+ @prefix it: <http://example.org/it#> .
+ it:bad a it:Assertion .
+ "#;
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix it: <http://example.org/it#> .
+ it:S a sh:NodeShape ;
+ sh:targetClass it:Assertion ;
+ sh:or (
+ [ sh:property [ sh:path it:reason ; sh:minCount 1 ] ]
+ [ sh:property [ sh:path it:other ; sh:minCount 4 ] ]
+ ) .
+ "#;
+ let r = report(&store_with(data), shapes);
+ assert!(r["conforms"].is_null(), "must not claim a verdict: {r}");
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(skipped.iter().any(|s| s["constraint"] == "sh:or"), "{r}");
+}
+
+/// A deliberate, documented divergence from pyshacl on reporting granularity.
+///
+/// SHACL says a failing `sh:node` produces a result at the shape that carries it,
+/// naming the value node that did not conform. pyshacl additionally surfaces the
+/// referenced shape's own results as separate entries, so a two-level nesting
+/// gives it three results where this validator gives one.
+///
+/// Both agree the data does not conform, and agree on the outer focus node. The
+/// difference is how much of the chain is itemised. It is pinned here so that a
+/// differential run reporting "missed" results against pyshacl on `sh:node` is
+/// read as this, and not as a missed violation.
+#[test]
+fn sh_node_reports_at_the_outer_shape_only() {
+ let data = r#"
+ @prefix ex: <http://example.org/> .
+ ex:a2 a ex:Agent .
+ ex:d2 a ex:Distribution ; ex:publisher ex:a2 .
+ ex:bad a ex:Dataset ; ex:distribution ex:d2 .
+ "#;
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:AgentShape a sh:NodeShape ;
+ sh:property [ sh:path ex:name ; sh:minCount 1 ] .
+ ex:DistributionShape a sh:NodeShape ;
+ sh:property [ sh:path ex:publisher ; sh:node ex:AgentShape ] .
+ ex:DatasetShape a sh:NodeShape ;
+ sh:targetClass ex:Dataset ;
+ sh:property [ sh:path ex:distribution ; sh:node ex:DistributionShape ] .
+ "#;
+ let r = report(&store_with(data), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ // pyshacl reports three here: ex:bad, ex:d2 and ex:a2.
+ assert_eq!(
+ r["violation_count"],
+ serde_json::json!(1),
+ "one result at the outer shape: {r}"
+ );
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/bad");
+}
diff --git a/tests/shacl_not_test.rs b/tests/shacl_not_test.rs
new file mode 100644
index 00000000..663b296b
--- /dev/null
+++ b/tests/shacl_not_test.rs
@@ -0,0 +1,143 @@
+//! `sh:not`, the constraint that zeroed 198 real violations.
+//!
+//! In the Scottish land register build a layer-2 shapes graph expressed its
+//! rule as `sh:not [ sh:hasValue ... ]`. The validator collected every other
+//! constraint on that property shape, never collected this one, and returned a
+//! clean report over data that broke the rule. The skip complement later made
+//! that visible — `conforms` became null with `sh:not` named in
+//! `skipped_constraints` — which is honest, but a shapes graph written to the
+//! specification still gets no verdict.
+//!
+//! These pin `sh:not` over the nested constraint forms the validator already
+//! evaluates in their positive sense, and pin that a nested form it cannot
+//! evaluate still reaches `skipped_constraints` rather than passing quietly.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+fn store() -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ ex:a a ex:Thing ; ex:mech ex:bad ; ex:code "ABC" ; ex:n "7"^^xsd:integer .
+ ex:b a ex:Thing ; ex:mech ex:good ; ex:code "123" ; ex:n "x" .
+ "#,
+ None,
+ )
+ .unwrap();
+ store
+}
+
+#[test]
+fn not_has_value_reports_the_node_that_carries_the_forbidden_value() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:mech ; sh:not [ sh:hasValue ex:bad ] ;
+ sh:message "must not be bad" ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(
+ r["conforms"],
+ serde_json::json!(false),
+ "pyshacl reports conforms=False, violations=1 for this case"
+ );
+ assert_eq!(r["violation_count"], serde_json::json!(1));
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/a");
+ assert_eq!(r["violations"][0]["constraint"], "not");
+ assert_eq!(r["violations"][0]["message"], "must not be bad");
+}
+
+/// The positive form of the same shape is already evaluated correctly. Pinning
+/// both directions is what isolates a fault to `sh:not` rather than to the
+/// nested constraint.
+#[test]
+fn the_positive_form_of_the_same_constraint_is_unchanged() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:mech ; sh:hasValue ex:bad ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false));
+ assert_eq!(r["violation_count"], serde_json::json!(1));
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/b");
+}
+
+#[test]
+fn not_datatype_reports_the_value_of_the_forbidden_type() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:n ; sh:not [ sh:datatype xsd:integer ] ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false));
+ assert_eq!(r["violation_count"], serde_json::json!(1));
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/a");
+}
+
+#[test]
+fn not_pattern_reports_the_value_that_matches() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:code ; sh:not [ sh:pattern "^[0-9]+$" ] ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false));
+ assert_eq!(r["violation_count"], serde_json::json!(1));
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/b");
+}
+
+/// Data that satisfies the negation must come back clean, not merely
+/// violation-free with a suppressed verdict.
+#[test]
+fn a_satisfied_negation_conforms() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:mech ; sh:not [ sh:hasValue ex:absent ] ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(true));
+ assert_eq!(r["violation_count"], serde_json::json!(0));
+}
+
+/// `sh:not` is no longer wholesale unimplemented, but a nested form the
+/// validator cannot evaluate must still suppress the verdict. Implementing the
+/// common cases must not convert an unevaluated rule into a silent pass.
+#[test]
+fn a_nested_form_that_cannot_be_evaluated_still_reaches_skipped() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:mech ; sh:not [ sh:closed true ] ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert!(
+ r["conforms"].is_null(),
+ "an unevaluated negation must not report a verdict, got {}",
+ r["conforms"]
+ );
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(
+ !skipped.is_empty(),
+ "the unevaluated nested form must be named in skipped_constraints"
+ );
+}
diff --git a/tests/shacl_qualified_test.rs b/tests/shacl_qualified_test.rs
new file mode 100644
index 00000000..b803e815
--- /dev/null
+++ b/tests/shacl_qualified_test.rs
@@ -0,0 +1,167 @@
+//! `sh:qualifiedValueShape` with `sh:qualifiedMinCount` / `sh:qualifiedMaxCount`.
+//!
+//! Modelled on the investment-fund vertical, which is where the corpus run found
+//! these unevaluated. Its `ifo:FundShape` carries two qualified constraints on the
+//! SAME path: `ifo:identifiedBy` must hold exactly one SEC series identifier, and
+//! should hold at least one LEI. That shape is why these are collected as
+//! independent entries instead of keyed by path the way `sh:or` and `sh:in` are —
+//! keying by path merges two different rules into one and silently drops a bound.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+/// ex:ok has one series id and one LEI. ex:noLei has a series id but no LEI.
+/// ex:twoSeries has two series ids, breaking the maximum.
+fn store() -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ ex:s1 a ex:SeriesId . ex:s2 a ex:SeriesId . ex:s3 a ex:SeriesId .
+ ex:l1 a ex:Lei .
+ ex:ok a ex:Fund ; ex:identifiedBy ex:s1, ex:l1 .
+ ex:noLei a ex:Fund ; ex:identifiedBy ex:s2 .
+ ex:twoSeries a ex:Fund ; ex:identifiedBy ex:s3, ex:s1, ex:l1 .
+ "#,
+ None,
+ )
+ .unwrap();
+ store
+}
+
+#[test]
+fn qualified_min_count_reports_the_node_below_the_bound() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Fund ;
+ sh:property [
+ sh:path ex:identifiedBy ;
+ sh:qualifiedValueShape [ sh:class ex:Lei ] ;
+ sh:qualifiedMinCount 1 ;
+ sh:message "no LEI" ;
+ ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/noLei");
+ assert_eq!(r["violations"][0]["constraint"], "qualifiedMinCount");
+ assert_eq!(r["violations"][0]["message"], "no LEI");
+}
+
+#[test]
+fn qualified_max_count_reports_the_node_above_the_bound() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Fund ;
+ sh:property [
+ sh:path ex:identifiedBy ;
+ sh:qualifiedValueShape [ sh:class ex:SeriesId ] ;
+ sh:qualifiedMaxCount 1 ;
+ ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(
+ r["violations"][0]["focus_node"],
+ "http://example.org/twoSeries"
+ );
+ assert_eq!(r["violations"][0]["constraint"], "qualifiedMaxCount");
+}
+
+/// The shape that motivated the design: two qualified constraints, same path,
+/// different nested shapes and different bounds. Both must be evaluated, and
+/// neither may absorb the other.
+#[test]
+fn two_qualified_constraints_on_one_path_are_both_evaluated() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Fund ;
+ sh:property [
+ sh:path ex:identifiedBy ;
+ sh:qualifiedValueShape [ sh:class ex:SeriesId ] ;
+ sh:qualifiedMinCount 1 ; sh:qualifiedMaxCount 1 ;
+ sh:message "exactly one series id" ;
+ ] ;
+ sh:property [
+ sh:path ex:identifiedBy ;
+ sh:qualifiedValueShape [ sh:class ex:Lei ] ;
+ sh:qualifiedMinCount 1 ;
+ sh:message "at least one LEI" ;
+ ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ let msgs: Vec<String> = r["violations"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v["message"].as_str().unwrap_or_default().to_string())
+ .collect();
+ assert!(
+ msgs.contains(&"at least one LEI".to_string()),
+ "the LEI rule must fire for ex:noLei: {r}"
+ );
+ assert!(
+ msgs.contains(&"exactly one series id".to_string()),
+ "the series-id rule must fire for ex:twoSeries: {r}"
+ );
+ assert_eq!(r["violation_count"], serde_json::json!(2), "{r}");
+}
+
+#[test]
+fn data_satisfying_both_bounds_conforms() {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ ex:s1 a ex:SeriesId . ex:l1 a ex:Lei .
+ ex:ok a ex:Fund ; ex:identifiedBy ex:s1, ex:l1 .
+ "#,
+ None,
+ )
+ .unwrap();
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Fund ;
+ sh:property [
+ sh:path ex:identifiedBy ;
+ sh:qualifiedValueShape [ sh:class ex:SeriesId ] ;
+ sh:qualifiedMinCount 1 ; sh:qualifiedMaxCount 1 ;
+ ] .
+ "#;
+ let r = report(&store, shapes);
+ assert_eq!(r["conforms"], serde_json::json!(true), "{r}");
+}
+
+/// A nested shape form that cannot be turned into a filter must suppress the
+/// verdict rather than count zero matches and report a spurious minimum breach.
+#[test]
+fn an_unsupported_nested_shape_is_recorded_as_skipped() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Fund ;
+ sh:property [
+ sh:path ex:identifiedBy ;
+ sh:qualifiedValueShape [ sh:closed true ] ;
+ sh:qualifiedMinCount 1 ;
+ ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert!(r["conforms"].is_null(), "must not claim a verdict: {r}");
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(!skipped.is_empty(), "{r}");
+}
diff --git a/tests/shacl_same_path_shapes_test.rs b/tests/shacl_same_path_shapes_test.rs
new file mode 100644
index 00000000..fcfe0383
--- /dev/null
+++ b/tests/shacl_same_path_shapes_test.rs
@@ -0,0 +1,138 @@
+//! Two property shapes on one path, each carrying its own list-valued constraint.
+//!
+//! `sh:or`, `sh:in` and `sh:not` all nest a list or a shape under a property shape
+//! that is almost always a blank node, and a blank-node label written into a SPARQL
+//! query is a fresh variable rather than a reference. The original workaround was to
+//! collect these per shape and key them by `sh:path`, which avoids naming the blank
+//! node at all.
+//!
+//! It also merges every property shape that shares a path. Two `sh:not` blocks on
+//! one path became one conjunction, `?val = bad1 && ?val = bad2`, which no value can
+//! satisfy, so both rules reported nothing and the run came back clean. That is a
+//! false clean, the one failure mode this validator must not have, and it is
+//! reachable from three constraints at once.
+//!
+//! Keying by the property shape's own printed term fixes it, the same way the
+//! node-shape complement already matches a shape by its printed term rather than
+//! splicing it into query text.
+//!
+//! Every expectation here is pyshacl's answer for the same input.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+fn store_with(ttl: &str) -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(ttl, None).unwrap();
+ store
+}
+
+const TWO_BADS: &str = r#"
+ @prefix ex: <http://example.org/> .
+ ex:a a ex:Thing ; ex:p ex:bad1 .
+ ex:b a ex:Thing ; ex:p ex:bad2 .
+"#;
+
+#[test]
+fn two_not_constraints_on_one_path_are_both_evaluated() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:p ; sh:not [ sh:hasValue ex:bad1 ] ] ;
+ sh:property [ sh:path ex:p ; sh:not [ sh:hasValue ex:bad2 ] ] .
+ "#;
+ let r = report(&store_with(TWO_BADS), shapes);
+ assert_eq!(
+ r["conforms"],
+ serde_json::json!(false),
+ "pyshacl reports two violations here; a clean run is the bug: {r}"
+ );
+ assert_eq!(r["violation_count"], serde_json::json!(2), "{r}");
+ let nodes: Vec<String> = r["violations"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v["focus_node"].as_str().unwrap_or_default().to_string())
+ .collect();
+ assert!(nodes.contains(&"http://example.org/a".to_string()), "{r}");
+ assert!(nodes.contains(&"http://example.org/b".to_string()), "{r}");
+}
+
+#[test]
+fn two_or_constraints_on_one_path_are_both_evaluated() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:p ; sh:or ( [ sh:datatype xsd:string ] ) ] ;
+ sh:property [ sh:path ex:p ; sh:or ( [ sh:datatype xsd:integer ] ) ] .
+ "#;
+ // The value is a string, so the second shape fails. Merged into one
+ // disjunction it would pass on the first alternative and report nothing.
+ let r = report(
+ &store_with(r#"@prefix ex: <http://example.org/> . ex:a a ex:Thing ; ex:p "x" ."#),
+ shapes,
+ );
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+}
+
+#[test]
+fn two_in_constraints_on_one_path_are_both_evaluated() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:p ; sh:in ( "x" ) ] ;
+ sh:property [ sh:path ex:p ; sh:in ( "y" ) ] .
+ "#;
+ let r = report(
+ &store_with(r#"@prefix ex: <http://example.org/> . ex:a a ex:Thing ; ex:p "x" ."#),
+ shapes,
+ );
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+}
+
+/// The ordinary single-shape case must be untouched by the change of key.
+#[test]
+fn one_property_shape_per_path_still_behaves() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:p ; sh:not [ sh:hasValue ex:bad1 ] ] .
+ "#;
+ let r = report(&store_with(TWO_BADS), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/a");
+}
+
+/// An unsupported nested form in one of two blocks must suppress the verdict
+/// without silencing the block beside it.
+#[test]
+fn an_unsupported_block_does_not_silence_its_neighbour() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:p ; sh:not [ sh:hasValue ex:bad1 ] ] ;
+ sh:property [ sh:path ex:p ; sh:not [ sh:closed true ] ] .
+ "#;
+ let r = report(&store_with(TWO_BADS), shapes);
+ assert!(r["conforms"].is_null(), "one block is unevaluated: {r}");
+ assert_eq!(
+ r["violation_count"],
+ serde_json::json!(1),
+ "the evaluable block must still report ex:a: {r}"
+ );
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/a");
+}
diff --git a/tests/shacl_sparql_prologue_test.rs b/tests/shacl_sparql_prologue_test.rs
new file mode 100644
index 00000000..b8d4ca15
--- /dev/null
+++ b/tests/shacl_sparql_prologue_test.rs
@@ -0,0 +1,144 @@
+//! A `sh:sparql` constraint whose SELECT declares its own prefixes.
+//!
+//! SHACL pre-binds `$this`, and this validator binds it by wrapping the author's
+//! SELECT as a subquery under a VALUES clause. SPARQL allows PREFIX and BASE only
+//! in the prologue, at the very start of a query, so an author's prologue carried
+//! into that subquery position makes the whole query unparseable. The constraint
+//! was then reported as skipped: honest, but it never ran.
+//!
+//! This is not a corner case. Declaring prefixes inside `sh:select` is the
+//! portable way to write a SPARQL constraint, it is what pyshacl accepts, and
+//! `sh:sparql` is the third most-used constraint across this machine's shapes
+//! files (223 occurrences in 88 files). Every one of the seven in
+//! `bank-register-ontology/shapes/bro-shapes.ttl` failed this way, found by the
+//! differential run against pyshacl rather than by the unit tests.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+fn store() -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ ex:a a ex:Assertion ; ex:conformant false .
+ ex:b a ex:Assertion ; ex:conformant false ; ex:reason "truncated" .
+ "#,
+ None,
+ )
+ .unwrap();
+ store
+}
+
+/// The shape from the banking vertical, reduced: a non-conformant assertion must
+/// record why. `ex:a` does not, `ex:b` does.
+const WITH_PROLOGUE: &str = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ;
+ sh:targetClass ex:Assertion ;
+ sh:sparql [
+ sh:message "non-conformant with no reason" ;
+ sh:severity sh:Violation ;
+ sh:select """
+ PREFIX ex: <http://example.org/>
+ SELECT $this WHERE {
+ $this ex:conformant false .
+ FILTER NOT EXISTS { $this ex:reason ?r }
+ }
+ """ ;
+ ] .
+"#;
+
+#[test]
+fn a_select_declaring_its_own_prefixes_is_executed() {
+ let r = report(&store(), WITH_PROLOGUE);
+ assert_eq!(
+ r["conforms"],
+ serde_json::json!(false),
+ "the constraint must run, not be skipped: {r}"
+ );
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/a");
+ assert_eq!(r["violations"][0]["message"], "non-conformant with no reason");
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(skipped.is_empty(), "nothing should be skipped: {r}");
+}
+
+/// BASE is prologue too, and may be followed by further PREFIX lines.
+#[test]
+fn a_select_with_base_and_comments_in_the_prologue_is_executed() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ;
+ sh:targetClass ex:Assertion ;
+ sh:sparql [
+ sh:message "non-conformant with no reason" ;
+ sh:select """
+ # the rule, as the register states it
+ BASE <http://example.org/>
+ PREFIX ex: <http://example.org/>
+ SELECT $this WHERE {
+ $this ex:conformant false .
+ FILTER NOT EXISTS { $this ex:reason ?r }
+ }
+ """ ;
+ ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+}
+
+/// A SELECT with no prologue of its own must keep working exactly as before.
+#[test]
+fn a_select_without_a_prologue_is_unaffected() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ;
+ sh:targetClass ex:Assertion ;
+ sh:sparql [
+ sh:message "non-conformant with no reason" ;
+ sh:select """
+ SELECT $this WHERE {
+ $this <http://example.org/conformant> false .
+ FILTER NOT EXISTS { $this <http://example.org/reason> ?r }
+ }
+ """ ;
+ ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+}
+
+/// A genuinely broken query must still be reported as skipped and must still
+/// suppress the verdict. Hoisting the prologue must not turn an unrunnable
+/// constraint into a silent pass.
+#[test]
+fn a_query_that_cannot_parse_is_still_reported_as_skipped() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ;
+ sh:targetClass ex:Assertion ;
+ sh:sparql [
+ sh:select """
+ PREFIX ex: <http://example.org/>
+ SELECT $this WHERE { this is not sparql (((
+ """ ;
+ ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert!(r["conforms"].is_null(), "must not claim a pass: {r}");
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(!skipped.is_empty(), "the failure must be named: {r}");
+}
diff --git a/tests/shacl_string_and_pair_test.rs b/tests/shacl_string_and_pair_test.rs
new file mode 100644
index 00000000..dcf18864
--- /dev/null
+++ b/tests/shacl_string_and_pair_test.rs
@@ -0,0 +1,139 @@
+//! `sh:minLength`, `sh:maxLength`, `sh:lessThan`, `sh:lessThanOrEquals`.
+//!
+//! Chosen by census rather than by taste: across 88 shapes files in 39 of this
+//! machine's vertical repositories, `sh:minLength` is the most-used constraint
+//! the validator did not evaluate (23 occurrences). Every shapes graph carrying
+//! one was getting `conforms: null` and no verdict at all.
+//!
+//! Every expectation here was checked against pyshacl on the same input.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+fn store() -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ ex:short a ex:Thing ; ex:code "AB" ; ex:low "3"^^xsd:integer ; ex:high "9"^^xsd:integer .
+ ex:exact a ex:Thing ; ex:code "ABC" ; ex:low "5"^^xsd:integer ; ex:high "5"^^xsd:integer .
+ ex:long a ex:Thing ; ex:code "ABCDE" ; ex:low "8"^^xsd:integer ; ex:high "2"^^xsd:integer .
+ "#,
+ None,
+ )
+ .unwrap();
+ store
+}
+
+#[test]
+fn min_length_reports_only_the_value_below_the_bound() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:code ; sh:minLength 3 ; sh:message "too short" ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/short");
+ assert_eq!(r["violations"][0]["constraint"], "minLength");
+ assert_eq!(r["violations"][0]["message"], "too short");
+}
+
+#[test]
+fn max_length_reports_only_the_value_above_the_bound() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:code ; sh:maxLength 3 ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/long");
+}
+
+/// The bound is inclusive at both ends, so the exact-length value passes both.
+#[test]
+fn a_value_exactly_on_both_bounds_conforms() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:code ; sh:minLength 2 ; sh:maxLength 5 ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["conforms"], serde_json::json!(true), "{r}");
+}
+
+#[test]
+fn less_than_compares_two_properties_of_the_same_focus_node() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:low ; sh:lessThan ex:high ; sh:message "low must be under high" ] .
+ "#;
+ let r = report(&store(), shapes);
+ // ex:short 3<9 passes; ex:exact 5<5 fails; ex:long 8<2 fails.
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(2), "{r}");
+ let nodes: Vec<_> = r["violations"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v["focus_node"].as_str().unwrap().to_string())
+ .collect();
+ assert!(nodes.contains(&"http://example.org/exact".to_string()), "{r}");
+ assert!(nodes.contains(&"http://example.org/long".to_string()), "{r}");
+}
+
+#[test]
+fn less_than_or_equals_admits_the_equal_case() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:low ; sh:lessThanOrEquals ex:high ] .
+ "#;
+ let r = report(&store(), shapes);
+ // Only ex:long (8 <= 2) fails now; ex:exact (5 <= 5) is admitted.
+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");
+ assert_eq!(r["violation_count"], serde_json::json!(1), "{r}");
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/long");
+}
+
+/// Implementing these must remove them from `skipped_constraints`. A stale skip
+/// suppresses the verdict of a run in which nothing was missed, and a null that
+/// fires on a complete run teaches the reader to ignore null.
+#[test]
+fn the_implemented_constraints_no_longer_suppress_the_verdict() {
+ for constraint in [
+ "sh:minLength 2",
+ "sh:maxLength 9",
+ "sh:lessThanOrEquals ex:high",
+ ] {
+ let shapes = format!(
+ r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
+ sh:property [ sh:path ex:low ; {constraint} ] .
+ "#
+ );
+ let r = report(&store(), &shapes);
+ assert!(
+ !r["conforms"].is_null(),
+ "{constraint} must yield a verdict: {r}"
+ );
+ }
+}
diff --git a/tests/shacl_target_forms_test.rs b/tests/shacl_target_forms_test.rs
new file mode 100644
index 00000000..43f46bd8
--- /dev/null
+++ b/tests/shacl_target_forms_test.rs
@@ -0,0 +1,145 @@
+//! The three explicit target forms: `sh:targetNode`, `sh:targetSubjectsOf`,
+//! `sh:targetObjectsOf`.
+//!
+//! Until now the validator selected focus nodes one way only, by class, and
+//! recorded the other three forms as skipped. Skipping was the honest answer
+//! while they were unimplemented — a shape whose only target is `sh:targetNode`
+//! selected nothing, and reporting `conforms: true` over nothing is the failure
+//! mode this validator must not have. But honest and absent is still absent:
+//! a shapes graph written against the specification gets no verdict at all.
+//!
+//! These pin the three forms against the answers pyshacl gives for the same
+//! data and shapes.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+fn report(store: &Arc<GraphStore>, shapes: &str) -> serde_json::Value {
+ serde_json::from_str(&ShaclValidator::validate(store, shapes).unwrap()).unwrap()
+}
+
+fn store() -> Arc<GraphStore> {
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ r#"
+ @prefix ex: <http://example.org/> .
+ ex:a a ex:Thing ; ex:mech ex:bad ; ex:p "present" .
+ ex:b a ex:Thing .
+ ex:c ex:knows ex:d .
+ "#,
+ None,
+ )
+ .unwrap();
+ store
+}
+
+const TARGET_NODE: &str = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetNode ex:b ;
+ sh:property [ sh:path ex:p ; sh:minCount 1 ; sh:message "needs p" ] .
+"#;
+
+const TARGET_NODE_SATISFIED: &str = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetNode ex:a ;
+ sh:property [ sh:path ex:p ; sh:minCount 1 ; sh:message "needs p" ] .
+"#;
+
+const TARGET_SUBJECTS_OF: &str = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetSubjectsOf ex:knows ;
+ sh:property [ sh:path ex:p ; sh:minCount 1 ; sh:message "needs p" ] .
+"#;
+
+const TARGET_OBJECTS_OF: &str = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetObjectsOf ex:knows ;
+ sh:property [ sh:path ex:p ; sh:minCount 1 ; sh:message "needs p" ] .
+"#;
+
+#[test]
+fn target_node_selects_the_named_node_and_reports_its_violation() {
+ let r = report(&store(), TARGET_NODE);
+ assert_eq!(r["focus_nodes"], serde_json::json!(1));
+ assert_eq!(
+ r["conforms"],
+ serde_json::json!(false),
+ "ex:b has no ex:p; pyshacl reports one violation here"
+ );
+ assert_eq!(r["violation_count"], serde_json::json!(1));
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/b");
+}
+
+#[test]
+fn target_node_that_satisfies_the_constraint_conforms() {
+ let r = report(&store(), TARGET_NODE_SATISFIED);
+ assert_eq!(r["focus_nodes"], serde_json::json!(1));
+ assert_eq!(r["conforms"], serde_json::json!(true));
+ assert_eq!(r["violation_count"], serde_json::json!(0));
+}
+
+#[test]
+fn target_subjects_of_selects_the_subject() {
+ let r = report(&store(), TARGET_SUBJECTS_OF);
+ assert_eq!(r["focus_nodes"], serde_json::json!(1));
+ assert_eq!(r["conforms"], serde_json::json!(false));
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/c");
+}
+
+#[test]
+fn target_objects_of_selects_the_object() {
+ let r = report(&store(), TARGET_OBJECTS_OF);
+ assert_eq!(r["focus_nodes"], serde_json::json!(1));
+ assert_eq!(r["conforms"], serde_json::json!(false));
+ assert_eq!(r["violations"][0]["focus_node"], "http://example.org/d");
+}
+
+/// An implemented target form must stop appearing in `skipped_constraints`.
+/// A stale skip is as misleading as a missing one: it suppresses the verdict
+/// on a run in which nothing was in fact missed.
+#[test]
+fn implemented_target_forms_are_no_longer_recorded_as_skipped() {
+ for shapes in [TARGET_NODE, TARGET_SUBJECTS_OF, TARGET_OBJECTS_OF] {
+ let r = report(&store(), shapes);
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ let stale: Vec<_> = skipped
+ .iter()
+ .filter(|s| {
+ let c = s["constraint"].as_str().unwrap_or_default();
+ c.contains("targetNode") || c.contains("targetSubjectsOf") || c.contains("targetObjectsOf")
+ })
+ .collect();
+ assert!(stale.is_empty(), "target form still recorded as skipped: {stale:?}");
+ }
+}
+
+/// `sh:targetNode` is an explicit target, not a query: it selects the named node
+/// whether or not that node appears in the data. A node absent from the data is
+/// therefore still a focus node, and a `sh:minCount 1` over it fails.
+///
+/// Checked against pyshacl, which reports `conforms=False` with one MinCount
+/// violation on `ex:nosuchnode` for exactly this input. Treating an absent node
+/// as an empty target instead would be a false clean of our own making.
+#[test]
+fn target_node_absent_from_the_data_is_still_a_focus_node() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetNode ex:nosuchnode ;
+ sh:property [ sh:path ex:p ; sh:minCount 1 ] .
+ "#;
+ let r = report(&store(), shapes);
+ assert_eq!(r["focus_nodes"], serde_json::json!(1));
+ assert_eq!(r["conforms"], serde_json::json!(false));
+ assert_eq!(r["violation_count"], serde_json::json!(1));
+ assert_eq!(
+ r["violations"][0]["focus_node"],
+ "http://example.org/nosuchnode"
+ );
+}
diff --git a/tests/shacl_test.rs b/tests/shacl_test.rs
index 1ab9dd92..4d012767 100644
--- a/tests/shacl_test.rs
+++ b/tests/shacl_test.rs
@@ -263,9 +263,17 @@ const NOT_DATA: &str = r#"
"#;
#[test]
-fn test_sh_not_is_not_silently_ignored() {
- // `sh:not` is not implemented. It must be reported as skipped, which
- // suppresses the verdict, rather than passing silently.
+fn test_sh_not_is_evaluated() {
+ // This test has been through all three states of the constraint it guards.
+ // First `sh:not` was silently ignored and this data came back clean, which
+ // is the false clean that cost 198 real violations in the Scottish land
+ // register build. Then it was recorded as skipped, and the test asserted a
+ // null verdict: honest, but the rule still never ran. It is evaluated now,
+ // so the assertion is the violation itself.
+ //
+ // The false-clean guard has not been dropped, only moved: an unevaluated
+ // negation is still pinned by
+ // `shacl_not_test::a_nested_form_that_cannot_be_evaluated_still_reaches_skipped`.
let store = store_with(NOT_DATA);
let shapes = r#"
@prefix sh: <http://www.w3.org/ns/shacl#> .
@@ -275,19 +283,26 @@ fn test_sh_not_is_not_silently_ignored() {
"#;
let report = ShaclValidator::validate(&store, shapes).unwrap();
let v: serde_json::Value = serde_json::from_str(&report).unwrap();
- assert!(v["conforms"].is_null(), "must not claim a pass: {v}");
- assert!(
- v["skipped_constraints"]
- .as_array()
- .is_some_and(|a| !a.is_empty()),
- "sh:not must be recorded as skipped: {v}"
+ assert_eq!(
+ v["conforms"],
+ serde_json::json!(false),
+ "ex:a carries the forbidden value; pyshacl agrees: {v}"
);
+ assert_eq!(v["violation_count"], serde_json::json!(1), "{v}");
+ assert_eq!(v["violations"][0]["focus_node"], "http://example.org/a");
+ assert_eq!(v["violations"][0]["constraint"], "not");
}
#[test]
-fn test_target_node_shape_does_not_report_a_pass() {
- // `sh:targetNode` selects no focus nodes here, so the shapes graph yields
- // nothing evaluable. Previously this reported conforms: true.
+fn test_target_node_shape_is_evaluated() {
+ // This test used to assert the opposite: `sh:targetNode` selected nothing,
+ // so the run had to come back null rather than claim a pass. That was the
+ // right answer while the form was unimplemented. It is implemented now, so
+ // the honest answer is a real verdict, and a null here would be the new
+ // defect. The invariant behind the old assertion is unchanged — never
+ // report a pass for something that was not evaluated — and it is still
+ // pinned, by `test_a_target_selecting_nothing_still_yields_no_verdict`
+ // below and by the vacuous-target suite.
let store = store_with("@prefix ex: <http://example.org/> . ex:b a ex:Thing .");
let shapes = r#"
@prefix sh: <http://www.w3.org/ns/shacl#> .
@@ -297,7 +312,37 @@ fn test_target_node_shape_does_not_report_a_pass() {
"#;
let report = ShaclValidator::validate(&store, shapes).unwrap();
let v: serde_json::Value = serde_json::from_str(&report).unwrap();
+ assert_eq!(v["focus_nodes"], serde_json::json!(1), "{v}");
+ assert_eq!(
+ v["conforms"],
+ serde_json::json!(false),
+ "ex:b has no ex:p, so the shape fails: {v}"
+ );
+ assert_eq!(v["violation_count"], serde_json::json!(1), "{v}");
+}
+
+#[test]
+fn test_a_target_selecting_nothing_still_yields_no_verdict() {
+ // The tri-state must stay reachable from a target now that all four target
+ // forms are evaluated. A form that is implemented can still select nothing,
+ // and a run that checked no nodes has not earned a pass.
+ let store = store_with("@prefix ex: <http://example.org/> . ex:b a ex:Thing .");
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:S a sh:NodeShape ; sh:targetSubjectsOf ex:predicateNotInTheData ;
+ sh:property [ sh:path ex:p ; sh:minCount 1 ] .
+ "#;
+ let report = ShaclValidator::validate(&store, shapes).unwrap();
+ let v: serde_json::Value = serde_json::from_str(&report).unwrap();
+ assert_eq!(v["focus_nodes"], serde_json::json!(0), "{v}");
assert!(v["conforms"].is_null(), "must not claim a pass: {v}");
+ assert!(
+ v["unmatched_shapes"]
+ .as_array()
+ .is_some_and(|a| !a.is_empty()),
+ "the empty target must be named: {v}"
+ );
}
#[test]
@@ -386,12 +431,22 @@ fn test_node_shape_constraints_reach_the_tri_state_verdict() {
}
#[test]
-fn test_tri_state_verdict_is_reachable_from_node_shape_property_shape_and_target() {
+fn test_tri_state_verdict_is_reachable_from_node_shape_and_property_shape() {
// A validator has three answers, not two, and every path that can select
// nothing or execute nothing has to reach the third one. This pins that
- // the null verdict is reachable from each of the three places a SHACL
+ // the null verdict is reachable from each place an unimplemented SHACL
// construct can sit, each with its own skipped entry naming the construct,
// so the next construct added has somewhere obvious to fail.
+ //
+ // There were three arms. The target arm is gone because all four core
+ // target forms are now evaluated, so no target form can produce a skipped
+ // entry any more; the target route to a null verdict is an empty target
+ // set, pinned by `test_a_target_selecting_nothing_still_yields_no_verdict`.
+ // The property arm names whichever constraint is currently unimplemented,
+ // so it has to be repointed each time one of them is implemented: off
+ // `sh:not`, then off `sh:minLength`, now on `sh:uniqueLang`. That churn is
+ // the test working, not the test being fragile — it fails the moment the
+ // constraint it names starts being evaluated.
let store = store_with(NOT_DATA);
let cases = [
(
@@ -409,19 +464,9 @@ fn test_tri_state_verdict_is_reachable_from_node_shape_property_shape_and_target
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix ex: <http://example.org/> .
ex:S a sh:NodeShape ; sh:targetClass ex:Thing ;
- sh:property [ sh:path ex:mech ; sh:not [ sh:hasValue ex:bad ] ] .
- "#,
- format!("{SH_NS}not"),
- ),
- (
- "target",
- r#"
- @prefix sh: <http://www.w3.org/ns/shacl#> .
- @prefix ex: <http://example.org/> .
- ex:S a sh:NodeShape ; sh:targetNode ex:a ;
- sh:property [ sh:path ex:mech ; sh:minCount 1 ] .
+ sh:property [ sh:path ex:mech ; sh:uniqueLang true ] .
"#,
- "sh:targetNode".to_string(),
+ format!("{SH_NS}uniqueLang"),
),
];
for (place, shapes, construct) in cases {
diff --git a/tools/shacl_differential.py b/tools/shacl_differential.py
new file mode 100644
index 00000000..a9abf7a2
--- /dev/null
+++ b/tools/shacl_differential.py
@@ -0,0 +1,195 @@
+#!/usr/bin/env python3
+"""Differential oracle: open-ontologies SHACL against pyshacl, over real shapes.
+
+A validator is trusted on evidence, not on its own test suite. This runs both
+engines over the same (data, shapes) pairs and compares three things in order of
+severity:
+
+ 1. FALSE CLEAN - we say conforms, pyshacl says not. The one failure mode the
+ validator must not have. Any of these is a stop-the-line bug.
+ 2. FALSE ALARM - we say not conforms, pyshacl says conforms. Noise that makes
+ a gate untrustworthy in the other direction.
+ 3. UNDETERMINED - we return null because something was skipped. Honest, but a
+ gap: the shapes graph got no verdict. These are the work list.
+
+Agreement on the verdict is not enough, so where both engines give a verdict the
+violation sets are compared as (focus_node, path) pairs.
+
+Usage:
+ python3 tools/shacl_differential.py CORPUS.json [--json out.json]
+
+CORPUS.json is a list of {"name", "data": [ttl...], "shapes": ttl} objects, or
+pass --discover ROOT to build one from a tree laid out as */shacl/*.ttl or
+*/shapes/*.ttl with data in */graph/*.ttl, */data/*.ttl or */examples/*.ttl.
+
+Nothing is capped silently: every pair excluded for size or timeout is listed in
+the report with the reason.
+"""
+import argparse
+import json
+import os
+import pathlib
+import subprocess
+import sys
+import tempfile
+
+BIN = os.environ.get(
+ "OPEN_ONTOLOGIES_BIN",
+ str(pathlib.Path(__file__).resolve().parent.parent / "target" / "release" / "open-ontologies"),
+)
+# A pair larger than this is reported as skipped rather than run. Both engines
+# parse the whole graph, and a multi-hundred-megabyte harvest turns a diff run
+# into an overnight job for no extra signal.
+MAX_BYTES = int(os.environ.get("SHACL_DIFF_MAX_BYTES", 40 * 1024 * 1024))
+TIMEOUT = int(os.environ.get("SHACL_DIFF_TIMEOUT", 300))
+
+
+def run_open_ontologies(data_files, shapes_file):
+ with tempfile.TemporaryDirectory() as d:
+ env = dict(os.environ, OPEN_ONTOLOGIES_STORAGE_MODE="persistent")
+ for f in data_files:
+ r = subprocess.run(
+ [BIN, "--data-dir", d, "load", str(f)],
+ capture_output=True, text=True, env=env, timeout=TIMEOUT,
+ )
+ if r.returncode != 0:
+ return {"error": f"load failed: {r.stderr.strip()[:300]}"}
+ r = subprocess.run(
+ [BIN, "--data-dir", d, "shacl", str(shapes_file)],
+ capture_output=True, text=True, env=env, timeout=TIMEOUT,
+ )
+ try:
+ return json.loads(r.stdout)
+ except json.JSONDecodeError:
+ return {"error": f"unparseable report: {(r.stdout + r.stderr).strip()[:300]}"}
+
+
+def run_pyshacl(data_files, shapes_file):
+ from pyshacl import validate
+ from rdflib import Graph
+
+ data = Graph()
+ for f in data_files:
+ data.parse(str(f))
+ shapes = Graph().parse(str(shapes_file))
+ conforms, results_graph, _ = validate(data, shacl_graph=shapes)
+ violations = set()
+ from rdflib.namespace import Namespace
+ SH = Namespace("http://www.w3.org/ns/shacl#")
+ # Every severity, not just sh:Violation. Collecting only Violations here
+ # compared pyshacl's violations against our results at ALL severities, and
+ # reported the difference as our defect: four sh:Warning results in the
+ # enterprise-knowledge vertical showed up as four extra violations we had
+ # invented. An oracle that manufactures findings is worse than no oracle.
+ for result in set(results_graph.subjects(SH.resultSeverity, None)):
+ focus = results_graph.value(result, SH.focusNode)
+ path = results_graph.value(result, SH.resultPath)
+ violations.add((str(focus), str(path) if path else None))
+ return {"conforms": conforms, "violations": violations}
+
+
+def ours_violation_set(report):
+ out = set()
+ for v in report.get("violations", []) or []:
+ out.add((str(v.get("focus_node")), v.get("path")))
+ return out
+
+
+def classify(ours, theirs):
+ """Return (verdict, detail). Order matters: false clean is checked first."""
+ if "error" in ours:
+ return "ERROR", ours["error"]
+ our_conforms = ours.get("conforms")
+ their_conforms = theirs["conforms"]
+
+ if our_conforms is None:
+ skipped = ours.get("skipped_constraints") or []
+ names = sorted({s.get("constraint", "?") for s in skipped})
+ if names:
+ return "UNDETERMINED", "skipped: " + ", ".join(names)
+ return "UNDETERMINED", ours.get("warning", "no verdict")
+
+ if our_conforms is True and their_conforms is False:
+ return "FALSE_CLEAN", f"pyshacl found {len(theirs['violations'])} violation(s), we found none"
+ if our_conforms is False and their_conforms is True:
+ return "FALSE_ALARM", f"we reported {len(ours_violation_set(ours))} violation(s), pyshacl found none"
+
+ ours_v, theirs_v = ours_violation_set(ours), theirs["violations"]
+ missed, extra = theirs_v - ours_v, ours_v - theirs_v
+ if missed or extra:
+ return "PARTIAL", f"{len(missed)} missed, {len(extra)} extra (verdict agrees)"
+ return "AGREE", f"{len(ours_v)} violation(s), identical sets"
+
+
+def discover(root):
+ cases, root = [], pathlib.Path(root)
+ for repo in sorted(p for p in root.iterdir() if p.is_dir()):
+ shapes = sorted(list((repo / "shacl").glob("*.ttl")) + list((repo / "shapes").glob("*.ttl")))
+ if not shapes:
+ continue
+ data = []
+ for sub in ("graph", "data", "examples", "ontology"):
+ data += sorted((repo / sub).glob("*.ttl"))
+ if not data:
+ continue
+ for s in shapes:
+ cases.append({"name": f"{repo.name}/{s.parent.name}/{s.name}",
+ "data": [str(p) for p in data], "shapes": str(s)})
+ return cases
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("corpus", nargs="?")
+ ap.add_argument("--discover")
+ ap.add_argument("--json")
+ ap.add_argument("--limit", type=int)
+ args = ap.parse_args()
+
+ cases = discover(args.discover) if args.discover else json.load(open(args.corpus))
+ if args.limit:
+ cases = cases[: args.limit]
+
+ rows, skipped_pairs = [], []
+ for case in cases:
+ data = [f for f in case["data"] if os.path.exists(f)]
+ size = sum(os.path.getsize(f) for f in data) + os.path.getsize(case["shapes"])
+ if size > MAX_BYTES:
+ reason = f"{size/1e6:.0f} MB over the {MAX_BYTES/1e6:.0f} MB cap"
+ skipped_pairs.append({"name": case["name"], "reason": reason})
+ print(f"{'NOT_RUN':<13} {case['name']}\n {reason}", flush=True)
+ continue
+ try:
+ ours = run_open_ontologies(data, case["shapes"])
+ theirs = run_pyshacl(data, case["shapes"])
+ verdict, detail = classify(ours, theirs)
+ except subprocess.TimeoutExpired:
+ reason = f"timed out after {TIMEOUT}s"
+ skipped_pairs.append({"name": case["name"], "reason": reason})
+ print(f"{'NOT_RUN':<13} {case['name']}\n {reason}", flush=True)
+ continue
+ except Exception as exc: # a parse failure in either engine is a result, not a crash
+ verdict, detail = "ERROR", f"{type(exc).__name__}: {exc}"[:300]
+ rows.append({"name": case["name"], "verdict": verdict, "detail": detail})
+ print(f"{verdict:<13} {case['name']}\n {detail}", flush=True)
+
+ counts = {}
+ for r in rows:
+ counts[r["verdict"]] = counts.get(r["verdict"], 0) + 1
+ print("\n" + "=" * 70)
+ print(f"{len(rows)} pair(s) run, {len(skipped_pairs)} not run")
+ for k in ("FALSE_CLEAN", "FALSE_ALARM", "PARTIAL", "UNDETERMINED", "AGREE", "ERROR"):
+ if k in counts:
+ print(f" {k:<13} {counts[k]}")
+ for s in skipped_pairs:
+ print(f" not run: {s['name']} - {s['reason']}")
+
+ if args.json:
+ json.dump({"rows": rows, "not_run": skipped_pairs, "counts": counts}, open(args.json, "w"), indent=1)
+
+ # A false clean is the one result that must fail a pipeline.
+ return 1 if counts.get("FALSE_CLEAN") else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())