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
Make SKOS hierarchy imports atomic
mikemikimikef992504227f1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8723c746..bc00cef6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,6 +43,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **No cycle detection for SKOS concepts at write time** (#774, #819) by @mikemikimike, reviewed by @Sameer6305 and @KaifAhmad1+ - Added cycle detection (`validate_skos_hierarchy`) for `skos:broader` and `skos:narrower` relationships in `ContextGraph.add_edge()` and `ContextGraph.add_edges()`, preventing direct 2-node cycles, self-loops, and multi-hop hierarchy cycles+ - Added `GraphSession.add_nodes_and_edges()` to validate SKOS hierarchy edges upfront under lock before node insertion, preventing partial-write leaks where nodes remain after a cyclic edge is rejected+ - Updated vocabulary, ontology (`/api/ontology/load`, `/api/ontology/create`), and JSON/CSV import routes to use `add_nodes_and_edges()` and return HTTP 422 with actionable error messages when a cycle is detected+- **`AgnoDecisionKit`/`AgnoKGToolkit` silently swallowed Agno tool registration failures** (#780, #818) by @Sameer6305 and @KaifAhmad1- Removed the `try/except: pass` wrapped around `self.register(fn)` in both toolkits' `__init__`; when Agno is installed, a registration failure now propagates immediately instead of leaving the toolkit half-registered with no signal to the caller- Graceful degradation when Agno isn't installed (`AGNO_AVAILABLE=False`) is unchanged — `_tools` is still populated so callers can introspect available tools without the packagediff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex 802295a1..f5ef322e 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -117,7 +117,7 @@ import uuidfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_trackerfrom ..utils.helpers import classify_path_distance-from ..utils.skos import validate_skos_hierarchy+from ..utils.skos import is_skos_hierarchy_edge, validate_skos_hierarchyfrom .entity_linker import EntityLinker# Optional imports for advanced features@@ -592,7 +592,12 @@ class ContextGraph:with self._lock:# Keep the SKOS hierarchy invariant at the lowest common write# layer so direct graph users cannot bypass API/session checks.- validate_skos_hierarchy([*self.find_edges(), *edges])+ hierarchy_edges = [edge for edge in edges if is_skos_hierarchy_edge(edge)]+ if hierarchy_edges:+ existing_edges = [+ edge for edge in self.find_edges() if is_skos_hierarchy_edge(edge)+ ]+ validate_skos_hierarchy([*existing_edges, *hierarchy_edges])for raw_edge in edges:if not isinstance(raw_edge, dict):continue@@ -952,12 +957,12 @@ class ContextGraph:family_id=explicit_family_id,)with self._lock:- validate_skos_hierarchy(- [- *self.find_edges(),- {"source": source_id, "target": target_id, "type": edge_type},+ candidate = {"source": source_id, "target": target_id, "type": edge_type}+ if is_skos_hierarchy_edge(candidate):+ existing_edges = [+ edge for edge in self.find_edges() if is_skos_hierarchy_edge(edge)]- )+ validate_skos_hierarchy([*existing_edges, candidate])return self._add_internal_edge(ContextEdge(edge_id=edge_id,diff --git a/semantica/explorer/routes/export_import.py b/semantica/explorer/routes/export_import.pyindex 3529590a..6beda930 100644--- a/semantica/explorer/routes/export_import.py+++ b/semantica/explorer/routes/export_import.py@@ -112,8 +112,10 @@ async def import_file(})- nodes_added = session.add_nodes(nodes)- edges_added = session.add_edges(edges)+ try:+ nodes_added, edges_added = session.add_nodes_and_edges(nodes, edges)+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from excreturn _import_response(nodes_added, edges_added)if filename.endswith(".csv"):@@ -184,8 +186,10 @@ async def import_file(detail="No valid nodes or edges could be parsed from the CSV payload.",)- nodes_added = session.add_nodes(nodes)- edges_added = session.add_edges(edges)+ try:+ nodes_added, edges_added = session.add_nodes_and_edges(nodes, edges)+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from excreturn _import_response(nodes_added, edges_added)raise HTTPException(diff --git a/semantica/explorer/routes/ontology.py b/semantica/explorer/routes/ontology.pyindex 31c21afa..2fac4c15 100644--- a/semantica/explorer/routes/ontology.py+++ b/semantica/explorer/routes/ontology.py@@ -1289,6 +1289,8 @@ async def load_ontology(temp_path,format=fmt)+ if not ontology_data.data.get("classes") and not ontology_data.data.get("properties"):+ raise ValueError("No OWL classes or properties found by OntologyIngestor")# Convert to graph nodes/edges using ontology datanodes, edges = await asyncio.to_thread(@@ -1296,9 +1298,12 @@ async def load_ontology(ontology_data.data)- # Add nodes and edges to session- nodes_added = await asyncio.to_thread(session.add_nodes, nodes)- edges_added = await asyncio.to_thread(session.add_edges, edges)+ try:+ nodes_added, edges_added = await asyncio.to_thread(+ session.add_nodes_and_edges, nodes, edges+ )+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc# Register in registryregistry = _get_registry(request)@@ -1347,8 +1352,12 @@ async def load_ontology(raise HTTPException(status_code=422, detail=f"Could not parse ontology: {exc}") from exc# Fallback path - use basic parsing- nodes_added = await asyncio.to_thread(session.add_nodes, nodes)- edges_added = await asyncio.to_thread(session.add_edges, edges)+ try:+ nodes_added, edges_added = await asyncio.to_thread(+ session.add_nodes_and_edges, nodes, edges+ )+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from excregistry = _get_registry(request)ontology_uri = metadata.get("uri", f"temp:{uuid.uuid4().hex[:12]}")@@ -1545,8 +1554,12 @@ async def create_ontology(logger.exception("Failed to generate ontology from schema text; aborting ontology creation.")raise HTTPException(status_code=500, detail=f"Ontology generation failed: {exc}") from exc- nodes_added = await asyncio.to_thread(session.add_nodes, nodes)- edges_added = await asyncio.to_thread(session.add_edges, edges)+ try:+ nodes_added, edges_added = await asyncio.to_thread(+ session.add_nodes_and_edges, nodes, edges+ )+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from excregistry = _get_registry(request)registry[onto_uri] = OntologyEntry(diff --git a/semantica/explorer/routes/vocabulary.py b/semantica/explorer/routes/vocabulary.pyindex 7ba6bbc4..17739b67 100644--- a/semantica/explorer/routes/vocabulary.py+++ b/semantica/explorer/routes/vocabulary.py@@ -225,13 +225,12 @@ async def import_vocabulary(raise HTTPException(status_code=422, detail=str(exc)) from exctry:- await asyncio.to_thread(session.validate_skos_hierarchy, edges)+ nodes_added, edges_added = await asyncio.to_thread(+ session.add_nodes_and_edges, nodes, edges+ )except ValueError as exc:raise HTTPException(status_code=422, detail=str(exc)) from exc- nodes_added = await asyncio.to_thread(session.add_nodes, nodes)- edges_added = await asyncio.to_thread(session.add_edges, edges)-return VocabularyImportResponse(status="success",filename=filename,diff --git a/semantica/explorer/session.py b/semantica/explorer/session.pyindex 9eafdb8c..369d326f 100644--- a/semantica/explorer/session.py+++ b/semantica/explorer/session.py@@ -13,7 +13,7 @@ from typing import Any, Dict, Iterable, List, Optionalfrom ..context.context_graph import ContextGraph, _resolve_edge_identityfrom .search_index import GraphSearchIndex-from ..utils.skos import validate_skos_hierarchy+from ..utils.skos import is_skos_hierarchy_edge, validate_skos_hierarchy_KG_AVAILABLE = Falsetry:@@ -748,8 +748,35 @@ class GraphSession:def validate_skos_hierarchy(self, edges: List[Dict[str, Any]]) -> None:"""Validate new SKOS hierarchy edges against the current graph."""- existing_edges = self.graph.find_edges()- validate_skos_hierarchy([*existing_edges, *edges])+ hierarchy_edges = [edge for edge in edges if is_skos_hierarchy_edge(edge)]+ if not hierarchy_edges:+ return+ existing_edges = [+ edge for edge in self.graph.find_edges() if is_skos_hierarchy_edge(edge)+ ]+ validate_skos_hierarchy([*existing_edges, *hierarchy_edges])++ def add_nodes_and_edges(+ self,+ nodes: List[Dict[str, Any]],+ edges: List[Dict[str, Any]],+ ) -> tuple[int, int]:+ """+ Validate SKOS hierarchy edges upfront and add nodes and edges under lock.++ Note: This provides lock-based mutual exclusion and pre-write validation,+ not transactional rollback atomicity.+ """+ with self._lock:+ self.validate_skos_hierarchy(edges)+ nodes_added = self.graph.add_nodes(nodes)+ edges_added = self.graph.add_edges(edges)+ has_mutation_callback = callable(getattr(self.graph, "mutation_callback", None))+ if (nodes_added or edges_added) and not has_mutation_callback:+ self._bump_graph_revision_locked()+ if (nodes_added or edges_added) and not has_mutation_callback:+ self.rebuild_search_index()+ return nodes_added, edges_addeddef add_node(self,@@ -778,6 +805,7 @@ class GraphSession:**properties: Any,) -> bool:with self._lock:+ self.validate_skos_hierarchy([{"source": source_id, "target": target_id, "type": edge_type}])added = self.graph.add_edge(source_id,target_id,diff --git a/semantica/utils/skos.py b/semantica/utils/skos.pyindex cfa48b0f..8c24bba5 100644--- a/semantica/utils/skos.py+++ b/semantica/utils/skos.py@@ -7,6 +7,16 @@ from typing import Iterable, Mapping_HIERARCHY_EDGE_TYPES = frozenset({"skos:broader", "skos:narrower"})+def is_skos_hierarchy_edge(edge: Mapping[str, object]) -> bool:+ """Return whether an edge uses a SKOS hierarchy predicate."""+ if not isinstance(edge, Mapping):+ return False+ return any(+ edge.get(key) in _HIERARCHY_EDGE_TYPES+ for key in ("type", "edge_type", "relationship", "predicate", "relation")+ )++def validate_skos_hierarchy(edges: Iterable[Mapping[str, object]]) -> None:"""Raise ``ValueError`` when SKOS hierarchy edges contain a cycle.@@ -18,21 +28,25 @@ def validate_skos_hierarchy(edges: Iterable[Mapping[str, object]]) -> None:parents: dict[str, set[str]] = defaultdict(set)for edge in edges:- if not isinstance(edge, Mapping):+ if not isinstance(edge, Mapping) or not is_skos_hierarchy_edge(edge):continueedge_type = next((edge.get(key)for key in ("type", "edge_type", "relationship", "predicate", "relation")- if edge.get(key) is not None+ if edge.get(key) in _HIERARCHY_EDGE_TYPES),None,)if edge_type not in _HIERARCHY_EDGE_TYPES:continue- source = str(edge.get("source", edge.get("source_id", "")))- target = str(edge.get("target", edge.get("target_id", "")))+ raw_source = edge.get("source", edge.get("source_id"))+ raw_target = edge.get("target", edge.get("target_id"))+ if raw_source is None or raw_target is None:+ continue+ source = str(raw_source).strip()+ target = str(raw_target).strip()if not source or not target:continuediff --git a/tests/explorer/test_ontology_subissue3.py b/tests/explorer/test_ontology_subissue3.pyindex 2d6f7d9d..40cb6bbe 100644--- a/tests/explorer/test_ontology_subissue3.py+++ b/tests/explorer/test_ontology_subissue3.py@@ -636,7 +636,25 @@ def test_health_shacl_dimension_returns_critical_for_truncated_graph(client):payload = client.get("/api/ontology/health?uri=http%3A%2F%2Fexample.org%2Fonto-a").json()shacl_dim = next(d for d in payload["dimensions"] if d["key"] == "shacl")assert shacl_dim["status"] == "critical"- assert shacl_dim["score"] == 0.0assert "exceeds maximum analysis limit" in shacl_dim["detail"]+def test_ontology_load_rejects_cyclic_skos_hierarchy(client):+ cyclic_ttl = """+@prefix skos: <http://www.w3.org/2004/02/skos/core#> .+@prefix ex: <http://example.org/> .+ex:S a skos:ConceptScheme ; skos:prefLabel "Scheme" .+ex:A a skos:Concept ; skos:prefLabel "Alpha" ; skos:inScheme ex:S ; skos:broader ex:B .+ex:B a skos:Concept ; skos:prefLabel "Beta" ; skos:inScheme ex:S ; skos:broader ex:A .+"""+ response = client.post(+ "/api/ontology/load",+ json={+ "content": cyclic_ttl,+ "format": "turtle",+ },+ )+ assert response.status_code == 422+ assert "cycle" in response.json()["detail"].lower()++diff --git a/tests/explorer/test_vocabulary.py b/tests/explorer/test_vocabulary.pyindex ee75ca7a..3de0f3e9 100644--- a/tests/explorer/test_vocabulary.py+++ b/tests/explorer/test_vocabulary.py@@ -124,8 +124,7 @@ def test_hierarchy_cycle_does_not_hang():def test_import_ttl_success():- mock_session.add_nodes.return_value = 2- mock_session.add_edges.return_value = 1+ mock_session.add_nodes_and_edges.return_value = (2, 1)response = client.post("/api/vocabulary/import",@@ -139,8 +138,7 @@ def test_import_ttl_success():def test_import_raw_text_success():- mock_session.add_nodes.return_value = 1- mock_session.add_edges.return_value = 0+ mock_session.add_nodes_and_edges.return_value = (1, 0)response = client.post("/api/vocabulary/import",@@ -151,8 +149,7 @@ def test_import_raw_text_success():def test_import_rdf_xml_success():- mock_session.add_nodes.return_value = 1- mock_session.add_edges.return_value = 0+ mock_session.add_nodes_and_edges.return_value = (1, 0)response = client.post("/api/vocabulary/import",@@ -171,7 +168,11 @@ def test_import_invalid_file_returns_422():def test_import_rejects_cyclic_hierarchy_before_writing_nodes():- mock_session.validate_skos_hierarchy.side_effect = lambda edges: validate_skos_hierarchy(edges)+ def add_nodes_and_edges(nodes, edges):+ validate_skos_hierarchy(edges)+ return 0, 0++ mock_session.add_nodes_and_edges.side_effect = add_nodes_and_edgesresponse = client.post("/api/vocabulary/import",@@ -180,4 +181,4 @@ def test_import_rejects_cyclic_hierarchy_before_writing_nodes():assert response.status_code == 422assert "cycle" in response.json()["detail"].lower()- mock_session.add_nodes.assert_not_called()+ mock_session.add_nodes_and_edges.assert_called_once()