Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(explorer): address PR #515 review findings

KaifAhmad1bb956b273599
diff --git a/semantica/explorer/routes/graph.py b/semantica/explorer/routes/graph.py
index 90ffe80f..018122f9 100644
--- a/semantica/explorer/routes/graph.py
+++ b/semantica/explorer/routes/graph.py
@@ -80,7 +80,9 @@ def _parse_bbox(raw_bbox: Optional[str]) -> Optional[tuple[float, float, float,
def _coerce_embedding_vector(value: object) -> Optional[List[float]]:
if isinstance(value, dict):
- for key in ("embedding", "vector", "values", "node2vec", "semantic"):
+ # Probe keys in priority order: generic first, then framework-specific.
+ # Must stay aligned with the top-level keys in _extract_node_embeddings.
+ for key in ("embedding", "embeddings", "vector", "values", "node2vec", "semantic"):
nested = _coerce_embedding_vector(value.get(key))
if nested is not None:
return nested
@@ -100,7 +102,10 @@ def _coerce_embedding_vector(value: object) -> Optional[List[float]]:
def _extract_node_embeddings(graph_dict: dict) -> dict[str, List[float]]:
- embeddings: dict[str, List[float]] = {}
+ # Top-level keys to probe on each entity (and its metadata/properties dicts).
+ # Priority: generic names first, then KG-extras-specific names.
+ # Must stay aligned with the inner probe list in _coerce_embedding_vector.
+ # TODO: cache this per-session graph revision to avoid re-scanning all nodes on every request.
embedding_keys = (
"embedding",
"embeddings",
@@ -111,6 +116,7 @@ def _extract_node_embeddings(graph_dict: dict) -> dict[str, List[float]]:
"reasoning_embedding",
)
+ embeddings: dict[str, List[float]] = {}
for entity in graph_dict.get("entities") or graph_dict.get("nodes") or []:
if not isinstance(entity, dict):
continue
@@ -393,6 +399,12 @@ async def find_path(
directed: bool = Query(True, description="If false, treat edges as undirected for traversal"),
session: GraphSession = Depends(get_session),
):
+ """Deprecated path-segment route kept for backward compatibility.
+
+ Node IDs that contain slashes will return 404 because FastAPI decodes
+ %2F before route matching. Use GET /api/graph/path?source=...&target=...
+ for slash-safe path lookup.
+ """
return await _find_path_impl(node_id, target, algorithm, directed, session)
@@ -611,6 +623,12 @@ async def semantic_neighborhood(
min_similarity: float = Query(0.0, ge=0.0, le=1.0),
session: GraphSession = Depends(get_session),
):
+ """Deprecated path-segment route kept for backward compatibility.
+
+ Node IDs that contain slashes will return 404 because FastAPI decodes
+ %2F before route matching. Use GET /api/graph/semantic-neighborhood?node_id=...
+ for slash-safe semantic neighborhood lookup.
+ """
return await _semantic_neighborhood_impl(node_id, top_k, min_similarity, session)
diff --git a/tests/explorer/test_explorer_api.py b/tests/explorer/test_explorer_api.py
index 7bca4caa..e402ad79 100644
--- a/tests/explorer/test_explorer_api.py
+++ b/tests/explorer/test_explorer_api.py
@@ -885,29 +885,39 @@ class TestBidirectionalPathRoute:
from semantica.utils.helpers import classify_path_distance
-class TestSlashSafeDistanceRoutes:
- class _FakeSimilarity:
- def find_most_similar(self, embeddings, query_embedding, top_k=10):
- assert "gene/protein:6164" in embeddings
- assert query_embedding == [1.0, 0.0, 0.0]
- return [("disease/term:1", 0.74)]
+class _FakeSimilarity:
+ """Minimal similarity stub shared by slash-safe distance route tests.
+
+ Expects embeddings keyed on 'gene/protein:6164' with query vector [1, 0, 0]
+ and returns a single neighbor result. Tests that need different behaviour
+ can assign a lambda to instance.find_most_similar after construction.
+ """
+
+ def find_most_similar(self, embeddings, query_embedding, top_k=10):
+ assert "gene/protein:6164" in embeddings
+ assert query_embedding == [1.0, 0.0, 0.0]
+ return [("disease/term:1", 0.74)]
+
+
+def _make_slash_node_session(*, with_embeddings: bool = True) -> GraphSession:
+ """Return an isolated GraphSession with slash-containing node IDs."""
+ graph = ContextGraph(advanced_analytics=False)
+ kwargs = {"embedding": [1.0, 0.0, 0.0]} if with_embeddings else {}
+ graph.add_node("gene/protein:6164", node_type="gene/protein", content="RPL34", **kwargs)
+ graph.add_node(
+ "disease/term:1",
+ node_type="disease",
+ content="Slash target",
+ **({"embedding": [0.7, 0.2, 0.1]} if with_embeddings else {}),
+ )
+ session = GraphSession(graph)
+ session._similarity = _FakeSimilarity()
+ return session
+
+class TestSlashSafeDistanceRoutes:
def test_query_semantic_neighborhood_supports_slash_node_ids(self):
- graph = ContextGraph(advanced_analytics=False)
- graph.add_node(
- "gene/protein:6164",
- node_type="gene/protein",
- content="RPL34",
- embedding=[1.0, 0.0, 0.0],
- )
- graph.add_node(
- "disease/term:1",
- node_type="disease",
- content="Slash target",
- embedding=[0.7, 0.2, 0.1],
- )
- session = GraphSession(graph)
- session._similarity = self._FakeSimilarity()
+ session = _make_slash_node_session(with_embeddings=True)
app = create_app(session=session)
with TestClient(app) as test_client:
resp = test_client.get(
@@ -921,24 +931,33 @@ class TestSlashSafeDistanceRoutes:
assert body["neighbors"][0]["id"] == "disease/term:1"
assert body["neighbors"][0]["similarity"] == 0.74
- def test_legacy_semantic_neighborhood_still_works_for_simple_ids(self, client):
- client.app.state.session.graph.add_node(
+ def test_legacy_semantic_neighborhood_still_works_for_simple_ids(self):
+ """Legacy path-segment route must still return 200 for slash-free node IDs."""
+ graph = ContextGraph(advanced_analytics=False)
+ graph.add_node(
"semantic_anchor",
node_type="entity",
content="Semantic anchor",
- embedding=[1.0, 0.0],
+ embedding=[1.0, 0.0, 0.0],
)
- client.app.state.session.graph.add_node(
+ graph.add_node(
"semantic_neighbor",
node_type="entity",
content="Semantic neighbor",
- embedding=[0.8, 0.2],
+ embedding=[0.8, 0.2, 0.0],
)
- client.app.state.session._similarity = self._FakeSimilarity()
- client.app.state.session._similarity.find_most_similar = (
+ session = GraphSession(graph)
+ fake = _FakeSimilarity()
+ fake.find_most_similar = (
lambda embeddings, query_embedding, top_k=10: [("semantic_neighbor", 0.8)]
)
- resp = client.get("/api/graph/node/semantic_anchor/semantic-neighborhood?top_k=10")
+ session._similarity = fake
+ app = create_app(session=session)
+ with TestClient(app) as test_client:
+ resp = test_client.get(
+ "/api/graph/node/semantic_anchor/semantic-neighborhood?top_k=10"
+ )
+
assert resp.status_code == 200
assert resp.json()["anchor_node"] == "semantic_anchor"
@@ -950,10 +969,7 @@ class TestSlashSafeDistanceRoutes:
assert resp.status_code == 404
def test_query_semantic_neighborhood_without_embeddings_returns_503(self):
- graph = ContextGraph(advanced_analytics=False)
- graph.add_node("gene/protein:6164", node_type="gene/protein", content="RPL34")
- session = GraphSession(graph)
- session._similarity = self._FakeSimilarity()
+ session = _make_slash_node_session(with_embeddings=False)
app = create_app(session=session)
with TestClient(app) as test_client:
resp = test_client.get(