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(explorer): give PathFinder a traversable graph view for path routes (#1829)
Sakshi Jain7f980e6a73e6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 62bd238d..a289543d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- `semantica.kg.RelationalSchemaMapper` maps rows from a relational source (`DBIngestor`, `SnowflakeIngestor`, `DatabricksIngestor`, `PandasIngestor`, a DataFrame or plain row dicts) to the `{"entities", "relationships"}` shape `GraphBuilder` and `OntologyGenerator` consume: entity tables become entities keyed by primary key, foreign keys become typed relationships, junction tables become relationships only- Every entity and relationship is tagged with the `source` it came from so `ConflictDetector` can key credibility on it. New `tests/kg/test_schema_mapper.py`+### Fixed++- **Explorer path routes returned 404 for every node pair on a `ContextGraph` session** (fixes #1725) by @sakshi04-ui+ - `GET /api/graph/path`, `GET /api/graph/node/{id}/path` and `POST /api/graph/distance-matrix` handed `PathFinder` the `{"entities", "relationships"}` dict from `build_graph_dict`. `PathFinder` duck-types against `has_node`/`neighbors`/`get_edge_data`, so `"a" in graph_dict` tested the two top-level keys and raised `Source node a not found` — surfacing as a 404 on the path routes, and as every pair landing in `unreachable` on the distance matrix+ - Adds `GraphSession.build_nx_graph()`, a NetworkX view that preserves isolated nodes and carries edge `weight` through for `dijkstra_shortest_path`, and points the three `PathFinder` call sites at it. The `{"entities", "relationships"}` dict is still used for the edge-weight index and the centrality sub-graph, which consume that shape+ - The route tests previously patched `build_graph_dict` to return an `nx.DiGraph`, so the production shape was never exercised; the patch is removed and the existing bidirectional suite (#469) now runs against a real `ContextGraph`+ - `alternative_path_count` was always `0`: the enrichment called `find_k_shortest_paths(..., directed=directed)`, which takes no `directed` argument, so it raised `TypeError` into a DEBUG log. The undirected case now passes an undirected view instead. The 404 masked this until the routes started returning paths+ - `PathFinder` returns a plain list, never a dict, so the `isinstance(result, dict)` branches that read `total_weight` off it were dead: `total_weight` was `0.0` on every path response, and `POST /api/graph/distance-matrix` with `metric="weighted"` raised `AttributeError` into the same swallowing `except` and returned `null` for every pair. Both now sum edge weights along the resolved path+ - `POST /api/graph/distance-matrix` mirrored one `src`→`tgt` result into both matrix cells, reporting the reverse direction as reachable on a directed graph. Each direction is now searched independently, so the matrix may be asymmetric and `unreachable_pairs` lists the specific ordered pairs that have no path+ - Undirected traversal (`directed=false`) can walk a stored edge backwards; `total_weight` costed those hops against the directed view and fell back to the default `1.0`, and `resolve_path_edge_ids` scanned only outgoing adjacency so the hop contributed no id. Both now resolve reverse hops, and the reported edge is the lowest-weight parallel edge — the one the path is costed against+ - `POST /api/graph/distance-matrix` rebuilt the whole graph once per node pair; it is now built once per request+## [0.7.0] - 2026-09-22### Addeddiff --git a/semantica/explorer/routes/graph.py b/semantica/explorer/routes/graph.pyindex 222f2af5..26744b37 100644--- a/semantica/explorer/routes/graph.py+++ b/semantica/explorer/routes/graph.py@@ -6,7 +6,7 @@ import asyncioimport loggingimport timefrom enum import Enum-from typing import List, Optional+from typing import Any, List, Optionallogger = logging.getLogger(__name__)@@ -198,6 +198,18 @@ class _PathAlgorithm(str, Enum):dijkstra = "dijkstra"+def _path_weight(graph: Any, path_nodes: List[str]) -> float:+ """Sum edge weights along a resolved path.++ PathFinder returns a plain list of node ids, never a dict, so callers+ cannot read a ``total_weight`` off the result — they have to add the+ weights up from the graph they traversed (#1725).+ """+ total = 0.0+ for index in range(len(path_nodes) - 1):+ data = graph.get_edge_data(path_nodes[index], path_nodes[index + 1]) or {}+ total += float(data.get("weight", 1.0))+ return totalasync def _find_path_impl(@@ -212,14 +224,16 @@ async def _find_path_impl(if path_finder is None:raise HTTPException(status_code=503, detail="PathFinder not available; KG extras may not be installed.")- graph_dict = await asyncio.to_thread(session.build_graph_dict)+ # PathFinder cannot traverse the {"entities", "relationships"} dict that+ # build_graph_dict returns; it needs a NetworkX view (#1725).+ path_graph = await asyncio.to_thread(session.build_nx_graph)path_fn = (path_finder.dijkstra_shortest_pathif algorithm == _PathAlgorithm.dijkstraelse path_finder.bfs_shortest_path)try:- result = await asyncio.to_thread(path_fn, graph_dict, source, target, directed=directed)+ result = await asyncio.to_thread(path_fn, path_graph, source, target, directed=directed)except Exception as exc:raise HTTPException(status_code=404, detail=f"No path found from '{source}' to '{target}': {exc}")@@ -227,7 +241,16 @@ async def _find_path_impl(if not path_nodes:raise HTTPException(status_code=404, detail=f"No path found from '{source}' to '{target}'")- total_weight = result.get("total_weight", 0.0) if isinstance(result, dict) else 0.0+ # PathFinder traverses an undirected view when directed=False, so hops may+ # run against a stored edge's direction. Cost and enrich the path on that+ # same view or reverse hops miss and silently fall back to weight 1.0.+ traversal_graph = path_graph if directed else path_graph.to_undirected()++ total_weight = (+ result.get("total_weight", 0.0)+ if isinstance(result, dict)+ else _path_weight(traversal_graph, path_nodes)+ )edge_ids = await asyncio.to_thread(session.resolve_path_edge_ids, path_nodes)hop_count = len(path_nodes) - 1 if path_nodes else 0@@ -274,12 +297,15 @@ async def _find_path_impl(default=None,)- # Alternative paths — count simple paths within hop_count + 2+ # Alternative paths — fetch up to hop_count + 2 shortest paths (Yen's+ # k, a path count, not a hop-length bound) and discount the primary.if path_finder is not None and hop_count > 0:try:+ # find_k_shortest_paths takes no `directed` argument; the+ # undirected case is expressed by the view itself.k_paths = await asyncio.to_thread(path_finder.find_k_shortest_paths,- graph_dict, source, target, hop_count + 2, directed=directed+ traversal_graph, source, target, hop_count + 2)alternative_path_count = max(0, len(k_paths) - 1)except Exception as exc:@@ -442,6 +468,8 @@ async def distance_matrix(n = len(body.node_ids)matrix: List[List[Optional[float]]] = [[None] * n for _ in range(n)]unreachable: List[tuple] = []+ # Built at most once, lazily: the semantic metric never needs it.+ matrix_graph = Nonefor i in range(n):matrix[i][i] = 0.0@@ -472,20 +500,30 @@ async def distance_matrix(if body.metric == "weighted"else path_finder.bfs_shortest_path)- graph_dict = await asyncio.to_thread(session.build_graph_dict)- result = await asyncio.to_thread(path_fn, graph_dict, src, tgt)- path_nodes = result.get("path", []) if isinstance(result, dict) else (result or [])- if path_nodes:- val = (- float(result.get("total_weight", len(path_nodes) - 1))- if body.metric == "weighted"- else float(len(path_nodes) - 1)+ if matrix_graph is None:+ matrix_graph = await asyncio.to_thread(session.build_nx_graph)++ # The graph is directed, so src->tgt says nothing about+ # tgt->src; search each direction instead of mirroring one+ # result into both cells (#1725).+ for row, col, a, b in ((i, j, src, tgt), (j, i, tgt, src)):+ result = await asyncio.to_thread(path_fn, matrix_graph, a, b)+ path_nodes = (+ result.get("path", [])+ if isinstance(result, dict)+ else (result or []))- matrix[i][j] = val- matrix[j][i] = val- else:- unreachable.append((src, tgt))- unreachable.append((tgt, src))+ if not path_nodes:+ unreachable.append((a, b))+ continue+ if body.metric == "weighted":+ matrix[row][col] = (+ float(result.get("total_weight", len(path_nodes) - 1))+ if isinstance(result, dict)+ else _path_weight(matrix_graph, path_nodes)+ )+ else:+ matrix[row][col] = float(len(path_nodes) - 1)except Exception as exc:logger.debug("distance_matrix pair (%s, %s) failed: %s", src, tgt, exc)unreachable.append((src, tgt))diff --git a/semantica/explorer/session.py b/semantica/explorer/session.pyindex 43bfde58..9606d796 100644--- a/semantica/explorer/session.py+++ b/semantica/explorer/session.py@@ -11,6 +11,8 @@ import uuidfrom datetime import datetime, timezonefrom typing import Any, Dict, Iterable, Iterator, List, Optional+import networkx as nx+from ..context.context_graph import ContextGraph, _resolve_edge_identityfrom .search_index import GraphSearchIndexfrom ..utils.skos import is_skos_hierarchy_edge, validate_skos_hierarchy@@ -722,6 +724,44 @@ class GraphSession:self._cached_embeddings = Noneself._cached_graph_revision = -1+ def build_nx_graph(self) -> nx.DiGraph:+ """Build a NetworkX view of the session graph for PathFinder traversal.++ ``build_graph_dict`` returns the ``{"entities", "relationships"}`` shape+ that the KG analytics modules consume. ``PathFinder`` cannot traverse+ that shape — it duck-types against ``has_node``/``neighbors``/+ ``get_edge_data``, and needs ``to_undirected`` for ``directed=False``+ traversal — so path queries get this view instead (#1725).++ Isolated nodes are preserved, and edge ``weight`` is carried over so+ ``dijkstra_shortest_path`` sees real weights rather than defaults.+ """+ nodes, _ = self.get_nodes(skip=0, limit=999_999)+ edges, _ = self.get_edges(skip=0, limit=999_999)++ graph = nx.DiGraph()+ for node in nodes:+ node_id = node.get("id")+ if node_id is not None:+ graph.add_node(node_id)+ for edge in edges:+ source = edge.get("source")+ target = edge.get("target")+ if source is None or target is None:+ continue+ try:+ weight = float(edge.get("weight", 1.0))+ except (TypeError, ValueError):+ weight = 1.0+ # ContextGraph allows parallel edges between the same pair; a+ # DiGraph holds one. Keep the lowest weight so the collapse is+ # deterministic and matches how PathFinder reads weight (as cost).+ existing = graph.get_edge_data(source, target)+ if existing is not None:+ weight = min(weight, existing.get("weight", weight))+ graph.add_edge(source, target, weight=weight)+ return graph+def build_graph_dict(self, node_ids: Optional[list] = None) -> dict:nodes, _ = self.get_nodes(skip=0, limit=999_999)edges, _ = self.get_edges(skip=0, limit=999_999)@@ -772,11 +812,21 @@ class GraphSession:edge for edge in self.graph._adjacency.get(source_id, [])if edge.target_id == target_id]+ if not candidates:+ # An undirected traversal can walk a stored edge backwards,+ # so a hop with no outgoing edge may still have an incoming+ # one to report (#1725).+ candidates = [+ edge for edge in self.graph._adjacency.get(target_id, [])+ if edge.target_id == source_id+ ]if not candidates:continue+ # Lowest weight first, matching the edge build_nx_graph keeps+ # and therefore the one the path was actually costed against.candidates.sort(key=lambda edge: (- -float(edge.weight),+ float(edge.weight),str(edge.edge_type),str(edge.edge_id),)diff --git a/tests/explorer/test_explorer_api.py b/tests/explorer/test_explorer_api.pyindex 0c5cdcf1..dc8029f2 100644--- a/tests/explorer/test_explorer_api.py+++ b/tests/explorer/test_explorer_api.py@@ -5,7 +5,6 @@ import jsonfrom pathlib import Pathimport uuid-import networkx as nximport pytestfrom semantica.context.context_graph import ContextGraph@@ -1051,11 +1050,11 @@ class TestGenericGraphFileLoading:# ---------------------------------------------------------------------------def _make_path_session() -> GraphSession:- """Return a GraphSession whose build_graph_dict yields an nx.DiGraph with A→B only.+ """Return a GraphSession over a real ContextGraph with A→B only.- GraphSession wraps a ContextGraph (required by create_app), but we patch- build_graph_dict so PathFinder receives an actual NetworkX DiGraph — the- graph type the Explorer is designed to traverse for path queries.+ Nothing is patched: the routes build their own traversable view via+ ``GraphSession.build_nx_graph()``, so these tests exercise the production+ graph shape (#1725)."""cg = ContextGraph(advanced_analytics=False)cg.add_node("A", node_type="entity", content="Node A")@@ -1065,17 +1064,7 @@ def _make_path_session() -> GraphSession:cg.add_edge("A", "B", edge_type="connects")cg.add_edge("gene/protein:6164", "disease/term:1", edge_type="connects")- session = GraphSession(cg)-- # Patch build_graph_dict to return the directed NetworkX graph that- # PathFinder needs. The ContextGraph dict format is not traversable by- # PathFinder; this mimics how a KG-backed session would expose the graph.- digraph = nx.DiGraph()- digraph.add_edge("A", "B")- digraph.add_edge("gene/protein:6164", "disease/term:1")- session.build_graph_dict = lambda node_ids=None: digraph # type: ignore[method-assign]-- return session+ return GraphSession(cg)@pytest.fixture@@ -1212,6 +1201,277 @@ class TestBidirectionalPathRoute:from semantica.utils.helpers import classify_path_distance # noqa: E402+# ---------------------------------------------------------------------------+# Path routes over the production ContextGraph shape (issue #1725)+# ---------------------------------------------------------------------------++def _make_chain_session() -> GraphSession:+ """GraphSession over a real ContextGraph holding a → b → c."""+ graph = ContextGraph(advanced_analytics=False)+ for node_id in ("a", "b", "c"):+ graph.add_node(node_id, node_type="entity", content=f"Node {node_id}")+ graph.add_edge("a", "b", edge_type="related_to")+ graph.add_edge("b", "c", edge_type="related_to")+ return GraphSession(graph)+++def chain_client():+ app = create_app(session=_make_chain_session())+ with TestClient(app) as c:+ yield c+++class TestPathRoutesOnContextGraph:+ """A ContextGraph-backed session must be traversable by the path routes.++ Before #1725 every one of these returned 404 "Source node a not found",+ because the routes handed PathFinder the {"entities", "relationships"}+ dict from build_graph_dict, which it cannot traverse.+ """++ def test_query_route_finds_multi_hop_path(self, chain_client):+ resp = chain_client.get(+ "/api/graph/path", params={"source": "a", "target": "c"}+ )+ assert resp.status_code == 200+ assert resp.json()["path"] == ["a", "b", "c"]++ def test_node_route_finds_multi_hop_path(self, chain_client):+ resp = chain_client.get("/api/graph/node/a/path", params={"target": "c"})+ assert resp.status_code == 200+ assert resp.json()["path"] == ["a", "b", "c"]++ def test_dijkstra_finds_multi_hop_path(self, chain_client):+ resp = chain_client.get(+ "/api/graph/path",+ params={"source": "a", "target": "c", "algorithm": "dijkstra"},+ )+ assert resp.status_code == 200+ assert resp.json()["path"] == ["a", "b", "c"]++ def test_directed_traversal_still_rejects_reverse(self, chain_client):+ """The fix must not turn the graph undirected by accident."""+ resp = chain_client.get(+ "/api/graph/path", params={"source": "c", "target": "a"}+ )+ assert resp.status_code == 404++ def test_undirected_traversal_walks_edges_backwards(self, chain_client):+ resp = chain_client.get(+ "/api/graph/path",+ params={"source": "c", "target": "a", "directed": "false"},+ )+ assert resp.status_code == 200+ assert resp.json()["path"] == ["c", "b", "a"]++ def test_path_resolves_edge_ids_for_every_hop(self, chain_client):+ resp = chain_client.get(+ "/api/graph/path", params={"source": "a", "target": "c"}+ )+ assert resp.status_code == 200+ assert len(resp.json()["edge_ids"]) == 2++ def test_total_weight_sums_edge_weights(self):+ """PathFinder returns a list, so total_weight has to be summed from the+ graph; the dead isinstance(result, dict) branch left it at 0.0."""+ graph = ContextGraph(advanced_analytics=False)+ for node_id in ("a", "b", "c"):+ graph.add_node(node_id, node_type="entity", content=node_id)+ graph.add_edge("a", "b", edge_type="related_to", weight=2.0)+ graph.add_edge("b", "c", edge_type="related_to", weight=3.0)++ app = create_app(session=GraphSession(graph))+ with TestClient(app) as client:+ resp = client.get(+ "/api/graph/path",+ params={"source": "a", "target": "c", "algorithm": "dijkstra"},+ )++ assert resp.status_code == 200+ assert resp.json()["total_weight"] == 5.0++ def test_distance_matrix_weighted_metric_sums_weights(self):+ """The weighted metric called result.get() on a list and silently+ returned None for every pair."""+ graph = ContextGraph(advanced_analytics=False)+ for node_id in ("a", "b", "c"):+ graph.add_node(node_id, node_type="entity", content=node_id)+ graph.add_edge("a", "b", edge_type="related_to", weight=2.0)+ graph.add_edge("b", "c", edge_type="related_to", weight=3.0)++ app = create_app(session=GraphSession(graph))+ with TestClient(app) as client:+ resp = client.post(+ "/api/graph/distance-matrix",+ json={"node_ids": ["a", "b", "c"], "metric": "weighted"},+ )++ assert resp.status_code == 200+ assert resp.json()["matrix"] == [+ [0.0, 2.0, 5.0],+ [None, 0.0, 3.0],+ [None, None, 0.0],+ ]++ def test_alternative_paths_are_counted(self):+ """find_k_shortest_paths takes no `directed` kwarg; passing one made+ the enrichment raise TypeError and report 0 alternatives."""+ graph = ContextGraph(advanced_analytics=False)+ for node_id in ("a", "b", "c", "d"):+ graph.add_node(node_id, node_type="entity", content=node_id)+ graph.add_edge("a", "b", edge_type="related_to")+ graph.add_edge("b", "d", edge_type="related_to")+ graph.add_edge("a", "c", edge_type="related_to")+ graph.add_edge("c", "d", edge_type="related_to")++ app = create_app(session=GraphSession(graph))+ with TestClient(app) as client:+ resp = client.get(+ "/api/graph/path", params={"source": "a", "target": "d"}+ )++ assert resp.status_code == 200+ assert resp.json()["alternative_path_count"] == 1++ def _reverse_edge_session(self) -> GraphSession:+ """A single stored A -> B edge of weight 7.0."""+ graph = ContextGraph(advanced_analytics=False)+ graph.add_node("A", node_type="entity", content="A")+ graph.add_node("B", node_type="entity", content="B")+ graph.add_edge("A", "B", edge_type="related_to", weight=7.0)+ return GraphSession(graph)++ def test_undirected_reverse_hop_reports_the_stored_weight(self):+ """Costing a reverse hop on the directed view missed the edge and+ silently fell back to the 1.0 default."""+ app = create_app(session=self._reverse_edge_session())+ with TestClient(app) as client:+ resp = client.get(+ "/api/graph/path",+ params={"source": "B", "target": "A", "directed": "false"},+ )++ assert resp.status_code == 200+ assert resp.json()["total_weight"] == 7.0++ def test_undirected_reverse_hop_reports_its_edge_id(self):+ """resolve_path_edge_ids only scanned outgoing adjacency, so a+ backwards-traversed hop contributed no id."""+ app = create_app(session=self._reverse_edge_session())+ with TestClient(app) as client:+ resp = client.get(+ "/api/graph/path",+ params={"source": "B", "target": "A", "directed": "false"},+ )++ assert resp.status_code == 200+ assert len(resp.json()["edge_ids"]) == 1++ def test_distance_matrix_does_not_mirror_directed_results(self):+ """Only A -> B exists, so B -> A must not be reported as reachable."""+ app = create_app(session=self._reverse_edge_session())+ with TestClient(app) as client:+ resp = client.post(+ "/api/graph/distance-matrix",+ json={"node_ids": ["A", "B"], "metric": "hops"},+ )++ assert resp.status_code == 200+ body = resp.json()+ assert body["matrix"] == [[0.0, 1.0], [None, 0.0]]+ assert body["unreachable_pairs"] == [["B", "A"]]++ def test_reported_edge_id_matches_the_traversed_parallel_edge(self):+ """build_nx_graph keeps the lowest-weight parallel edge, so the+ reported id must be that edge, not the highest-weight one."""+ graph = ContextGraph(advanced_analytics=False)+ graph.add_node("x", node_type="entity", content="X")+ graph.add_node("y", node_type="entity", content="Y")+ graph.add_edge("x", "y", edge_type="expensive", weight=9.0)+ graph.add_edge("x", "y", edge_type="cheap", weight=1.0)+ session = GraphSession(graph)++ cheap_id = next(+ str(edge.edge_id)+ for edge in session.graph._adjacency["x"]+ if float(edge.weight) == 1.0+ )++ app = create_app(session=session)+ with TestClient(app) as client:+ resp = client.get(+ "/api/graph/path",+ params={"source": "x", "target": "y", "algorithm": "dijkstra"},+ )++ assert resp.status_code == 200+ body = resp.json()+ assert body["total_weight"] == 1.0+ assert body["edge_ids"] == [cheap_id]++ def test_parallel_edges_collapse_to_lowest_weight(self):+ """A DiGraph holds one edge per pair; the collapse must be deterministic."""+ graph = ContextGraph(advanced_analytics=False)+ graph.add_node("x", node_type="entity", content="X")+ graph.add_node("y", node_type="entity", content="Y")+ graph.add_edge("x", "y", edge_type="expensive", weight=9.0)+ graph.add_edge("x", "y", edge_type="cheap", weight=1.0)++ view = GraphSession(graph).build_nx_graph()++ assert view.get_edge_data("x", "y")["weight"] == 1.0++ def test_isolated_nodes_survive_the_graph_view(self):+ """A node with no edges must still be findable as a path endpoint."""+ graph = ContextGraph(advanced_analytics=False)+ graph.add_node("lonely", node_type="entity", content="Lonely")++ view = GraphSession(graph).build_nx_graph()++ assert "lonely" in view++ def test_distance_matrix_builds_the_graph_once(self, monkeypatch):+ """The graph view must be hoisted out of the O(n^2) pair loop."""+ session = _make_chain_session()+ calls = {"count": 0}+ real_build = session.build_nx_graph++ def _counting_build():+ calls["count"] += 1+ return real_build()++ monkeypatch.setattr(session, "build_nx_graph", _counting_build)++ app = create_app(session=session)+ with TestClient(app) as client:+ resp = client.post(+ "/api/graph/distance-matrix",+ json={"node_ids": ["a", "b", "c"], "metric": "hops"},+ )++ assert resp.status_code == 200+ assert calls["count"] == 1++ def test_distance_matrix_reports_hop_counts(self, chain_client):+ """distance-matrix shared the defect: every pair landed in unreachable."""+ resp = chain_client.post(+ "/api/graph/distance-matrix",+ json={"node_ids": ["a", "b", "c"], "metric": "hops"},+ )+ assert resp.status_code == 200+ body = resp.json()+ # The graph is directed: a reaches b and c, but nothing reaches a.+ assert body["matrix"] == [+ [0.0, 1.0, 2.0],+ [None, 0.0, 1.0],+ [None, None, 0.0],+ ]+ assert sorted(body["unreachable_pairs"]) == [+ ["b", "a"], ["c", "a"], ["c", "b"],+ ]++class _FakeSimilarity:"""Minimal similarity stub shared by slash-safe distance route tests.