Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(kg): build the PageRank adjacency once for a graph dict, not per node (#1844)

Younes Berianef87998d5c4fc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a289543d..a8bdc686 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **`calculate_pagerank` rebuilt the adjacency once per node for a plain graph dictionary** (fixes #1842)
+ - `_get_filtered_neighbors` called `build_adjacency(graph, directed=True)` for every node, making neighbour resolution O(N * (N + E)). `calculate_pagerank` now builds it once before the node loop and passes it in through a new optional `adjacency` argument; scores are unchanged. New `tests/kg/test_centrality_pagerank_adjacency_reuse.py`
+
- **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
diff --git a/semantica/kg/centrality_calculator.py b/semantica/kg/centrality_calculator.py
index a8e15569..387195ca 100644
--- a/semantica/kg/centrality_calculator.py
+++ b/semantica/kg/centrality_calculator.py
@@ -655,9 +655,19 @@ class CentralityCalculator:
data = []
has_outgoing = np.zeros(n, dtype=bool)
+ # A plain graph dictionary has its adjacency built once for the
+ # whole loop rather than once per node.
+ adjacency = (
+ build_adjacency(graph, directed=True)
+ if isinstance(graph, dict)
+ else None
+ )
+
for node in nodes:
source_idx = node_index[node]
- neighbors = self._get_filtered_neighbors(graph, node, relationship_types)
+ neighbors = self._get_filtered_neighbors(
+ graph, node, relationship_types, adjacency=adjacency
+ )
# Distribute PageRank equally among the neighbours that survive
# the node filter. Counting the filtered-out ones too would send
@@ -738,14 +748,21 @@ class CentralityCalculator:
self,
graph: Any,
node: str,
- relationship_types: Optional[List[str]]
+ relationship_types: Optional[List[str]],
+ adjacency: Optional[Dict[str, List[str]]] = None,
) -> List[str]:
- """Get neighbors filtered by relationship types."""
+ """Get neighbors filtered by relationship types.
+
+ ``adjacency`` is an optional prebuilt outgoing adjacency for a plain
+ graph dictionary, so a caller looping over nodes builds it once.
+ """
if isinstance(graph, dict):
# A plain graph dictionary has no neighbour walk of its own, so the
# outgoing adjacency comes from the same dict-aware builder the rest
# of the analytics use.
- neighbors = build_adjacency(graph, directed=True).get(node, [])
+ if adjacency is None:
+ adjacency = build_adjacency(graph, directed=True)
+ neighbors = adjacency.get(node, [])
elif hasattr(graph, 'neighbors'):
_raw = list(graph.neighbors(node))
neighbors = [n.get("id") if isinstance(n, dict) else n for n in _raw]
diff --git a/tests/kg/test_centrality_pagerank_adjacency_reuse.py b/tests/kg/test_centrality_pagerank_adjacency_reuse.py
new file mode 100644
index 00000000..5237912b
--- /dev/null
+++ b/tests/kg/test_centrality_pagerank_adjacency_reuse.py
@@ -0,0 +1,46 @@
+"""PageRank on a plain graph dictionary builds the adjacency once, not per node.
+
+``_get_filtered_neighbors`` called ``build_adjacency(graph, directed=True)`` for
+every node, so neighbour resolution cost O(N * (N + E)) instead of O(N + E).
+"""
+
+from semantica.kg import CentralityCalculator, centrality_calculator
+
+
+def _graph_dict(n=30):
+ return {
+ "entities": [{"id": f"n{i}", "type": "thing"} for i in range(n)],
+ "relationships": [
+ {"source": f"n{i}", "target": f"n{(i + 1) % n}", "type": "next"}
+ for i in range(n)
+ ],
+ }
+
+
+def test_pagerank_builds_the_adjacency_once_for_a_graph_dict(monkeypatch):
+ calls = []
+ real = centrality_calculator.build_adjacency
+
+ def counting(graph, directed=False):
+ calls.append(directed)
+ return real(graph, directed=directed)
+
+ monkeypatch.setattr(centrality_calculator, "build_adjacency", counting)
+
+ CentralityCalculator().calculate_pagerank(_graph_dict())
+
+ assert len(calls) == 1
+
+
+def test_pagerank_scores_are_unchanged_by_adjacency_reuse():
+ graph = _graph_dict(5)
+ graph["relationships"].append({"source": "n0", "target": "n2", "type": "skip"})
+
+ plain = CentralityCalculator().calculate_pagerank(graph)["centrality"]
+ typed = CentralityCalculator().calculate_pagerank(
+ graph, relationship_types=["next"]
+ )["centrality"]
+
+ assert abs(sum(plain.values()) - 1.0) < 1e-6
+ assert plain["n2"] > plain["n3"]
+ assert set(typed) == set(plain)