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: resolve all remaining review issues in ontology alignment API
KaifAhmad139c9fc97b40e
diff --git a/semantica/ontology/engine.py b/semantica/ontology/engine.pyindex cf7dd893..2bd9fb36 100644--- a/semantica/ontology/engine.py+++ b/semantica/ontology/engine.py@@ -72,6 +72,12 @@ class OntologyEngine:if not self.store:raise ProcessingError("TripletStore instance not configured in OntologyEngine.")+ if not predicate.startswith(("http://", "https://")):+ raise ProcessingError(+ f"predicate must be a full URI (e.g. 'http://www.w3.org/2002/07/owl#equivalentClass'), "+ f"not a CURIE: '{predicate}'"+ )+tracking_id = self.progress.start_tracking(module="ontology",submodule="OntologyEngine",@@ -109,13 +115,14 @@ class OntologyEngine:<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>+ <http://www.w3.org/2004/02/skos/core#narrowMatch>,+ <http://www.w3.org/2004/02/skos/core#relatedMatch>))}}"""try:results = self.store.execute_query(query, **options)-+alignments = []if hasattr(results, 'bindings'):for b in results.bindings:@@ -138,8 +145,14 @@ class OntologyEngine:filter_clause = ""if ontology_uri:- # Sanitize double quotes to prevent breaking out of the STRSTARTS string literal- safe_ontology_uri = ontology_uri.replace('"', '%22')+ # Sanitize characters that could break out of the SPARQL string literal or WHERE block+ safe_ontology_uri = (+ ontology_uri+ .replace("\\", "%5C")+ .replace('"', '%22')+ .replace("{", "%7B")+ .replace("}", "%7D")+ )filter_clause = f'FILTER(STRSTARTS(STR(?s), "{safe_ontology_uri}") || STRSTARTS(STR(?o), "{safe_ontology_uri}"))'query = f"""@@ -152,7 +165,8 @@ class OntologyEngine:<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>+ <http://www.w3.org/2004/02/skos/core#narrowMatch>,+ <http://www.w3.org/2004/02/skos/core#relatedMatch>)){filter_clause}}}diff --git a/semantica/triplet_store/query_engine.py b/semantica/triplet_store/query_engine.pyindex 36cb4ec2..3e0dd315 100644--- a/semantica/triplet_store/query_engine.py+++ b/semantica/triplet_store/query_engine.py@@ -305,11 +305,12 @@ class QueryEngine:<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>+ <http://www.w3.org/2004/02/skos/core#narrowMatch>,+ <http://www.w3.org/2004/02/skos/core#relatedMatch>))}}"""-+expanded_uris = set([entity_uri])try:if hasattr(store_backend, "execute_sparql"):@@ -319,17 +320,19 @@ class QueryEngine:uri = val.get("value") if isinstance(val, dict) else valif uri:expanded_uris.add(uri)-+ else:+ self.logger.warning(+ "store_backend does not support execute_sparql; returning original URI only"+ )self.progress_tracker.stop_tracking(- tracking_id,- status="completed",+ tracking_id,+ status="completed",message=f"Expanded to {len(expanded_uris)} URIs")except Exception as e:self.logger.error(f"Failed to expand alignments for {entity_uri}: {e}")self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))- # Fallback to returning just the original URI if the expansion query fails-+return list(expanded_uris)def build_values_clause(self, variable_name: str, uris: List[str]) -> str:@@ -344,7 +347,7 @@ class QueryEngine:"""if not uris:return ""- formatted_uris = " ".join([f"<{uri}>" for uri in uris])+ formatted_uris = " ".join([f"<{self._sanitize_uri(uri)}>" for uri in uris])return f"VALUES ?{variable_name} {{ {formatted_uris} }}"def _validate_query(self, query: str) -> bool:diff --git a/tests/triplet_store/test_triplet_store.py b/tests/triplet_store/test_triplet_store.pyindex 053d70ae..4bc72e98 100644--- a/tests/triplet_store/test_triplet_store.py+++ b/tests/triplet_store/test_triplet_store.py@@ -136,21 +136,29 @@ class TestTripletStore(unittest.TestCase):mock_backend.execute_sparql.assert_called_once()def test_end_to_end_cross_ontology_uri_flow(self):+ """+ Full end-to-end: real expand_entity_uri queries a mock backend,+ then build_values_clause injects the results into a SPARQL template.+ """engine = QueryEngine()- engine.expand_entity_uri = MagicMock(return_value=["http://ex.org/1", "http://aligned.org/2"])-+ mock_backend = MagicMock()+ mock_backend.execute_sparql.return_value = {+ "bindings": [{"aligned": {"value": "http://aligned.org/2"}}]+ }original_uri = "http://ex.org/1"- expanded = engine.expand_entity_uri(original_uri, store_backend=MagicMock(), use_alignments=True)+ expanded = engine.expand_entity_uri(original_uri, store_backend=mock_backend, use_alignments=True)values_clause = engine.build_values_clause("subject", expanded)-- mock_select_query = f"""- SELECT DISTINCT ?aligned WHERE {{++ sparql_query = f"""+ SELECT ?instance ?name WHERE {{{values_clause}- ?subject <http://schema.org/name> ?name .+ ?instance a ?subject .+ ?instance <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()++ self.assertIn("http://ex.org/1", sparql_query)+ self.assertIn("http://aligned.org/2", sparql_query)+ self.assertIn("VALUES ?subject", sparql_query)+ mock_backend.execute_sparql.assert_called_once()