Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(explorer): resolve all PR review issues — bugs, tests, refactor

KaifAhmad188bd7d6b058a
diff --git a/pyproject.toml b/pyproject.toml
index 1e03d95f..1c0f4181 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -213,7 +213,7 @@ explorer-lite = [
# Everything
all = [
- "semantica[dev,viz,gpu,infra,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all,vectorstore-all,parse-docling,explorer]"
+ "semantica[dev,viz,gpu,infra,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all,vectorstore-all,parse-docling,explorer]",
"semantica[dev,viz,gpu,infra,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all,vectorstore-all,parse-docling,agno]"
]
diff --git a/semantica/explorer/app.py b/semantica/explorer/app.py
index 1082d38a..0d189165 100644
--- a/semantica/explorer/app.py
+++ b/semantica/explorer/app.py
@@ -6,12 +6,11 @@ static file serving, route registration, and WebSocket support.
"""
import os
-import traceback
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
-from fastapi import FastAPI, Request
+from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
@@ -32,12 +31,10 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:
@asynccontextmanager
async def lifespan(app: FastAPI):
-
if session is not None:
app.state.session = session
app.state.ws_manager = ConnectionManager()
yield
-
app = FastAPI(
title="Semantica Knowledge Explorer",
@@ -46,7 +43,6 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:
lifespan=lifespan,
)
-
cors_origins = os.environ.get("EXPLORER_CORS_ORIGINS", "*")
app.add_middleware(
CORSMiddleware,
@@ -56,7 +52,6 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:
allow_headers=["*"],
)
-
@app.exception_handler(KeyError)
async def key_error_handler(request: Request, exc: KeyError):
return JSONResponse(
@@ -73,6 +68,11 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:
@app.exception_handler(Exception)
async def generic_error_handler(request: Request, exc: Exception):
+ # Let FastAPI's built-in HTTPException handler take precedence so that
+ # responses from dependency injection (e.g. 503 from get_session) are
+ # not swallowed and converted to 500.
+ if isinstance(exc, HTTPException):
+ raise exc
return JSONResponse(
status_code=500,
content={"detail": "Internal Server Error"},
@@ -94,7 +94,6 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:
app.include_router(export_import_router)
app.include_router(annotations_router)
-
from fastapi import WebSocket, WebSocketDisconnect
@app.websocket("/ws/graph-updates")
@@ -103,12 +102,10 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:
await manager.connect(websocket)
try:
while True:
-
await websocket.receive_text()
except WebSocketDisconnect:
manager.disconnect(websocket)
-
@app.get("/api/health")
async def health():
return {"status": "healthy"}
@@ -121,7 +118,6 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:
"status": "active",
}
-
static_dir = Path(__file__).resolve().parent.parent / "static"
static_dir.mkdir(parents=True, exist_ok=True)
from fastapi.staticfiles import StaticFiles
diff --git a/semantica/explorer/routes/analytics.py b/semantica/explorer/routes/analytics.py
index dc7c584e..92917a4e 100644
--- a/semantica/explorer/routes/analytics.py
+++ b/semantica/explorer/routes/analytics.py
@@ -14,24 +14,6 @@ from ..session import GraphSession
router = APIRouter(prefix="/api/analytics", tags=["Analytics"])
-def _build_graph_dict(session: GraphSession) -> dict:
- """Build the entity/relationship dict expected by KG analysers."""
- nodes, _ = session.get_nodes(skip=0, limit=999_999)
- edges, _ = session.get_edges(skip=0, limit=999_999)
- return {
- "entities": [
- {"id": n.get("id"), "type": n.get("type", "entity"),
- "text": n.get("content", n.get("id", "")), "metadata": n.get("metadata", {})}
- for n in nodes
- ],
- "relationships": [
- {"source": e.get("source"), "target": e.get("target"),
- "type": e.get("type", "related_to"), "metadata": e.get("metadata", {})}
- for e in edges
- ],
- }
-
-
@router.get("", response_model=AnalyticsResponse)
async def get_analytics(
metrics: Optional[str] = Query(
@@ -42,7 +24,7 @@ async def get_analytics(
):
"""Compute graph analytics (centrality, community, connectivity)."""
requested = set((metrics or "centrality,community,connectivity").split(","))
- graph_dict = await asyncio.to_thread(_build_graph_dict, session)
+ graph_dict = await asyncio.to_thread(session.build_graph_dict)
result: dict = {}
if "centrality" in requested and session.centrality is not None:
@@ -84,7 +66,7 @@ async def validate_graph(
if validator is None:
return ValidationReportResponse(valid=True, error_count=0, warning_count=0, issues=[])
- graph_dict = await asyncio.to_thread(_build_graph_dict, session)
+ graph_dict = await asyncio.to_thread(session.build_graph_dict)
try:
report = await asyncio.to_thread(validator.validate, graph_dict)
@@ -95,7 +77,6 @@ async def validate_graph(
issues=[ValidationIssue(severity="error", message=str(exc))],
)
-
if isinstance(report, dict):
valid = report.get("valid", True)
errors = report.get("errors", [])
diff --git a/semantica/explorer/routes/annotations.py b/semantica/explorer/routes/annotations.py
index 35dd2a30..c189a89f 100644
--- a/semantica/explorer/routes/annotations.py
+++ b/semantica/explorer/routes/annotations.py
@@ -38,21 +38,9 @@ async def create_annotation(
raise KeyError(body.node_id)
ann_data = body.model_dump()
- ann_id = await asyncio.to_thread(session.add_annotation, ann_data)
-
-
- anns = await asyncio.to_thread(session.get_annotations)
- for a in anns:
- if a.get("annotation_id") == ann_id:
- return AnnotationResponse(**a)
-
- return AnnotationResponse(
- annotation_id=ann_id,
- node_id=body.node_id,
- content=body.content,
- tags=body.tags,
- visibility=body.visibility,
- )
+ # add_annotation mutates ann_data in-place, adding annotation_id and created_at.
+ await asyncio.to_thread(session.add_annotation, ann_data)
+ return AnnotationResponse(**ann_data)
@router.delete("/{annotation_id}", status_code=204)
diff --git a/semantica/explorer/routes/decisions.py b/semantica/explorer/routes/decisions.py
index 7d502d5c..71c9b0a6 100644
--- a/semantica/explorer/routes/decisions.py
+++ b/semantica/explorer/routes/decisions.py
@@ -149,20 +149,34 @@ async def check_compliance(
"""
Check policy compliance for a decision.
- Returns a stub result when no PolicyEngine is wired up.
+ Inspects edges of type ``violates``, ``non_compliant``, or ``breaches``
+ originating from the decision node. Returns ``compliant=True`` when no
+ such edges are found, which is the correct result for graphs that have
+ no policy-violation edges defined.
"""
node = await asyncio.to_thread(session.get_node, decision_id)
if node is None:
raise KeyError(decision_id)
+ edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)
- try:
- from ...context.policy_engine import PolicyEngine
- except ImportError:
- pass
+ _VIOLATION_TYPES = {"violates", "non_compliant", "breaches"}
+ violation_edges = [
+ e for e in edges
+ if e.get("source") == decision_id and e.get("type") in _VIOLATION_TYPES
+ ]
+
+ violations = [
+ {
+ "policy_id": e.get("target"),
+ "type": e.get("type"),
+ "metadata": e.get("metadata", {}),
+ }
+ for e in violation_edges
+ ]
return ComplianceResponse(
decision_id=decision_id,
- compliant=True,
- violations=[],
+ compliant=len(violations) == 0,
+ violations=violations,
)
diff --git a/semantica/explorer/routes/enrich.py b/semantica/explorer/routes/enrich.py
index 854c9870..91fff7ca 100644
--- a/semantica/explorer/routes/enrich.py
+++ b/semantica/explorer/routes/enrich.py
@@ -65,29 +65,43 @@ async def predict_links(
if node is None:
raise KeyError(body.node_id)
- # Build graph dict
+ # Get all nodes and edges to build candidate pairs manually,
+ # because ContextGraph.nodes is a dict (not callable) and is incompatible
+ # with LinkPredictor._get_all_nodes which requires nodes() or get_all_nodes().
nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)
edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)
- graph_dict = {
- "entities": [{"id": n.get("id"), "type": n.get("type", "entity")} for n in nodes],
- "relationships": [
- {"source": e.get("source"), "target": e.get("target"),
- "type": e.get("type", "related_to")}
- for e in edges
- ],
+
+ # Pre-compute already-connected node IDs so we skip them.
+ # (LinkPredictor._edge_exists returns False for ContextGraph since it has no
+ # has_edge/get_edge method, so we handle exclusion here instead.)
+ existing_neighbours = {
+ e.get("target") for e in edges if e.get("source") == body.node_id
+ } | {
+ e.get("source") for e in edges if e.get("target") == body.node_id
}
- try:
- predictions = await asyncio.to_thread(
- predictor.predict_links, graph_dict, body.node_id, top_n=body.top_n
- )
- pred_list = predictions if isinstance(predictions, list) else []
- return LinkPredictionResponse(
- node_id=body.node_id,
- predictions=[_safe_dict(p) for p in pred_list],
- )
- except Exception as exc:
- raise ValueError(f"Link prediction failed: {exc}")
+ # Score each candidate via score_link (which works with ContextGraph because
+ # it falls back to has_node / get_neighbors).
+ scored = []
+ for n in nodes:
+ candidate = n.get("id")
+ if not candidate or candidate == body.node_id or candidate in existing_neighbours:
+ continue
+ try:
+ score = predictor.score_link(session.graph, body.node_id, candidate)
+ if score > 0:
+ scored.append(
+ {"target": candidate, "score": score, "type": n.get("type", "entity")}
+ )
+ except Exception:
+ continue
+
+ scored.sort(key=lambda x: x["score"], reverse=True)
+
+ return LinkPredictionResponse(
+ node_id=body.node_id,
+ predictions=scored[: body.top_n],
+ )
@router.post("/api/enrich/dedup", response_model=DedupResponse)
@@ -100,11 +114,16 @@ async def detect_duplicates(
from ...deduplication import DuplicateDetector
detector = DuplicateDetector()
- nodes, _ = session.get_nodes(skip=0, limit=999_999)
+ # Use asyncio.to_thread — get_nodes acquires an RLock and must not block
+ # the event loop.
+ nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)
entities = [
- {"id": n.get("id"), "text": n.get("content", n.get("id", "")),
- "type": n.get("type", "entity")}
+ {
+ "id": n.get("id"),
+ "text": n.get("content", n.get("id", "")),
+ "type": n.get("type", "entity"),
+ }
for n in nodes
]
@@ -146,7 +165,6 @@ async def run_reasoning(
raise ValueError(f"Reasoning failed: {exc}")
-
def _safe_dict(obj) -> dict:
"""Convert an object to a JSON-safe dict."""
if isinstance(obj, dict):
diff --git a/semantica/explorer/routes/export_import.py b/semantica/explorer/routes/export_import.py
index 7b2e3e35..11062275 100644
--- a/semantica/explorer/routes/export_import.py
+++ b/semantica/explorer/routes/export_import.py
@@ -3,8 +3,8 @@ Export & import routes.
"""
import asyncio
-import io
import json
+import os
import tempfile
from typing import Optional
@@ -35,39 +35,6 @@ _FORMAT_MAP = {
}
-def _build_kg_dict(session: GraphSession, node_ids: Optional[list] = None) -> dict:
- """Build the knowledge-graph dict that exporters expect."""
- nodes, _ = session.get_nodes(skip=0, limit=999_999)
- edges, _ = session.get_edges(skip=0, limit=999_999)
-
- if node_ids:
- id_set = set(node_ids)
- nodes = [n for n in nodes if n.get("id") in id_set]
- edges = [
- e for e in edges
- if e.get("source") in id_set and e.get("target") in id_set
- ]
-
- return {
- "entities": [
- {
- "id": n.get("id"),
- "type": n.get("type", "entity"),
- "text": n.get("content", n.get("id", "")),
- "metadata": n.get("metadata", {}),
- }
- for n in nodes
- ],
- "relationships": [
- {
- "source": e.get("source"),
- "target": e.get("target"),
- "type": e.get("type", "related_to"),
- "metadata": e.get("metadata", {}),
- }
- for e in edges
- ],
- }
@router.post("/api/export")
@@ -84,8 +51,7 @@ async def export_graph(
func_name, content_type, ext = _FORMAT_MAP[fmt]
- kg = await asyncio.to_thread(_build_kg_dict, session, body.node_ids)
-
+ kg = await asyncio.to_thread(session.build_graph_dict, body.node_ids)
try:
from ...export.methods import (
@@ -106,20 +72,21 @@ async def export_graph(
if export_fn is None:
raise ValueError(f"Export function {func_name} not found.")
- # Write to a temp file, read back content.
- with tempfile.NamedTemporaryFile(suffix=ext, delete=False, mode="w") as tmp:
- tmp_path = tmp.name
-
- await asyncio.to_thread(export_fn, kg, tmp_path)
+ # Write to a temp file; always clean up even if export or read fails.
+ tmp_path = None
+ try:
+ with tempfile.NamedTemporaryFile(suffix=ext, delete=False, mode="w") as tmp:
+ tmp_path = tmp.name
- with open(tmp_path, "r", encoding="utf-8", errors="replace") as fh:
- content = fh.read()
+ await asyncio.to_thread(export_fn, kg, tmp_path)
- import os
- os.unlink(tmp_path)
+ with open(tmp_path, "r", encoding="utf-8", errors="replace") as fh:
+ content = fh.read()
+ finally:
+ if tmp_path and os.path.exists(tmp_path):
+ os.unlink(tmp_path)
except ImportError:
-
content = json.dumps(kg, indent=2, default=str)
content_type = "application/json"
ext = ".json"
diff --git a/semantica/explorer/routes/graph.py b/semantica/explorer/routes/graph.py
index 3b6a0a77..468e9712 100644
--- a/semantica/explorer/routes/graph.py
+++ b/semantica/explorer/routes/graph.py
@@ -138,13 +138,17 @@ async def find_path(
if pf is None:
raise ValueError("PathFinder not available — KG extras may not be installed.")
- graph_data = await asyncio.to_thread(_build_graph_dict, session)
+ graph_data = await asyncio.to_thread(session.build_graph_dict)
- result = await asyncio.to_thread(
- pf.find_shortest_path, graph_data, node_id, target
- )
+ # Select algorithm: dijkstra for weighted shortest path, bfs otherwise.
+ if algorithm.lower() == "dijkstra":
+ path_fn = pf.dijkstra_shortest_path
+ else:
+ path_fn = pf.bfs_shortest_path
+
+ result = await asyncio.to_thread(path_fn, graph_data, node_id, target)
- path_nodes = result.get("path", []) if isinstance(result, dict) else []
+ path_nodes = result.get("path", []) if isinstance(result, dict) else (result or [])
total_weight = result.get("total_weight", 0.0) if isinstance(result, dict) else 0.0
return PathResponse(
@@ -185,27 +189,3 @@ async def graph_stats(
-def _build_graph_dict(session: GraphSession) -> dict:
- """Build a graph dict for analytics helpers (entities + relationships)."""
- nodes, _ = session.get_nodes(skip=0, limit=999_999)
- edges, _ = session.get_edges(skip=0, limit=999_999)
- return {
- "entities": [
- {
- "id": n.get("id"),
- "type": n.get("type", "entity"),
- "text": n.get("content", n.get("id", "")),
- "metadata": n.get("metadata", {}),
- }
- for n in nodes
- ],
- "relationships": [
- {
- "source": e.get("source"),
- "target": e.get("target"),
- "type": e.get("type", "related_to"),
- "metadata": e.get("metadata", {}),
- }
- for e in edges
- ],
- }
diff --git a/semantica/explorer/routes/temporal.py b/semantica/explorer/routes/temporal.py
index 300e124d..d0ac0149 100644
--- a/semantica/explorer/routes/temporal.py
+++ b/semantica/explorer/routes/temporal.py
@@ -121,5 +121,10 @@ async def temporal_patterns(
if isinstance(patterns, dict):
patterns = patterns.get("patterns", [])
return TemporalPatternResponse(patterns=patterns if isinstance(patterns, list) else [])
- except Exception:
+ except ImportError:
+ # TemporalPatternDetector is an optional KG extra; return empty gracefully.
+ return TemporalPatternResponse(patterns=[])
+ except Exception as exc:
+ import logging
+ logging.getLogger(__name__).warning("temporal_patterns failed: %s", exc, exc_info=True)
return TemporalPatternResponse(patterns=[])
diff --git a/semantica/explorer/session.py b/semantica/explorer/session.py
index 61262bb1..191442d9 100644
--- a/semantica/explorer/session.py
+++ b/semantica/explorer/session.py
@@ -36,17 +36,16 @@ class GraphSession:
Thread safety: all mutations to the graph or the annotations store
must go through methods on this class, which are protected by an
- ``RLock``.
+ ``RLock``. Lazy analytics properties are also initialised under the
+ same lock to prevent double-instantiation under concurrent requests.
"""
def __init__(self, graph: ContextGraph) -> None:
self.graph = graph
self._lock = threading.RLock()
-
self.annotations: Dict[str, Dict[str, Any]] = {}
-
self._centrality: Any = None
self._community: Any = None
self._connectivity: Any = None
@@ -56,7 +55,6 @@ class GraphSession:
self._link_predictor: Any = None
self._validator: Any = None
-
@classmethod
def from_file(cls, path: str) -> "GraphSession":
"""Load a ContextGraph from a JSON file and wrap it in a session."""
@@ -64,55 +62,69 @@ class GraphSession:
graph.load_from_file(path)
return cls(graph)
+ # ------------------------------------------------------------------
+ # Lazy analytics properties (thread-safe double-checked locking)
+ # ------------------------------------------------------------------
@property
def centrality(self) -> Any:
- if self._centrality is None and _KG_AVAILABLE:
- self._centrality = CentralityCalculator()
- return self._centrality
+ with self._lock:
+ if self._centrality is None and _KG_AVAILABLE:
+ self._centrality = CentralityCalculator()
+ return self._centrality
@property
def community(self) -> Any:
- if self._community is None and _KG_AVAILABLE:
- self._community = CommunityDetector()
- return self._community
+ with self._lock:
+ if self._community is None and _KG_AVAILABLE:
+ self._community = CommunityDetector()
+ return self._community
@property
def connectivity(self) -> Any:
- if self._connectivity is None and _KG_AVAILABLE:
- self._connectivity = ConnectivityAnalyzer()
- return self._connectivity
+ with self._lock:
+ if self._connectivity is None and _KG_AVAILABLE:
+ self._connectivity = ConnectivityAnalyzer()
+ return self._connectivity
@property
def path_finder(self) -> Any:
- if self._path_finder is None and _KG_AVAILABLE:
- self._path_finder = PathFinder()
- return self._path_finder
+ with self._lock:
+ if self._path_finder is None and _KG_AVAILABLE:
+ self._path_finder = PathFinder()
+ return self._path_finder
@property
def node_embedder(self) -> Any:
- if self._node_embedder is None and _KG_AVAILABLE:
- self._node_embedder = NodeEmbedder()
- return self._node_embedder
+ with self._lock:
+ if self._node_embedder is None and _KG_AVAILABLE:
+ self._node_embedder = NodeEmbedder()
+ return self._node_embedder
@property
def similarity(self) -> Any:
- if self._similarity is None and _KG_AVAILABLE:
- self._similarity = SimilarityCalculator()
- return self._similarity
+ with self._lock:
+ if self._similarity is None and _KG_AVAILABLE:
+ self._similarity = SimilarityCalculator()
+ return self._similarity
@property
def link_predictor(self) -> Any:
- if self._link_predictor is None and _KG_AVAILABLE:
- self._link_predictor = LinkPredictor()
- return self._link_predictor
+ with self._lock:
+ if self._link_predictor is None and _KG_AVAILABLE:
+ self._link_predictor = LinkPredictor()
+ return self._link_predictor
@property
def validator(self) -> Any:
- if self._validator is None and _KG_AVAILABLE:
- self._validator = GraphValidator()
- return self._validator
+ with self._lock:
+ if self._validator is None and _KG_AVAILABLE:
+ self._validator = GraphValidator()
+ return self._validator
+ # ------------------------------------------------------------------
+ # Graph read helpers
+ # ------------------------------------------------------------------
def get_node(self, node_id: str) -> Optional[Dict[str, Any]]:
"""Get a single node by ID, or ``None``."""
@@ -187,9 +199,12 @@ class GraphSession:
with self._lock:
return self.graph.find_active_nodes(node_type=node_type, at_time=at_time)
+ # ------------------------------------------------------------------
+ # Annotation CRUD
+ # ------------------------------------------------------------------
def add_annotation(self, annotation: Dict[str, Any]) -> str:
- """Add an annotation and return its ID."""
+ """Add an annotation (mutates the dict in-place) and return its ID."""
ann_id = str(uuid.uuid4())
annotation["annotation_id"] = ann_id
annotation["created_at"] = datetime.utcnow().isoformat()
@@ -210,6 +225,51 @@ class GraphSession:
with self._lock:
return self.annotations.pop(annotation_id, None) is not None
+ def build_graph_dict(self, node_ids: Optional[list] = None) -> dict:
+ """
+ Build the ``{entities, relationships}`` dict consumed by KG analytics
+ helpers, exporters, and path-finders.
+
+ Args:
+ node_ids: Optional list of node IDs to include. When given, only
+ nodes in the list and edges between them are returned.
+ """
+ nodes, _ = self.get_nodes(skip=0, limit=999_999)
+ edges, _ = self.get_edges(skip=0, limit=999_999)
+
+ if node_ids:
+ id_set = set(node_ids)
+ nodes = [n for n in nodes if n.get("id") in id_set]
+ edges = [
+ e for e in edges
+ if e.get("source") in id_set and e.get("target") in id_set
+ ]
+
+ return {
+ "entities": [
+ {
+ "id": n.get("id"),
+ "type": n.get("type", "entity"),
+ "text": n.get("content", n.get("id", "")),
+ "metadata": n.get("metadata", {}),
+ }
+ for n in nodes
+ ],
+ "relationships": [
+ {
+ "source": e.get("source"),
+ "target": e.get("target"),
+ "type": e.get("type", "related_to"),
+ "metadata": e.get("metadata", {}),
+ }
+ for e in edges
+ ],
+ }
+
+ # ------------------------------------------------------------------
+ # Graph mutation helpers
+ # ------------------------------------------------------------------
+
def add_nodes(self, nodes: List[Dict[str, Any]]) -> int:
"""Thread-safe node addition."""
with self._lock:
diff --git a/tests/explorer/test_explorer_api.py b/tests/explorer/test_explorer_api.py
index e47f9661..d8047a0d 100644
--- a/tests/explorer/test_explorer_api.py
+++ b/tests/explorer/test_explorer_api.py
@@ -22,7 +22,6 @@ except ImportError:
)
-
def _build_sample_graph() -> ContextGraph:
"""Create a small ContextGraph with a handful of nodes and edges."""
g = ContextGraph(advanced_analytics=False)
@@ -59,6 +58,9 @@ def client():
yield c
+# ---------------------------------------------------------------------------
+# Health & Info
+# ---------------------------------------------------------------------------
class TestHealthInfo:
def test_health(self, client):
@@ -72,8 +74,12 @@ class TestHealthInfo:
body = r.json()
assert body["name"] == "Semantica Knowledge Explorer"
assert "version" in body
+ assert body["status"] == "active"
+# ---------------------------------------------------------------------------
+# Graph — Nodes
+# ---------------------------------------------------------------------------
class TestGraphNodes:
def test_list_nodes(self, client):
@@ -82,6 +88,7 @@ class TestGraphNodes:
body = r.json()
assert body["total"] >= 5
assert len(body["nodes"]) <= body["total"]
+ assert "skip" in body and "limit" in body
def test_list_nodes_pagination(self, client):
r = client.get("/api/graph/nodes?skip=0&limit=2")
@@ -94,6 +101,7 @@ class TestGraphNodes:
r = client.get("/api/graph/nodes?type=language")
assert r.status_code == 200
body = r.json()
+ assert body["total"] >= 2
assert all(n["type"] == "language" for n in body["nodes"])
def test_list_nodes_search(self, client):
@@ -101,6 +109,8 @@ class TestGraphNodes:
assert r.status_code == 200
body = r.json()
assert body["total"] >= 1
+ assert any("python" in n["id"].lower() or "python" in n["content"].lower()
+ for n in body["nodes"])
def test_get_node(self, client):
r = client.get("/api/graph/node/python")
@@ -108,6 +118,7 @@ class TestGraphNodes:
body = r.json()
assert body["id"] == "python"
assert body["type"] == "language"
+ assert "content" in body
def test_get_node_not_found(self, client):
r = client.get("/api/graph/node/nonexistent_xyz")
@@ -121,9 +132,19 @@ class TestGraphNodes:
assert len(body) >= 1
ids = [nb["id"] for nb in body]
assert "ml" in ids or "web_dev" in ids
+ # Each neighbour must have required fields
+ for nb in body:
+ assert "id" in nb and "type" in nb and "hop" in nb
+ def test_get_neighbors_depth(self, client):
+ r = client.get("/api/graph/node/python/neighbors?depth=2")
+ assert r.status_code == 200
+ assert isinstance(r.json(), list)
+# ---------------------------------------------------------------------------
+# Graph — Edges
+# ---------------------------------------------------------------------------
class TestGraphEdges:
def test_list_edges(self, client):
@@ -131,21 +152,33 @@ class TestGraphEdges:
assert r.status_code == 200
body = r.json()
assert body["total"] >= 3
+ assert all("source" in e and "target" in e and "type" in e
+ for e in body["edges"])
def test_list_edges_filter_type(self, client):
r = client.get("/api/graph/edges?type=used_in")
assert r.status_code == 200
body = r.json()
+ assert len(body["edges"]) >= 1
assert all(e["type"] == "used_in" for e in body["edges"])
def test_list_edges_filter_source(self, client):
r = client.get("/api/graph/edges?source=python")
assert r.status_code == 200
body = r.json()
+ assert len(body["edges"]) >= 1
assert all(e["source"] == "python" for e in body["edges"])
+ def test_list_edges_filter_target(self, client):
+ r = client.get("/api/graph/edges?target=ml")
+ assert r.status_code == 200
+ body = r.json()
+ assert all(e["target"] == "ml" for e in body["edges"])
+# ---------------------------------------------------------------------------
+# Search & Stats
+# ---------------------------------------------------------------------------
class TestSearchStats:
def test_search(self, client):
@@ -154,6 +187,15 @@ class TestSearchStats:
body = r.json()
assert body["query"] == "programming"
assert len(body["results"]) >= 1
+ # Each result must carry a node and a score
+ for item in body["results"]:
+ assert "node" in item and "score" in item
+ assert item["node"]["id"] # non-empty id
+
+ def test_search_no_results(self, client):
+ r = client.post("/api/graph/search", json={"query": "zzznomatchzzz"})
+ assert r.status_code == 200
+ assert r.json()["total"] == 0
def test_stats(self, client):
r = client.get("/api/graph/stats")
@@ -162,7 +204,13 @@ class TestSearchStats:
assert body["node_count"] >= 5
assert body["edge_count"] >= 3
assert "density" in body
+ assert "node_types" in body and "edge_types" in body
+ assert body["density"] >= 0.0
+
+# ---------------------------------------------------------------------------
+# Decisions
+# ---------------------------------------------------------------------------
class TestDecisions:
def test_list_decisions(self, client):
@@ -171,17 +219,22 @@ class TestDecisions:
body = r.json()
assert isinstance(body, list)
assert len(body) >= 1
+ for d in body:
+ assert "decision_id" in d and "category" in d
def test_list_decisions_category(self, client):
r = client.get("/api/decisions?category=tech")
assert r.status_code == 200
body = r.json()
+ assert len(body) >= 1
assert all(d["category"] == "tech" for d in body)
def test_get_decision(self, client):
r = client.get("/api/decisions/decision_1")
assert r.status_code == 200
- assert r.json()["decision_id"] == "decision_1"
+ body = r.json()
+ assert body["decision_id"] == "decision_1"
+ assert body["outcome"] == "approved"
def test_get_decision_not_found(self, client):
r = client.get("/api/decisions/nope")
@@ -197,16 +250,43 @@ class TestDecisions:
def test_precedents(self, client):
r = client.get("/api/decisions/decision_1/precedents")
assert r.status_code == 200
- assert isinstance(r.json(), list)
+ body = r.json()
+ assert isinstance(body, list)
+ # decision_2 shares category "tech" so should appear
+ ids = [d["decision_id"] for d in body]
+ assert "decision_2" in ids
+
+ def test_compliance_no_violations(self, client):
+ """Graph has no violation edges so compliance must be True."""
+ r = client.get("/api/decisions/decision_1/compliance")
+ assert r.status_code == 200
+ body = r.json()
+ assert "compliant" in body and "violations" in body
+ assert body["compliant"] is True
+ assert isinstance(body["violations"], list)
+
+ def test_compliance_with_violation(self, client):
+ """Add a violation edge then check compliance detects it."""
+ # Add a policy node and a violates edge directly on the underlying graph
+ session = GraphSession(client.app.state.session.graph)
+ session.graph.add_node("policy_1", node_type="policy", content="Data policy")
+ session.graph.add_edge("decision_1", "policy_1", edge_type="violates")
- def test_compliance(self, client):
r = client.get("/api/decisions/decision_1/compliance")
assert r.status_code == 200
body = r.json()
- assert "compliant" in body
+ assert body["compliant"] is False
+ assert len(body["violations"]) >= 1
+ assert body["violations"][0]["policy_id"] == "policy_1"
+ # Clean up — remove the test edge so other tests are not affected
+ # (ContextGraph doesn't expose edge removal; re-create the session fixture
+ # to isolate: this test intentionally runs after all other decision tests)
+# ---------------------------------------------------------------------------
+# Temporal
+# ---------------------------------------------------------------------------
class TestTemporal:
def test_snapshot_now(self, client):
@@ -214,14 +294,23 @@ class TestTemporal:
assert r.status_code == 200
body = r.json()
assert "active_node_count" in body
+ assert "timestamp" in body
+ assert isinstance(body["active_nodes"], list)
- def test_snapshot_at(self, client):
+ def test_snapshot_at_includes_temporal_node(self, client):
r = client.get("/api/temporal/snapshot?at=2025-06-15T00:00:00")
assert r.status_code == 200
body = r.json()
ids = [n["id"] for n in body["active_nodes"]]
assert "temporal_node" in ids
+ def test_snapshot_at_excludes_temporal_node(self, client):
+ r = client.get("/api/temporal/snapshot?at=2026-01-01T00:00:00")
+ assert r.status_code == 200
+ body = r.json()
+ ids = [n["id"] for n in body["active_nodes"]]
+ assert "temporal_node" not in ids
+
def test_diff(self, client):
r = client.get(
"/api/temporal/diff"
@@ -230,27 +319,53 @@ class TestTemporal:
)
assert r.status_code == 200
body = r.json()
- assert "added_nodes" in body
- assert "removed_nodes" in body
+ assert "added_nodes" in body and "removed_nodes" in body
+ # temporal_node became active between t1 and t2
+ assert "temporal_node" in body["added_nodes"]
+ def test_patterns(self, client):
+ r = client.get("/api/temporal/patterns")
+ assert r.status_code == 200
+ body = r.json()
+ assert "patterns" in body
+ assert isinstance(body["patterns"], list)
+# ---------------------------------------------------------------------------
+# Analytics
+# ---------------------------------------------------------------------------
class TestAnalytics:
- def test_analytics(self, client):
+ def test_analytics_response_shape(self, client):
r = client.get("/api/analytics")
assert r.status_code == 200
+ body = r.json()
+ # At least one analytics key must be present (or all None when KG extras absent)
+ assert set(body.keys()) >= {"centrality", "community", "connectivity"} or \
+ all(v is None for v in body.values())
+
+ def test_analytics_select_metric(self, client):
+ r = client.get("/api/analytics?metrics=centrality")
+ assert r.status_code == 200
+ # When KG extras are absent the key is still present but None; otherwise a dict
+ body = r.json()
+ assert "centrality" in body
def test_validation(self, client):
r = client.get("/api/analytics/validation")
assert r.status_code == 200
body = r.json()
assert "valid" in body
+ assert "error_count" in body and "warning_count" in body
+ assert isinstance(body["issues"], list)
+# ---------------------------------------------------------------------------
+# Reasoning
+# ---------------------------------------------------------------------------
class TestReasoning:
- def test_reason(self, client):
+ def test_reason_forward(self, client):
r = client.post(
"/api/reason",
json={
@@ -259,14 +374,107 @@ class TestReasoning:
"mode": "forward",
},
)
+ # 200 when reasoning module is available; 422 when it's not installed.
+ # Either is acceptable — the endpoint must not 500.
+ assert r.status_code in (200, 422), (
+ f"Unexpected status {r.status_code}: {r.text}"
+ )
+ if r.status_code == 200:
+ body = r.json()
+ assert "inferred_facts" in body
+ assert "rules_fired" in body
+ assert isinstance(body["inferred_facts"], list)
+ assert isinstance(body["rules_fired"], int)
+
+ def test_reason_empty_rules(self, client):
+ r = client.post(
+ "/api/reason",
+ json={"facts": ["Person(Alice)"], "rules": [], "mode": "forward"},
+ )
assert r.status_code in (200, 422)
+ if r.status_code == 200:
+ assert r.json()["rules_fired"] == 0
+# ---------------------------------------------------------------------------
+# Enrichment — Extract
+# ---------------------------------------------------------------------------
+class TestEnrichExtract:
+ def test_extract_returns_structure(self, client):
+ r = client.post(
+ "/api/enrich/extract",
+ json={"text": "Alice works at Acme Corp in New York."},
+ )
+ # 200 when spacy/transformers available; 422 otherwise
+ assert r.status_code in (200, 422), (
+ f"Unexpected status {r.status_code}: {r.text}"
+ )
+ if r.status_code == 200:
+ body = r.json()
+ assert "entities" in body and "relations" in body
+ assert isinstance(body["entities"], list)
+ assert isinstance(body["relations"], list)
+
+ def test_extract_empty_text(self, client):
+ r = client.post("/api/enrich/extract", json={"text": ""})
+ assert r.status_code in (200, 422)
+
+
+# ---------------------------------------------------------------------------
+# Enrichment — Link Prediction
+# ---------------------------------------------------------------------------
+
+class TestLinkPrediction:
+ def test_predict_links_known_node(self, client):
+ r = client.post(
+ "/api/enrich/links",
+ json={"node_id": "python", "top_n": 5},
+ )
+ # 200 when KG extras available; 422 otherwise
+ assert r.status_code in (200, 422), (
+ f"Unexpected status {r.status_code}: {r.text}"
+ )
+ if r.status_code == 200:
+ body = r.json()
+ assert body["node_id"] == "python"
+ assert isinstance(body["predictions"], list)
+ # Must not include existing neighbours
+ neighbour_ids = {"ml", "web_dev"}
+ for pred in body["predictions"]:
+ assert pred.get("target") not in neighbour_ids
+
+ def test_predict_links_unknown_node(self, client):
+ r = client.post(
+ "/api/enrich/links",
+ json={"node_id": "does_not_exist", "top_n": 5},
+ )
+ assert r.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Enrichment — Deduplication
+# ---------------------------------------------------------------------------
+
+class TestDedup:
+ def test_dedup_returns_structure(self, client):
+ r = client.post("/api/enrich/dedup", json={"threshold": 0.8})
+ assert r.status_code in (200, 422), (
+ f"Unexpected status {r.status_code}: {r.text}"
+ )
+ if r.status_code == 200:
+ body = r.json()
+ assert "duplicates" in body and "total_flagged" in body
+ assert isinstance(body["duplicates"], list)
+ assert body["total_flagged"] == len(body["duplicates"])
+
+
+# ---------------------------------------------------------------------------
+# Annotations
+# ---------------------------------------------------------------------------
class TestAnnotations:
def test_create_and_list(self, client):
-
r = client.post(
"/api/annotations",
json={"node_id": "python", "content": "Great language!", "tags": ["fav"]},
@@ -274,6 +482,9 @@ class TestAnnotations:
assert r.status_code == 201
ann = r.json()
assert ann["node_id"] == "python"
+ assert ann["content"] == "Great language!"
+ assert "annotation_id" in ann and ann["annotation_id"]
+ assert "created_at" in ann
ann_id = ann["annotation_id"]
# List all
@@ -290,6 +501,10 @@ class TestAnnotations:
r = client.delete(f"/api/annotations/{ann_id}")
assert r.status_code == 204
+ # Verify gone
+ r = client.get("/api/annotations")
+ assert all(a["annotation_id"] != ann_id for a in r.json())
+
def test_create_annotation_bad_node(self, client):
r = client.post(
"/api/annotations",
@@ -302,19 +517,36 @@ class TestAnnotations:
assert r.status_code == 404
+# ---------------------------------------------------------------------------
+# Export
+# ---------------------------------------------------------------------------
class TestExport:
def test_export_json(self, client):
r = client.post("/api/export", json={"format": "json"})
assert r.status_code == 200
- assert "json" in r.headers.get("content-type", "").lower() or len(r.content) > 0
+ ct = r.headers.get("content-type", "")
+ assert "json" in ct.lower()
+ # Payload must be valid JSON with entities and relationships
+ data = r.json()
+ assert "entities" in data and "relationships" in data
+ assert len(data["entities"]) >= 5
+
+ def test_export_json_subset(self, client):
+ r = client.post("/api/export", json={"format": "json", "node_ids": ["python", "ml"]})
+ assert r.status_code == 200
+ data = r.json()
+ ids = [e["id"] for e in data["entities"]]
+ assert set(ids) == {"python", "ml"}
def test_export_unsupported(self, client):
r = client.post("/api/export", json={"format": "pdf"})
assert r.status_code == 422
-
+# ---------------------------------------------------------------------------
+# Import
+# ---------------------------------------------------------------------------
class TestImport:
def test_import_json(self, client):
@@ -333,5 +565,34 @@ class TestImport:
assert body["status"] == "success"
assert body["nodes_added"] >= 1
+ # Verify the node is now in the graph
r2 = client.get("/api/graph/node/imported_node")
assert r2.status_code == 200
+ assert r2.json()["id"] == "imported_node"
+
+ def test_import_with_edges(self, client):
+ payload = json.dumps({
+ "nodes": [
+ {"id": "import_src", "type": "test", "properties": {"content": "src"}},
+ {"id": "import_tgt", "type": "test", "properties": {"content": "tgt"}},
+ ],
+ "edges": [
+ {"source": "import_src", "target": "import_tgt", "type": "links_to"}
+ ],
+ })
+ r = client.post(
+ "/api/import",
+ files={"file": ("import2.json", payload, "application/json")},
+ )
+ assert r.status_code == 200
+ body = r.json()
+ assert body["status"] == "success"
+ assert body["nodes_added"] >= 2
+
+ def test_import_unsupported_format(self, client):
+ r = client.post(
+ "/api/import",
+ files={"file": ("data.csv", b"a,b,c", "text/csv")},
+ )
+ assert r.status_code == 200
+ assert r.json()["status"] == "unsupported"