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
changed struct approach and an e2e test
ZohaibHassan16bcdf3c357ab0
diff --git a/docs/reference/ontology.md b/docs/reference/ontology.mdindex fb3cc9ab..4fded4b6 100644--- a/docs/reference/ontology.md+++ b/docs/reference/ontology.md@@ -262,19 +262,21 @@ You can create and query alignments programmatically using the `OntologyEngine`:```pythonfrom semantica.ontology.engine import OntologyEngine+from semantica.triplet_store.triplet_store import TripletStore-# Ensure your engine is initialized with a TripletStore instance+# Setup the store and engine (using Blazegraph as an example)+my_triplet_store = TripletStore(backend="blazegraph")engine = OntologyEngine(store=my_triplet_store)# Create an alignment between an internal class and a standard schemaengine.create_alignment(- source_uri="http://internal.org/ontology/Employee"- target_uri="[http://schema.org/Person]",- predicate="[http://www.w3.org/2002/07/owl#equivalentClass]"+ source_uri="http://internal.org/ontology/Employee",+ target_uri="http://schema.org/Person",+ predicate="http://www.w3.org/2002/07/owl#equivalentClass")# Retrieve all bidirectional alignments for a specific entity-alignments = engine.get_alignments("[http://internal.org/ontology/Employee](http://internal.org/ontology/Employee)")+alignments = engine.get_alignments("http://internal.org/ontology/Employee")```### Automated Alignment Suggestionsdiff --git a/semantica/ontology/engine.py b/semantica/ontology/engine.pyindex 6c2bbc1b..cf7dd893 100644--- a/semantica/ontology/engine.py+++ b/semantica/ontology/engine.py@@ -59,6 +59,12 @@ class OntologyEngine:) -> List[Dict[str, Any]]:return self.propgen.infer_properties(entities, relationships, classes, **options)+ def _sanitize_uri(self, uri: str) -> str:+ """Prevent SPARQL injection by percent-encoding dangerous characters."""+ if not isinstance(uri, str):+ return ""+ return uri.replace("<", "%3C").replace(">", "%3E")+def create_alignment(self, source_uri: str, target_uri: str, predicate: str, **options) -> None:"""Creates an alignment between two ontology entities and stores it.@@ -87,17 +93,24 @@ class OntologyEngine:"""if not self.store:raise ProcessingError("TripletStore instance not configured in OntologyEngine.")++ safe_uri = self._sanitize_uri(entity_uri)query = f"""SELECT ?s ?p ?o WHERE {{- {{ <{entity_uri}> ?p ?o . BIND(<{entity_uri}> AS ?s) }}+ {{ <{safe_uri}> ?p ?o . BIND(<{safe_uri}> AS ?s) }}UNION- {{ ?s ?p <{entity_uri}> . BIND(<{entity_uri}> AS ?o) }}+ {{ ?s ?p <{safe_uri}> . BIND(<{safe_uri}> AS ?o) }}- FILTER (- STRSTARTS(STR(?p), "http://www.w3.org/2002/07/owl#") ||- STRSTARTS(STR(?p), "http://www.w3.org/2004/02/skos/core#")- )+ FILTER (?p IN (+ <http://www.w3.org/2002/07/owl#equivalentClass>,+ <http://www.w3.org/2002/07/owl#equivalentProperty>,+ <http://www.w3.org/2002/07/owl#sameAs>,+ <http://www.w3.org/2004/02/skos/core#exactMatch>,+ <http://www.w3.org/2004/02/skos/core#closeMatch>,+ <http://www.w3.org/2004/02/skos/core#broadMatch>,+ <http://www.w3.org/2004/02/skos/core#narrowMatch>+ ))}}"""try:@@ -125,16 +138,22 @@ class OntologyEngine:filter_clause = ""if ontology_uri:- filter_clause = f'FILTER(STRSTARTS(STR(?s), "{ontology_uri}") || STRSTARTS(STR(?o), "{ontology_uri}"))'+ # Sanitize double quotes to prevent breaking out of the STRSTARTS string literal+ safe_ontology_uri = ontology_uri.replace('"', '%22')+ filter_clause = f'FILTER(STRSTARTS(STR(?s), "{safe_ontology_uri}") || STRSTARTS(STR(?o), "{safe_ontology_uri}"))'query = f"""SELECT ?s ?p ?o WHERE {{?s ?p ?o .- FILTER (- STRSTARTS(STR(?p), "http://www.w3.org/2002/07/owl#equivalent") ||- STRSTARTS(STR(?p), "http://www.w3.org/2002/07/owl#sameAs") ||- STRSTARTS(STR(?p), "http://www.w3.org/2004/02/skos/core#")- )+ FILTER (?p IN (+ <http://www.w3.org/2002/07/owl#equivalentClass>,+ <http://www.w3.org/2002/07/owl#equivalentProperty>,+ <http://www.w3.org/2002/07/owl#sameAs>,+ <http://www.w3.org/2004/02/skos/core#exactMatch>,+ <http://www.w3.org/2004/02/skos/core#closeMatch>,+ <http://www.w3.org/2004/02/skos/core#broadMatch>,+ <http://www.w3.org/2004/02/skos/core#narrowMatch>+ )){filter_clause}}}"""@@ -153,9 +172,7 @@ class OntologyEngine:except Exception as e:self.logger.error(f"Failed to list alignments: {e}")raise ProcessingError(f"Failed to list alignments: {e}")---+def evaluate(self, ontology: Dict[str, Any], **options):return self.evaluator.evaluate_ontology(ontology, **options)@@ -166,7 +183,4 @@ class OntologyEngine:return self.owl.generate_owl(ontology, format=format, **options)def export_owl(self, ontology: Dict[str, Any], path: str, format: str = "turtle"):- return self.owl.export_owl(ontology, path, format=format)---+ return self.owl.export_owl(ontology, path, format=format)\ No newline at end of filediff --git a/semantica/ontology/reuse_manager.py b/semantica/ontology/reuse_manager.pyindex 16ec266d..22e95138 100644--- a/semantica/ontology/reuse_manager.py+++ b/semantica/ontology/reuse_manager.py@@ -369,19 +369,11 @@ class ReuseManager:) -> List[Dict[str, str]]:"""Suggest alignments between a source and target ontology based on heuristics.- Currently matches identical class/property names with differing URIs.-- Args:- target: Target ontology dictionary- source: Source ontology dictionary- **options: Additional heuristics configurations-- Returns:- List of alignment dictionaries (source_uri, target_uri, predicate, reason)"""suggestions = []- # Helper to find matches based on identical names+ # Nested function for DRY+def find_matches(target_items, source_items, entity_type):predicate = ("http://www.w3.org/2002/07/owl#equivalentClass"@@ -389,34 +381,36 @@ class ReuseManager:else "http://www.w3.org/2002/07/owl#equivalentProperty")+ # Build hash map of target entities by normalized name+ target_map = {}+ for t_item in target_items:+ t_uri = t_item.get("uri")+ t_name = t_item.get("name", "").strip().lower()+ if t_uri and t_name:+ target_map.setdefault(t_name, []).append(t_uri)++ # Single pass through source items checking the hash mapfor s_item in source_items:s_uri = s_item.get("uri")s_name = s_item.get("name", "").strip().lower()if not s_uri or not s_name:continue- for t_item in target_items:- t_uri = t_item.get("uri")- t_name = t_item.get("name", "").strip().lower()-- if not t_uri or not t_name:- continue-- # If names match exactly but URIs are different, suggest an alignment- if s_name == t_name and s_uri != t_uri:- suggestions.append({- "source_uri": s_uri,- "target_uri": t_uri,- "predicate": predicate,- "reason": f"Exact label match for {entity_type}: '{s_item.get('name')}'"- })-+ if s_name in target_map:+ for t_uri in target_map[s_name]:+ if s_uri != t_uri:+ suggestions.append({+ "source_uri": s_uri,+ "target_uri": t_uri,+ "predicate": predicate,+ "reason": f"Exact label match for {entity_type}: '{s_item.get('name')}'"+ })find_matches(target.get("classes", []), source.get("classes", []), "class")find_matches(target.get("properties", []), source.get("properties", []), "property")return suggestions-+def merge_ontology_data(self, target: Dict[str, Any], source: Dict[str, Any], **optionsdiff --git a/semantica/triplet_store/query_engine.py b/semantica/triplet_store/query_engine.pyindex e90a9869..36cb4ec2 100644--- a/semantica/triplet_store/query_engine.py+++ b/semantica/triplet_store/query_engine.py@@ -290,17 +290,23 @@ class QueryEngine:)# SPARQL query to find bidirectional alignments++ safe_uri = self._sanitize_uri(entity_uri)query = f"""SELECT DISTINCT ?aligned WHERE {{- {{ <{entity_uri}> ?p ?aligned }}+ {{ <{safe_uri}> ?p ?aligned }}UNION- {{ ?aligned ?p <{entity_uri}> }}+ {{ ?aligned ?p <{safe_uri}> }}- FILTER (- STRSTARTS(STR(?p), "http://www.w3.org/2002/07/owl#equivalent") ||- STRSTARTS(STR(?p), "http://www.w3.org/2002/07/owl#sameAs") ||- STRSTARTS(STR(?p), "http://www.w3.org/2004/02/skos/core#")- )+ FILTER (?p IN (+ <http://www.w3.org/2002/07/owl#equivalentClass>,+ <http://www.w3.org/2002/07/owl#equivalentProperty>,+ <http://www.w3.org/2002/07/owl#sameAs>,+ <http://www.w3.org/2004/02/skos/core#exactMatch>,+ <http://www.w3.org/2004/02/skos/core#closeMatch>,+ <http://www.w3.org/2004/02/skos/core#broadMatch>,+ <http://www.w3.org/2004/02/skos/core#narrowMatch>+ ))}}"""@@ -417,6 +423,12 @@ class QueryEngine:cache_key = self._get_cache_key(query)self.query_cache[cache_key] = result++ def _sanitize_uri(self, uri: str) -> str:+ """Prevent SPARQL injection by percent-encoding dangerous characters."""+ if not isinstance(uri, str):+ return ""+ return uri.replace("<", "%3C").replace(">", "%3E")def clear_cache(self) -> None:"""Clear query cache."""diff --git a/tests/triplet_store/test_triplet_store.py b/tests/triplet_store/test_triplet_store.pyindex 5a6e0dad..053d70ae 100644--- a/tests/triplet_store/test_triplet_store.py+++ b/tests/triplet_store/test_triplet_store.py@@ -134,3 +134,23 @@ class TestTripletStore(unittest.TestCase):self.assertIn("http://ex.org/aligned_entity", result)self.assertEqual(len(result), 2)mock_backend.execute_sparql.assert_called_once()++ def test_end_to_end_cross_ontology_uri_flow(self):+ engine = QueryEngine()+ engine.expand_entity_uri = MagicMock(return_value=["http://ex.org/1", "http://aligned.org/2"])+++ original_uri = "http://ex.org/1"+ expanded = engine.expand_entity_uri(original_uri, store_backend=MagicMock(), use_alignments=True)+ values_clause = engine.build_values_clause("subject", expanded)++ mock_select_query = f"""+ SELECT DISTINCT ?aligned WHERE {{+ {values_clause}+ ?subject <http://schema.org/name> ?name .+ }}+ """++ self.assertIn("<http://ex.org/1> <http://aligned.org/2>", mock_select_query)+ self.assertIn("VALUES ?subject", mock_select_query)+ engine.expand_entity_uri.assert_called_once()