How to Configure SHACL Validation for Ontology Governance in Semantica

Semantica provides a tunable, three-stage SHACL pipeline—shape generation, serialization, and validation—that enforces governance policies through configurable quality tiers and programmatic violation reporting.

The semantica-agi/semantica repository embeds a full‑stack SHACL validation pipeline designed to govern generated ontologies through strict, policy‑driven constraints. By configuring the SHACLGenerator and OntologyValidator components, teams can automate compliance checks directly within their ontology lifecycle. This article walks through exactly how to configure SHACL validation for ontology governance using the actual source implementation.

Generating SHACL Shapes with Quality Tiers

In semantica/ontology/ontology_generator.py, the SHACLGenerator class at line 756 instantiates with a quality tier that dictates the strictness of generated shapes. The tier is applied internally through _apply_quality_tier, which automatically sets closed=True on every node shape that declares at least one property when quality_tier == "strict" as implemented at line 1026. This single parameter enforces a closed‑world governance policy by rejecting any data that contains properties not explicitly defined in the shape.

Selecting a Governance Tier

The generator supports three governance levels according to the semantica source code. Basic performs lightweight checks suitable for early development. Standard adds normal production constraints, including in_values and pattern restrictions on property shapes as implemented around line 880. Strict activates the closed‑world assumption and retains all advanced constraints, making it the recommended setting for full ontology governance.

Serializing SHACL Graphs for Storage and Version Control

After generation, SHACLGenerator.serialize() outputs the shape graph to a string‑based format. The method accepts a format argument—turtle (default), json-ld, or n-triples—allowing teams to store shapes in version control or feed them directly into downstream validators as shown at line 868. Serializing to Turtle is the most common choice for policy files that must be diffed in git.

Running Validation and Reporting Violations

The validation stage relies on a thin wrapper around pyshacl that normalizes inputs and returns a structured report. This stage is where governance policies are actually enforced against RDF data graphs.

The _run_pyshacl Validation Helper

In semantica/ontology/ontology_validator.py, the _run_pyshacl helper at line 48 loads a data graph and the generated SHACL shapes, executes pyshacl.validate(), and returns a structured SHACLValidationReport. This low‑level function is the backbone of the validation stage and handles all format conversions internally when you specify data_graph_format.

Understanding SHACLValidationReport

The SHACLValidationReport class at line 60 exposes a conforms boolean and detailed lists of SHACLViolation, warnings, and infos as defined at line 25. Each SHACLViolation carries rich metadata including the focus node, constraint component, min/max counts, datatype, and class constraints that failed. The explain_violations() method at line 82 translates these structured records into human‑readable messages without requiring external LLM calls, making it ideal for automated CI logs.

End-to-End Workflow to Configure SHACL Validation

Below is a practical pattern that combines generation, serialization, and validation into a single governance check. This workflow uses the strict quality tier to enforce closed shapes and raises an exception when violations exceed a threshold.

from semantica.ontology.ontology_generator import SHACLGenerator
from semantica.ontology.ontology_validator import _run_pyshacl

# Build SHACL shapes with strict governance rules

shacl_gen = SHACLGenerator(quality_tier="strict")
shacl_graph = shacl_gen.generate(my_ontology_dict)

# Serialize to Turtle for version control or CI caching

shacl_ttl = shacl_gen.serialize(shacl_graph, format="turtle")

# Validate an RDF data graph against the policy

validation_report = _run_pyshacl(
    data_graph_ttl,
    shacl_ttl,
    data_graph_format="turtle"
)

# Inspect and enforce governance

if not validation_report.conforms:
    validation_report.explain_violations()
    raise ValueError(
        f"Ontology does not conform: {validation_report.violation_count} violations"
    )
else:
    print(validation_report.summary())

For higher‑level integration, instantiate OntologyValidator and call validate(), which runs symbolic reasoners plus optional SHACL checking. Passing validate=True to OntologyGenerator.generate() triggers this automatically according to the semantica-agi/semantica implementation.

from semantica.ontology.ontology_validator import OntologyValidator

validator = OntologyValidator()
result = validator.validate(my_ontology_dict)  # runs reasoners + optional SHACL

Advanced Configuration Tips for SHACL Governance

  • Quality Tier Selection – Choose basic for lightweight prototyping, standard for normal production pipelines, or strict for full governance that closes node shapes.
  • Property Inheritance Control – Set include_inherited=False when you do not want child classes to inherit parent property shapes. This simplifies the validation surface and reduces unexpected constraint propagation in large ontologies.
  • Payload and Timeout Limits – Production deployments exposed through the HTTP API should review the constants in semantica/explorer/routes/ontology.py, which cap the maximum SHACL graph size and request timeout. Adjust these constants before importing large ontologies to avoid server‑side rejections.

Summary

  • The SHACLGenerator class in semantica/ontology/ontology_generator.py creates shapes governed by a configurable quality tier (basic, standard, or strict) that controls closed‑world enforcement and property constraints.
  • Use SHACLGenerator.serialize() to emit shapes in Turtle, JSON‑LD, or N‑Triples for storage or pipeline caching.
  • The _run_pyshacl helper in semantica/ontology/ontology_validator.py executes validation and returns a SHACLValidationReport with detailed SHACLViolation metadata.
  • Call explain_violations() to produce human‑readable violation summaries without LLM dependencies, then reject or flag ontologies that do not conform.

Frequently Asked Questions

How do I switch from basic to strict SHACL validation in Semantica?

Instantiate SHACLGenerator with quality_tier="strict" as implemented in semantica/ontology/ontology_generator.py. The _apply_quality_tier method will then set closed=True on every node shape that has properties, enforcing a closed‑world governance model.

What serialization format should I use for SHACL shapes?

The SHACLGenerator.serialize() method supports turtle (default), json-ld, and n-triples. Turtle is the recommended format for version‑controlled governance policies because it diffs cleanly in source control.

How does Semantica report SHACL violations without external LLMs?

The SHACLValidationReport.explain_violations() method in semantica/ontology/ontology_validator.py transforms structured SHACLViolation objects into human‑readable text using only the embedded metadata. This design keeps validation fast and deterministic in CI environments.

Can SHACL validation be automated inside a CI pipeline?

Yes. Generate and serialize shapes once, then run _run_pyshacl or OntologyValidator.validate() as a gated step. Raise an exception or exit with a non‑zero status when validation_report.conforms is False to block non‑compliant ontology merges.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →