Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(ontology): target the namespace the data uses, and stop inventing constraints (#1104, #1105)
FABIOTESS981c9d920896
diff --git a/semantica/ontology/ontology_generator.py b/semantica/ontology/ontology_generator.pyindex 80851f63..564b94d7 100644--- a/semantica/ontology/ontology_generator.py+++ b/semantica/ontology/ontology_generator.py@@ -30,6 +30,7 @@ Author: Semantica ContributorsLicense: MIT"""+import refrom dataclasses import dataclass, field, replace as dataclass_replacefrom datetime import datetimefrom typing import Any, Dict, List, Optional@@ -751,6 +752,10 @@ class SHACLGraph:shapes_uri: strnode_shapes: List[NodeShape] = field(default_factory=list)prefixes: Dict[str, str] = field(default_factory=dict)+ # Bare class and property names mapped to the absolute IRI the data uses+ # for them. Shapes are indexed internally by name; this is what those names+ # expand to at serialisation time (#1104).+ term_iris: Dict[str, str] = field(default_factory=dict)class SHACLGenerator:@@ -783,8 +788,23 @@ class SHACLGenerator:include_inherited: bool = True,severity: str = "Violation",quality_tier: str = "standard",+ target_namespace: Optional[str] = None,+ attach_domainless_properties: bool = False,config: Optional[Dict[str, Any]] = None,):+ """+ Args:+ base_uri: Namespace the shape resources themselves live in.+ target_namespace: Namespace the terms being validated live in, used+ to expand sh:targetClass and sh:path when the ontology does not+ supply absolute IRIs. This is deliberately separate from+ base_uri: shapes that target their own namespace match nothing,+ and pySHACL reports that as conforming (#1104).+ attach_domainless_properties: When True, a property with no declared+ domain is attached to every node shape, which is the pre-0.6.6+ behaviour. It invents a constraint the ontology never stated, so+ it is off by default (#1105).+ """self.logger = get_logger("ontology_shacl")self.progress_tracker = get_progress_tracker()self.base_uri = base_uri.rstrip("/") + "/"@@ -792,6 +812,8 @@ class SHACLGenerator:self.include_inherited = include_inheritedself.severity = severityself.quality_tier = quality_tier+ self.target_namespace = target_namespace+ self.attach_domainless_properties = attach_domainless_propertiesself.config = config or {}# ── Public API ────────────────────────────────────────────────────────────@@ -829,10 +851,14 @@ class SHACLGenerator:"ex": base_uri,}+ target_ns = self._resolve_target_namespace(ontology, base_uri)+ prefixes["ex"] = target_ns+graph = SHACLGraph(base_uri=base_uri,shapes_uri=self.shapes_uri,prefixes=prefixes,+ term_iris=self._build_term_index(classes, properties, target_ns),)self.progress_tracker.update_tracking(tracking_id, message="Generating node shapes")@@ -901,6 +927,83 @@ class SHACLGenerator:# ── Internal pipeline stages ──────────────────────────────────────────────+ _DEFAULT_TARGET_NAMESPACE = "https://semantica.dev/ns#"++ @staticmethod+ def _is_absolute_iri(value: Any) -> bool:+ return isinstance(value, str) and bool(+ re.match(r"^[A-Za-z][A-Za-z0-9+.\-]*:", value.strip())+ )++ @staticmethod+ def _join_iri(base: str, local: str) -> str:+ separator = "" if base.endswith(("#", "/", ":")) else "#"+ return f"{base}{separator}{local}"++ def _resolve_target_namespace(self, ontology: Dict[str, Any], base_uri: str) -> str:+ """+ Decide which namespace sh:targetClass and sh:path are expanded in.++ base_uri says where the shapes live. It is only the right answer here+ when the ontology declared it, meaning shapes and terms deliberately+ share a namespace. Falling back to the shapes namespace produces shapes+ that target terms no data graph uses.+ """+ if self.target_namespace:+ return self.target_namespace++ namespace = ontology.get("namespace")+ if isinstance(namespace, dict) and namespace.get("base_uri"):+ return str(namespace["base_uri"])++ # An IRI already carried by a term is the most reliable evidence of+ # where the data lives, so prefer it over any configured default.+ for terms in (ontology.get("classes"), ontology.get("properties")):+ for term in terms or []:+ if not isinstance(term, dict):+ continue+ for key in ("uri", "iri", "id"):+ value = term.get(key)+ if self._is_absolute_iri(value):+ value = value.strip()+ cut = max(value.rfind("#"), value.rfind("/"))+ if cut != -1:+ return value[: cut + 1]++ if ontology.get("uri") and self._is_absolute_iri(ontology["uri"]):+ return str(ontology["uri"])++ if base_uri != self.base_uri:+ return base_uri++ return self._DEFAULT_TARGET_NAMESPACE++ def _build_term_index(+ self,+ classes: List[Dict[str, Any]],+ properties: List[Dict[str, Any]],+ target_ns: str,+ ) -> Dict[str, str]:+ """Map every class and property name to the absolute IRI it expands to."""+ index: Dict[str, str] = {}+ for term in list(classes or []) + list(properties or []):+ if not isinstance(term, dict):+ continue+ name = term.get("name")+ if not isinstance(name, str) or not name.strip():+ continue+ name = name.strip()++ iri = ""+ for key in ("uri", "iri", "id"):+ value = term.get(key)+ if isinstance(value, str) and value.strip():+ value = value.strip()+ iri = value if self._is_absolute_iri(value) else self._join_iri(target_ns, value)+ break+ index.setdefault(name, iri or self._join_iri(target_ns, name))+ return index+def _build_class_index(self, classes: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:@@ -949,13 +1052,22 @@ class SHACLGenerator:self.logger.debug(f"Property '{pname}' domain '{d}' has no matching node shape — skipped")- else:- # No domain declared → attach to all shapes+ elif self.attach_domainless_properties:self.logger.debug(- f"Property '{pname}' has no domain — attaching to all node shapes"+ f"Property '{pname}' has no domain, attaching to all node shapes "+ "because attach_domainless_properties is set")for node_shape in graph.node_shapes:node_shape.property_shapes.append(self._build_property_shape(prop))+ else:+ # Attaching here would state a constraint the ontology does not.+ # With minCount 1 that invalidates every instance of every+ # class, so the property is left unattached (#1105).+ self.logger.warning(+ f"Property '{pname}' declares no domain, so it is not attached "+ "to any node shape. Declare a domain, or pass "+ "attach_domainless_properties=True to restore the old behaviour."+ )def _build_property_shape(self, prop: Dict[str, Any]) -> PropertyShape:ptype = prop.get("type", "")@@ -1036,9 +1148,18 @@ class SHACLGenerator:return "\n".join(f"@prefix {p}: <{u}> ." for p, u in sorted(graph.prefixes.items()))def _uri(self, graph: SHACLGraph, local: str) -> str:- """Return a compact URI reference; fall back to ex:local for bare names."""+ """+ Return a URI reference for a class or property name.++ Bare names are expanded through the graph's term index, which holds the+ IRI the data actually uses, rather than being pasted onto whichever+ namespace the shapes happen to live in (#1104).+ """if local.startswith("http://") or local.startswith("https://"):return f"<{local}>"+ resolved = graph.term_iris.get(local)+ if resolved:+ return f"<{resolved}>"if ":" in local:return localreturn f"ex:{local}"diff --git a/tests/ontology/test_ontology_advanced.py b/tests/ontology/test_ontology_advanced.pyindex 14ac52d5..98d5dc6e 100644--- a/tests/ontology/test_ontology_advanced.py+++ b/tests/ontology/test_ontology_advanced.py@@ -293,20 +293,33 @@ class TestSHACLHierarchicalAndValidation(unittest.TestCase):f"Duplicate paths in {node_shape.target_class}: {paths}")# 21- def test_no_domain_property_attaches_to_all_shapes(self):- onto = {- "classes": [{"name": "A"}, {"name": "B"}],- "properties": [- {"name": "globalProp", "type": "datatype", "range": "string"}- # no domain- ],- }- gen = self._make_gen()- graph = gen.generate(onto)+ _NO_DOMAIN_ONTOLOGY = {+ "classes": [{"name": "A"}, {"name": "B"}],+ "properties": [+ {"name": "globalProp", "type": "datatype", "range": "string"}+ # no domain+ ],+ }++ def test_no_domain_property_attaches_to_all_shapes_when_opted_in(self):+ """attach_domainless_properties=True keeps the pre-0.6.6 behaviour."""+ gen = self._make_gen(attach_domainless_properties=True)+ graph = gen.generate(self._NO_DOMAIN_ONTOLOGY)for node_shape in graph.node_shapes:paths = {ps.path for ps in node_shape.property_shapes}self.assertIn("globalProp", paths)+ def test_no_domain_property_is_not_attached_by_default(self):+ """+ Attaching states a constraint the ontology does not (#1105). This test+ previously asserted the opposite, which pinned the defect in place.+ """+ gen = self._make_gen()+ graph = gen.generate(self._NO_DOMAIN_ONTOLOGY)+ for node_shape in graph.node_shapes:+ paths = {ps.path for ps in node_shape.property_shapes}+ self.assertNotIn("globalProp", paths)+# 22def test_empty_classes_produces_no_shapes(self):gen = self._make_gen()diff --git a/tests/ontology/test_shacl_target_namespace.py b/tests/ontology/test_shacl_target_namespace.pynew file mode 100644index 00000000..74449490--- /dev/null+++ b/tests/ontology/test_shacl_target_namespace.py@@ -0,0 +1,216 @@+"""+Regression tests for #1104 and #1105.++#1104: SHACLGenerator used one namespace for two different jobs. `base_uri`+names where the shape resources live, and it was also used to expand every+sh:targetClass and sh:path. With the default `https://semantica.dev/shapes/`+that made shapes target `.../shapes/Person`, while data carries+`.../ns#Person` or the ontology's own class IRI. The shapes matched nothing.+pySHACL then reported conforms=True, because a shape with no focus nodes is+vacuously satisfied, so the mismatch was invisible to the validator the+package ships with.++#1105: a property with no declared domain was attached to every node shape,+which invents a constraint the ontology never stated. With minCount 1 that+makes every instance of every class invalid.++These tests validate real data through pySHACL rather than reading the shapes+text, so a shape that targets nothing cannot pass by being ignored.+"""++import pytest++rdflib = pytest.importorskip("rdflib")+pyshacl = pytest.importorskip("pyshacl")++from rdflib import Graph, RDF, Namespace # noqa: E402++from semantica.ontology.ontology_generator import SHACLGenerator # noqa: E402++SH = Namespace("http://www.w3.org/ns/shacl#")+ONTOLOGY_NS = "https://example.org/onto#"+SHAPES_NS = "https://semantica.dev/shapes/"+++def _ontology(*, declare_namespace: bool, carry_class_uris: bool):+ """+ Build the same ontology in the shapes the generator can hand over.++ A generated ontology carries class URIs; a hand written one often carries+ only names, and only sometimes declares a namespace. All of them have to+ produce shapes that match the data.+ """+ def class_def(name):+ entry = {"name": name, "label": name}+ if carry_class_uris:+ entry["uri"] = ONTOLOGY_NS + name+ return entry++ def prop_def(name, **extra):+ entry = {"name": name, "type": "datatype", "range": "string", **extra}+ if carry_class_uris:+ entry["uri"] = ONTOLOGY_NS + name+ return entry++ ontology = {+ "classes": [class_def("Person"), class_def("Organization")],+ "properties": [+ prop_def("fullName", domain="Person", required=True),+ # No domain. The ontology never says which class this belongs to.+ prop_def("sourceDocument", required=True),+ ],+ }+ if declare_namespace:+ ontology["namespace"] = {"base_uri": ONTOLOGY_NS}+ return ontology+++SHAPES = [+ pytest.param(True, True, id="namespace+uris"),+ pytest.param(True, False, id="namespace-only"),+ pytest.param(False, True, id="uris-only"),+]++# A Person with no fullName. This violates the shape the ontology does state.+VIOLATING_DATA = f"""+@prefix ex: <{ONTOLOGY_NS}> .+ex:alice a ex:Person .+"""++# A Person that satisfies every constraint the ontology actually declares.+CONFORMING_DATA = f"""+@prefix ex: <{ONTOLOGY_NS}> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .+ex:bob a ex:Person ;+ ex:fullName "Bob Smith"^^xsd:string .+"""+++def _shapes_graph(ontology, **kwargs):+ generator = SHACLGenerator(**kwargs)+ graph = generator.generate(ontology)+ shapes = Graph()+ shapes.parse(data=generator.serialize(graph, "turtle"), format="turtle")+ return shapes+++def _validate(data_ttl, shapes_graph):+ data = Graph()+ data.parse(data=data_ttl, format="turtle")+ conforms, _, text = pyshacl.validate(+ data, shacl_graph=shapes_graph, inference="none", advanced=True+ )+ return conforms, text++[email protected]("declare_namespace,carry_class_uris", SHAPES)+def test_target_class_names_a_class_the_data_can_instantiate(declare_namespace, carry_class_uris):+ shapes = _shapes_graph(_ontology(+ declare_namespace=declare_namespace, carry_class_uris=carry_class_uris+ ))+ targets = {str(o) for o in shapes.objects(None, SH.targetClass)}++ assert targets == {ONTOLOGY_NS + "Person", ONTOLOGY_NS + "Organization"}, targets+ assert not any(t.startswith(SHAPES_NS) for t in targets), (+ f"shapes still target their own shapes namespace: {targets}"+ )++[email protected]("declare_namespace,carry_class_uris", SHAPES)+def test_property_path_names_a_predicate_the_data_uses(declare_namespace, carry_class_uris):+ shapes = _shapes_graph(_ontology(+ declare_namespace=declare_namespace, carry_class_uris=carry_class_uris+ ))+ paths = {str(o) for o in shapes.objects(None, SH.path)}++ assert paths, "no sh:path emitted at all"+ for path in paths:+ assert path.startswith(ONTOLOGY_NS), path++[email protected]("declare_namespace,carry_class_uris", SHAPES)+def test_a_real_violation_is_actually_reported(declare_namespace, carry_class_uris):+ """The killer case. Shapes that match nothing make pySHACL return conforms=True."""+ shapes = _shapes_graph(_ontology(+ declare_namespace=declare_namespace, carry_class_uris=carry_class_uris+ ))+ conforms, text = _validate(VIOLATING_DATA, shapes)++ assert not conforms, (+ "a Person with no fullName was reported as conforming, which means the "+ f"shapes matched no focus nodes:\n{text}"+ )+ assert "fullName" in text++[email protected]("declare_namespace,carry_class_uris", SHAPES)+def test_conforming_data_still_conforms(declare_namespace, carry_class_uris):+ shapes = _shapes_graph(_ontology(+ declare_namespace=declare_namespace, carry_class_uris=carry_class_uris+ ))+ conforms, text = _validate(CONFORMING_DATA, shapes)+ assert conforms, text+++def test_default_target_namespace_is_the_vocabulary_not_the_shapes_namespace():+ """With nothing declared anywhere, targets must not land in the shapes namespace."""+ ontology = {+ "classes": [{"name": "Person", "label": "Person"}],+ "properties": [{"name": "fullName", "type": "datatype", "range": "string",+ "domain": "Person", "required": True}],+ }+ shapes = _shapes_graph(ontology)+ targets = {str(o) for o in shapes.objects(None, SH.targetClass)}++ assert targets, "no sh:targetClass emitted at all"+ for target in targets:+ assert not target.startswith(SHAPES_NS), target+++def test_shape_resources_are_distinct_from_the_classes_they_target():+ shapes = _shapes_graph(_ontology(declare_namespace=True, carry_class_uris=True))+ node_shapes = {str(s) for s in shapes.subjects(RDF.type, SH.NodeShape)}+ targets = {str(o) for o in shapes.objects(None, SH.targetClass)}++ assert node_shapes, "no node shapes emitted"+ assert node_shapes.isdisjoint(targets), (+ f"a shape and the class it targets are the same resource: {node_shapes & targets}"+ )+++# ── #1105 ────────────────────────────────────────────────────────────────────++def test_domainless_property_is_not_asserted_on_every_class():+ """minCount 1 on a domain-less property invalidates every instance of every class."""+ generator = SHACLGenerator()+ graph = generator.generate(_ontology(declare_namespace=True, carry_class_uris=True))++ carriers = [+ shape.target_class+ for shape in graph.node_shapes+ for prop in shape.property_shapes+ if prop.path.endswith("sourceDocument")+ ]+ assert carriers == [], f"a property with no declared domain was attached to {carriers}"+++def test_domainless_property_does_not_invalidate_conforming_data():+ shapes = _shapes_graph(_ontology(declare_namespace=True, carry_class_uris=True))+ conforms, text = _validate(CONFORMING_DATA, shapes)++ assert conforms, f"invented a constraint the ontology never declared:\n{text}"+ assert "sourceDocument" not in text+++def test_domainless_attachment_is_available_as_an_explicit_opt_in():+ """The old behaviour stays reachable for anyone who relied on it."""+ generator = SHACLGenerator(attach_domainless_properties=True)+ graph = generator.generate(_ontology(declare_namespace=True, carry_class_uris=True))++ carriers = {+ shape.target_class+ for shape in graph.node_shapes+ for prop in shape.property_shapes+ if prop.path.endswith("sourceDocument")+ }+ assert len(carriers) == len(graph.node_shapes)