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(triplet-store): resolve entity/class/property IRIs against ontology namespace base_uri (Fixes #447)
KaifAhmad10b52b715dc1b
diff --git a/semantica/triplet_store/triplet_store.py b/semantica/triplet_store/triplet_store.pyindex 6ba88f4b..026d22dc 100644--- a/semantica/triplet_store/triplet_store.py+++ b/semantica/triplet_store/triplet_store.py@@ -170,6 +170,30 @@ class TripletStore:RDFS_DOMAIN = "http://www.w3.org/2000/01/rdf-schema#domain"RDFS_RANGE = "http://www.w3.org/2000/01/rdf-schema#range"+ # Resolve base URI from ontology — used to mint entity/class/property IRIs+ # that are reconcilable with the ontology's own namespace.+ ns = ontology.get("namespace") or {}+ if isinstance(ns, dict):+ base_uri = ns.get("base_uri") or ontology.get("uri") or ""+ else:+ base_uri = ontology.get("uri") or ""+ # Ensure trailing separator so "base_uri + local" is always a valid IRI path.+ if base_uri and not base_uri.endswith(("/", "#")):+ base_uri = base_uri + "/"++ def _resolve_iri(local: str, kind: str) -> str:+ """Expand a bare local name to a full IRI.++ If *base_uri* is available the local name is appended to it so the+ resulting IRI sits in the same namespace as the ontology classes.+ Falls back to ``urn:<kind>:<local>`` only when no base URI is known.+ """+ if local.startswith("http") or local.startswith("urn:"):+ return local+ if base_uri:+ return f"{base_uri}{local}"+ return f"urn:{kind}:{local}"+# 1. Process Ontologyclasses = ontology.get("classes", [])properties = ontology.get("properties", [])@@ -180,18 +204,13 @@ class TripletStore:if not cls_uri:continue- if not cls_uri.startswith("http") and not cls_uri.startswith("urn:"):- # Fallback if no URI provided- cls_uri = f"urn:class:{cls_uri}"-+ cls_uri = _resolve_iri(cls_uri, "class")triplets.append(Triplet(cls_uri, RDF_TYPE, OWL_CLASS))# Hierarchyparent = cls.get("parent") or cls.get("subClassOf")if parent:- parent_uri = parent- if not parent.startswith("http") and not parent.startswith("urn:"):- parent_uri = f"urn:class:{parent}"+ parent_uri = _resolve_iri(parent, "class")triplets.append(Triplet(cls_uri, RDFS_SUBCLASS, parent_uri))for prop in properties:@@ -199,8 +218,7 @@ class TripletStore:if not prop_uri:continue- if not prop_uri.startswith("http") and not prop_uri.startswith("urn:"):- prop_uri = f"urn:property:{prop_uri}"+ prop_uri = _resolve_iri(prop_uri, "property")# Determine property type (Object or Datatype)# Default to ObjectProperty if not specified@@ -218,9 +236,7 @@ class TripletStore:domains = [domains]for domain in domains:- domain_uri = domain- if not domain.startswith("http") and not domain.startswith("urn:"):- domain_uri = f"urn:class:{domain}"+ domain_uri = _resolve_iri(domain, "class")triplets.append(Triplet(prop_uri, RDFS_DOMAIN, domain_uri))if "range" in prop:@@ -229,9 +245,7 @@ class TripletStore:ranges = [ranges]for range_ in ranges:- range_uri = range_- if not range_.startswith("http") and not range_.startswith("urn:"):- range_uri = f"urn:class:{range_}"+ range_uri = _resolve_iri(range_, "class")triplets.append(Triplet(prop_uri, RDFS_RANGE, range_uri))# 2. Process Knowledge Graph@@ -245,28 +259,19 @@ class TripletStore:if not entity_id:continue- entity_uri = entity.get("uri")- if not entity_uri:- entity_uri = f"urn:entity:{entity_id}"-+ entity_uri = entity.get("uri") or _resolve_iri(entity_id, "entity")entity_map[entity_id] = entity_uri# Entity Typeentity_type = entity.get("type")if entity_type:- type_uri = entity_type- if not entity_type.startswith("http") and not entity_type.startswith(- "urn:"- ):- type_uri = f"urn:class:{entity_type}"+ type_uri = _resolve_iri(entity_type, "class")triplets.append(Triplet(entity_uri, RDF_TYPE, type_uri))# Entity Propertiesprops = entity.get("properties", {})for k, v in props.items():- prop_uri = k- if not k.startswith("http") and not k.startswith("urn:"):- prop_uri = f"urn:property:{k}"+ prop_uri = _resolve_iri(k, "property")triplets.append(Triplet(entity_uri, prop_uri, str(v)))for rel in relationships:@@ -277,11 +282,9 @@ class TripletStore:if not source_id or not target_id or not rel_type:continue- source_uri = entity_map.get(source_id, f"urn:entity:{source_id}")- target_uri = entity_map.get(target_id, f"urn:entity:{target_id}")- rel_uri = rel_type- if not rel_type.startswith("http") and not rel_type.startswith("urn:"):- rel_uri = f"urn:property:{rel_type}"+ source_uri = entity_map.get(source_id) or _resolve_iri(source_id, "entity")+ target_uri = entity_map.get(target_id) or _resolve_iri(target_id, "entity")+ rel_uri = _resolve_iri(rel_type, "property")triplets.append(Triplet(source_uri, rel_uri, target_uri))diff --git a/tests/triplet_store/test_triplet_store.py b/tests/triplet_store/test_triplet_store.pyindex 2a424477..a320511e 100644--- a/tests/triplet_store/test_triplet_store.py+++ b/tests/triplet_store/test_triplet_store.py@@ -482,3 +482,122 @@ class TestSKOSTripletStore(unittest.TestCase):return_value=QueryResult(bindings=[], variables=[]))self.assertEqual(store.get_skos_concepts(), [])+++@patch("semantica.triplet_store.blazegraph_store.BlazegraphStore")+class TestTripletStoreOntologyNamespace(unittest.TestCase):+ """Regression tests for Issue #447 — store() must use ontology namespace base_uri."""++ BASE = "https://example.com/"++ def _make_store(self, mock_bg):+ """Return (store, captured_triplets_list).++ add_triplets is patched so store() never touches the bulk_loader or+ backend; instead every Triplet passed to it is appended to the list.+ """+ captured = []++ def _capture(triplets, **_kw):+ captured.extend(triplets)+ return {"success": True}++ with (+ patch("semantica.triplet_store.triplet_store.get_logger", return_value=MagicMock()),+ patch("semantica.triplet_store.triplet_store.get_progress_tracker", return_value=MagicMock()),+ ):+ store = TripletStore(backend="blazegraph")+ store.add_triplets = _capture+ return store, captured++ def _ontology(self):+ return {+ "namespace": {"base_uri": self.BASE},+ "classes": [{"name": "Person"}],+ "properties": [{"name": "knows", "domain": ["Person"], "range": ["Person"]}],+ }++ def _kg(self):+ return {+ "entities": [+ {"id": "alice", "type": "Person"},+ {"id": "bob", "type": "Person"},+ ],+ "relationships": [{"source": "alice", "target": "bob", "type": "knows"}],+ }++ def test_entity_uri_uses_base_uri(self, mock_bg):+ store, captured = self._make_store(mock_bg)+ store.store(self._kg(), self._ontology())+ subjects = {t.subject for t in captured}+ self.assertIn(f"{self.BASE}alice", subjects)+ self.assertIn(f"{self.BASE}bob", subjects)+ self.assertNotIn("urn:entity:alice", subjects)++ def test_entity_type_uses_base_uri(self, mock_bg):+ store, captured = self._make_store(mock_bg)+ store.store(self._kg(), self._ontology())+ RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"+ type_objects = {t.object for t in captured if t.predicate == RDF_TYPE}+ self.assertIn(f"{self.BASE}Person", type_objects)+ self.assertNotIn("urn:class:Person", type_objects)++ def test_relationship_type_uses_base_uri(self, mock_bg):+ store, captured = self._make_store(mock_bg)+ store.store(self._kg(), self._ontology())+ predicates = {t.predicate for t in captured}+ self.assertIn(f"{self.BASE}knows", predicates)+ self.assertNotIn("urn:property:knows", predicates)++ def test_ontology_class_uri_uses_base_uri(self, mock_bg):+ store, captured = self._make_store(mock_bg)+ store.store(self._kg(), self._ontology())+ OWL_CLASS = "http://www.w3.org/2002/07/owl#Class"+ class_subjects = {t.subject for t in captured if t.object == OWL_CLASS}+ self.assertIn(f"{self.BASE}Person", class_subjects)++ def test_ontology_property_domain_range_use_base_uri(self, mock_bg):+ store, captured = self._make_store(mock_bg)+ store.store(self._kg(), self._ontology())+ RDFS_DOMAIN = "http://www.w3.org/2000/01/rdf-schema#domain"+ RDFS_RANGE = "http://www.w3.org/2000/01/rdf-schema#range"+ domain_objects = {t.object for t in captured if t.predicate == RDFS_DOMAIN}+ range_objects = {t.object for t in captured if t.predicate == RDFS_RANGE}+ self.assertIn(f"{self.BASE}Person", domain_objects)+ self.assertIn(f"{self.BASE}Person", range_objects)++ def test_explicit_entity_uri_not_overridden(self, mock_bg):+ store, captured = self._make_store(mock_bg)+ kg = {"entities": [{"id": "alice", "uri": "https://other.org/Alice", "type": "Person"}], "relationships": []}+ store.store(kg, self._ontology())+ subjects = {t.subject for t in captured}+ self.assertIn("https://other.org/Alice", subjects)+ self.assertNotIn(f"{self.BASE}alice", subjects)++ def test_no_base_uri_falls_back_to_urn(self, mock_bg):+ store, captured = self._make_store(mock_bg)+ kg = {"entities": [{"id": "alice", "type": "Person"}], "relationships": []}+ ontology = {"classes": [{"name": "Person"}], "properties": []}+ store.store(kg, ontology)+ subjects = {t.subject for t in captured}+ self.assertIn("urn:entity:alice", subjects)++ def test_base_uri_via_top_level_uri_key(self, mock_bg):+ """ontology['uri'] should work as a fallback when namespace dict is absent."""+ store, captured = self._make_store(mock_bg)+ ontology = {"uri": self.BASE, "classes": [{"name": "Person"}], "properties": []}+ kg = {"entities": [{"id": "alice", "type": "Person"}], "relationships": []}+ store.store(kg, ontology)+ subjects = {t.subject for t in captured}+ self.assertIn(f"{self.BASE}alice", subjects)++ def test_trailing_slash_not_doubled(self, mock_bg):+ """base_uri already ending with '/' must not produce 'base//local'."""+ store, captured = self._make_store(mock_bg)+ ontology = {"namespace": {"base_uri": "https://example.com/"}, "classes": [], "properties": []}+ # Give alice a type so a triplet is emitted with alice as subject+ kg = {"entities": [{"id": "alice", "type": "Person"}], "relationships": []}+ store.store(kg, ontology)+ subjects = {t.subject for t in captured}+ self.assertIn("https://example.com/alice", subjects)+ self.assertNotIn("https://example.com//alice", subjects)