Chapter 5 of 10
SHACL operational data contracts
Validation
About 4 minutes · includes examples, an exercise, and references
Chapter at a glance
- •SHACL validates operational graph contracts without replacing OWL semantics.
- •Targets, entailment mode, and validation scope determine what was actually checked.
- •Preserve the SHACL results graph and all version information.
SHACL validates an RDF data graph against a shapes graph. A shape selects focus nodes through targets and applies constraints to those nodes or to values reached through property paths. This gives graph pipelines a closed-world operational checkpoint without changing the open-world semantics of RDF and OWL. The distinction is essential: an ontology may allow incomplete knowledge, while an ingestion contract can still require an explicit identifier, source, and effective date before publication.
Node shapes describe requirements for focus nodes. Property shapes constrain values reached by a path. Common constraints include minimum and maximum counts, datatype, node kind, class, string pattern, numeric range, allowed values, language uniqueness, and nested shapes. A closed shape can reject properties not listed in its allowed set, with ignored properties such as rdf:type. Closedness is useful at strict API boundaries but brittle for extensible integration graphs. Apply it where a producer and consumer explicitly agree on a versioned payload.
Targets determine validation scope. targetClass selects instances of a class, subject and object targets select nodes participating in a predicate, and targetNode selects explicit resources. Inference can change which nodes are targeted, so the validation contract must declare its entailment assumptions. Validating only newly submitted nodes is fast but may miss constraints broken on connected existing nodes. A merge, deletion, or relation update may require a dependency-aware validation neighborhood or a full release validation.
Validation results are RDF data. Each result can identify the focus node, value, path, source shape, constraint component, severity, and message. Preserve the result graph with the input batch, shapes version, processor version, and entailment mode. Turning all failures into one boolean discards the evidence needed for remediation and quality analysis.
Severity supports policy. An informational finding might record a missing optional label; a warning may permit staging but block promotion later; a violation may reject publication. Severity alone should not be the decision rule. Map specific shape identifiers to actions, owners, and exception policies. A team should not change a shape from violation to warning simply to make a dashboard green without reviewing downstream risk.
SHACL property paths can express sequences, inverses, alternatives, and repeated paths. Core constraints cover many contracts. SHACL-SPARQL allows custom constraints expressed as SELECT queries, but portability, performance, recursion, and security require care. Prefer SHACL Core when possible. Treat a custom SPARQL constraint like production code: parameterize assumptions, bound work, test edge cases, and restrict SERVICE or expensive graph traversal.
Validation belongs at several points. Validate mapped records before identity resolution so malformed source data is visible. Validate proposed entity merges because they can violate cardinality or disjointness expectations. Validate the staged graph before release. Validate high-consequence write proposals before commit. Run periodic full checks to catch drift introduced by out-of-band changes or updated shapes.
Shape evolution needs compatibility discipline. Adding a required property is breaking for existing producers. Tightening a pattern can invalidate historical data. Version shapes, publish migration guidance, and test new shapes against representative snapshots before enforcement. A release can run old and new shapes in parallel to estimate impact. Keep stable shape IRIs when the meaning remains compatible; mint a new contract identity for materially different semantics.
SHACL does not prove truth. A conforming graph can contain a fabricated date with the correct datatype. It validates declared structure and constraints. Provenance, source trust, entity resolution, statistical checks, and domain review address other quality dimensions. Likewise, a violation does not always mean the source is wrong; it may reveal an outdated shape or a legitimate exception. Route exceptions through explicit review rather than silently suppressing them.
Metrics should connect validation to product risk: violation rate by shape and producer, time to remediation, recurrence after fix, blocked release count, exception age, and downstream incidents involving previously warned data. This turns shapes from a static schema artifact into an observable quality control system.
Key points
- SHACL validates operational graph contracts without replacing OWL semantics.
- Targets, entailment mode, and validation scope determine what was actually checked.
- Preserve the SHACL results graph and all version information.
- Shape changes require compatibility testing and migration policy.
A release-gating acquisition shape
Read the expected behavior in the surrounding walkthrough, then copy and run this reference implementation.
@prefix ex: <https://kg.example/ontology/> .
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ex:AcquisitionReleaseShape a sh:NodeShape ;
sh:targetClass ex:Acquisition ;
sh:property [
sh:path ex:acquirer ;
sh:minCount 1 ; sh:maxCount 1 ;
sh:class ex:Organization ;
] ;
sh:property [
sh:path ex:effectiveDate ;
sh:minCount 1 ; sh:maxCount 1 ;
sh:datatype xsd:date ;
] ;
sh:property [
sh:path ex:evidence ;
sh:minCount 1 ;
sh:nodeKind sh:IRI ;
] .Worked examples
Toy
Valid-looking but invalid data
A loan record has two checkout dates and an untyped borrower string.
A node shape reports max-count and node-kind violations. The report points to the loan focus node and properties so the producer can repair the mapping.
- Focus node
- Result path
- Constraint component and severity
System
Dual-run shape migration
A new compliance release requires every control assertion to cite approved evidence.
Run existing and proposed shapes against production snapshots. Slice violations by producer and age, migrate historical records, then move the new shape from warning to release-blocking violation through an approved rollout.
- Breaking producers
- Exception policy
- Rollback criteria
Exercise
Build a validation gate
Create a SHACL contract for one high-value event or relationship in your domain.
- Use class, cardinality, datatype, and evidence constraints.
- Define validation scope for insert, update, merge, and full release.
- Specify severity-to-action mappings.
- Create conforming and non-conforming fixtures.
Success criteria
- Fixtures cover boundary cases and unknown values.
- Results retain focus node and shape identity.
- The gate distinguishes structural validity from truth.
- A breaking shape change has a rollout plan.
Reflect: Which constraint belongs in SHACL, and which tempting rule belongs in application policy instead?
References and further reading
- Shapes Constraint Language (SHACL)The W3C Recommendation for validating RDF data graphs against reusable node and property shapes.
- SPARQL 1.1 Query LanguageThe W3C Recommendation for graph patterns, filters, aggregation, property paths, subqueries, and RDF datasets.
- OWL 2 Web Ontology Language PrimerThe W3C primer for OWL classes, properties, individuals, restrictions, inference, and ontology design.