Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Reject cyclic SKOS hierarchies

mikemikimike692260cc768f
diff --git a/semantica/explorer/routes/vocabulary.py b/semantica/explorer/routes/vocabulary.py
index 4e992229..7ba6bbc4 100644
--- a/semantica/explorer/routes/vocabulary.py
+++ b/semantica/explorer/routes/vocabulary.py
@@ -6,7 +6,7 @@ import asyncio
from collections import defaultdict
from typing import Dict, List, Optional
-from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
+from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile
from ..dependencies import get_session
from ..schemas import ConceptNode, ConceptSummary, VocabularyImportResponse, VocabularyScheme
@@ -224,6 +224,11 @@ async def import_vocabulary(
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
+ try:
+ await asyncio.to_thread(session.validate_skos_hierarchy, 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)
diff --git a/semantica/explorer/session.py b/semantica/explorer/session.py
index 8692f59e..19c3d885 100644
--- a/semantica/explorer/session.py
+++ b/semantica/explorer/session.py
@@ -13,6 +13,7 @@ from typing import Any, Dict, Iterable, List, Optional
from ..context.context_graph import ContextGraph, _resolve_edge_identity
from .search_index import GraphSearchIndex
+from .utils.skos import validate_skos_hierarchy
_KG_AVAILABLE = False
try:
@@ -736,6 +737,7 @@ class GraphSession:
def add_edges(self, edges: List[Dict[str, Any]]) -> int:
with self._lock:
+ self.validate_skos_hierarchy(edges)
added = self.graph.add_edges(edges)
has_mutation_callback = callable(getattr(self.graph, "mutation_callback", None))
if added and not has_mutation_callback:
@@ -744,6 +746,11 @@ class GraphSession:
self.rebuild_search_index()
return added
+ 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])
+
def add_node(
self,
node_id: str,
diff --git a/semantica/explorer/utils/skos.py b/semantica/explorer/utils/skos.py
new file mode 100644
index 00000000..35e6d8f9
--- /dev/null
+++ b/semantica/explorer/utils/skos.py
@@ -0,0 +1,57 @@
+"""Validation helpers for SKOS graph relationships."""
+
+from collections import defaultdict
+from typing import Iterable, Mapping
+
+
+_HIERARCHY_EDGE_TYPES = frozenset({"skos:broader", "skos:narrower"})
+
+
+def validate_skos_hierarchy(
+ edges: Iterable[Mapping[str, object]],
+) -> None:
+ """Raise ``ValueError`` when SKOS hierarchy edges contain a cycle.
+
+ ``skos:broader`` points from a concept to its parent while
+ ``skos:narrower`` expresses the same relationship in the opposite
+ direction. Both forms are normalized to a child-to-parent adjacency
+ map before cycle detection.
+ """
+
+ parents: dict[str, set[str]] = defaultdict(set)
+ for edge in edges:
+ edge_type = edge.get("type")
+ 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", "")))
+ if not source or not target:
+ continue
+
+ child, parent = (
+ (source, target)
+ if edge_type == "skos:broader"
+ else (target, source)
+ )
+ parents[child].add(parent)
+
+ visiting: set[str] = set()
+ visited: set[str] = set()
+
+ def visit(concept: str) -> None:
+ if concept in visiting:
+ raise ValueError(
+ f"SKOS hierarchy contains a cycle involving '{concept}'."
+ )
+ if concept in visited:
+ return
+
+ visiting.add(concept)
+ for parent in parents.get(concept, ()):
+ visit(parent)
+ visiting.remove(concept)
+ visited.add(concept)
+
+ for concept in parents:
+ visit(concept)
diff --git a/tests/explorer/test_vocabulary.py b/tests/explorer/test_vocabulary.py
index 7b91d17f..b148ac3c 100644
--- a/tests/explorer/test_vocabulary.py
+++ b/tests/explorer/test_vocabulary.py
@@ -7,6 +7,7 @@ from fastapi.testclient import TestClient
from semantica.explorer.dependencies import get_session
from semantica.explorer.routes.vocabulary import router
+from semantica.explorer.utils.skos import validate_skos_hierarchy
app = FastAPI()
app.include_router(router)
@@ -34,6 +35,15 @@ MINIMAL_RDF_XML = b"""<?xml version=\"1.0\"?>
"""
+CYCLIC_TTL = b"""
+@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 .
+"""
+
+
def setup_function():
mock_session.reset_mock()
@@ -158,3 +168,16 @@ def test_import_invalid_file_returns_422():
files={"file": ("bad.ttl", b"this is not valid RDF!", "text/turtle")},
)
assert response.status_code == 422
+
+
+def test_import_rejects_cyclic_hierarchy_before_writing_nodes():
+ mock_session.validate_skos_hierarchy.side_effect = lambda edges: validate_skos_hierarchy(edges)
+
+ response = client.post(
+ "/api/vocabulary/import",
+ files={"file": ("cyclic.ttl", CYCLIC_TTL, "text/turtle")},
+ )
+
+ assert response.status_code == 422
+ assert "cycle" in response.json()["detail"].lower()
+ mock_session.add_nodes.assert_not_called()