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(kg): make PageRank node-label and relationship filtering work with ContextGraph (#1758)
Kevinf87266ce27cc
diff --git a/semantica/kg/_graph_view.py b/semantica/kg/_graph_view.pyindex f467125b..675285b0 100644--- a/semantica/kg/_graph_view.py+++ b/semantica/kg/_graph_view.py@@ -172,6 +172,37 @@ def _edge_endpoints(edge: Any) -> Optional[Tuple[Any, Any]]:return source, target+def _edge_type_of(edge: Any) -> Any:+ """Read an edge's relationship type from a mapping or an object."""+ if isinstance(edge, dict):+ return _first_value(+ edge, "type", "edge_type", "relationship_type", "relationship"+ )+ return _first_attribute(+ edge, "edge_type", "type", "relationship_type", "relationship"+ )+++def _dict_edge_types(+ graph: Dict[str, Any], source: Any, target: Any, directed: bool+) -> Set[Any]:+ """Collect the types of every declared edge between two nodes."""+ types: Set[Any] = set()+ for edge in _extract_edges(graph):+ endpoints = _edge_endpoints(edge)+ if endpoints is None:+ continue+ src, dst = endpoints+ forwards = src == source and dst == target+ backwards = src == target and dst == source+ if not (forwards or (backwards and not directed)):+ continue+ edge_type = _edge_type_of(edge)+ if edge_type:+ types.add(edge_type)+ return types++def _node_id(value: Any) -> Any:if isinstance(value, dict):value = _first_value(@@ -204,3 +235,120 @@ def _first_attribute(value: Any, *names: str) -> Any:if attribute not in (None, ""):return attributereturn None+++def _label_of(node_data: Any) -> Optional[str]:+ """Read a node label from a mapping entry or a node object."""+ if isinstance(node_data, dict):+ return _first_value(node_data, "label", "type", "node_type")+ return _first_attribute(node_data, "node_type", "label", "type")+++def _dict_node_label(graph: Dict[str, Any], node: Any) -> Optional[str]:+ """Read a node's label out of a plain graph dictionary."""+ mapping = graph.get("nodes")+ if isinstance(mapping, dict) and node in mapping:+ return _label_of(mapping[node])++ for value in _extract_nodes(graph):+ if _node_id(value) == node:+ return _label_of(value)+ return None+++def graph_node_ids(graph: Any) -> List[Any]:+ """Return the node ids of any supported graph.++ NetworkX exposes ``nodes`` as a callable view, while+ :class:`~semantica.context.context_graph.ContextGraph` exposes it as a+ mapping keyed by node id. A plain ``{"entities": [...], "relationships":+ [...]}`` mapping declares its nodes under ``entities``/``nodes`` instead, so+ it is read through the same view builder the rest of the analytics use.+ """+ if isinstance(graph, dict):+ return list(build_graph_view(graph).nodes)++ nodes = getattr(graph, "nodes", None)+ if nodes is None:+ return []+ if callable(nodes):+ return list(nodes())+ return list(nodes)+++def graph_node_label(graph: Any, node: Any) -> Optional[str]:+ """Read a node's label from either a mapping or an object.++ NetworkX stores node attributes in a dict, while ``ContextGraph`` stores a+ :class:`~semantica.context.context_graph.ContextNode` dataclass whose label+ is ``node_type``. A plain graph dictionary keeps its entities under+ ``entities``/``nodes``, so the label comes from the matching entry.+ """+ if isinstance(graph, dict):+ return _dict_node_label(graph, node)++ return _label_of(graph.nodes[node])+++def edge_types_between(+ graph: Any, source: Any, target: Any, directed: bool = False+) -> Optional[Set[Any]]:+ """Collect the relationship types of every edge between two nodes.++ Returns ``None`` when the graph exposes no edge types at all, because a+ caller cannot classify a link it has no metadata for. An empty set means the+ two nodes are joined by edges that declare no type. Callers keep the+ neighbour on ``None`` and apply the filter to a set. A plain graph+ dictionary is read through its ``relationships``/``edges`` entries.++ ``directed`` narrows the edge-list lookup to edges that leave ``source`` and+ enter ``target``. The default reads the pair as undirected, which is what a+ community detector wants; a caller walking an outgoing adjacency list has to+ pass ``directed=True``, or a reverse edge of another type reads as a match.+ The NetworkX lookup further down is keyed by the direction it is called with+ already, so the flag changes nothing there.++ ``ContextGraph`` keeps parallel edges and its ``get_edge_data()`` returns+ only the first one, so the edge list is the only view that shows them all.+ NetworkX returns plain attributes for a simple graph and a key-to-attributes+ mapping for a multigraph.+ """+ if isinstance(graph, dict):+ return _dict_edge_types(graph, source, target, directed)++ edges = getattr(graph, "edges", None)+ if isinstance(edges, (list, tuple)) and any(+ hasattr(edge, "source_id") for edge in edges+ ):+ types: Set[Any] = set()+ for edge in edges:+ src = getattr(edge, "source_id", None)+ dst = getattr(edge, "target_id", None)+ forwards = src == source and dst == target+ backwards = src == target and dst == source+ if forwards or (backwards and not directed):+ edge_type = getattr(edge, "edge_type", None)+ if edge_type:+ types.add(edge_type)+ return types++ if hasattr(graph, "get_edge_data"):+ data = graph.get_edge_data(source, target)+ if not isinstance(data, dict) or not data:+ return set()+ is_multigraph = getattr(graph, "is_multigraph", None)+ if callable(is_multigraph) and is_multigraph():+ candidates = data.values()+ else:+ candidates = [data]+ types = set()+ for attributes in candidates:+ if isinstance(attributes, dict):+ edge_type = attributes.get("type") or attributes.get(+ "relationship"+ )+ if edge_type:+ types.add(edge_type)+ return types++ return Nonediff --git a/semantica/kg/centrality_calculator.py b/semantica/kg/centrality_calculator.pyindex 3e4bc9f1..39fbc049 100644--- a/semantica/kg/centrality_calculator.py+++ b/semantica/kg/centrality_calculator.py@@ -51,7 +51,13 @@ from scipy import sparsefrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker-from ._graph_view import build_adjacency, build_graph_view+from ._graph_view import (+ build_adjacency,+ build_graph_view,+ edge_types_between,+ graph_node_ids,+ graph_node_label,+)class CentralityCalculator:@@ -599,7 +605,8 @@ class CentralityCalculator:a page to determine a rough estimate of how important the website is.Args:- graph: Graph object (NetworkX or similar)+ graph: Graph object (NetworkX, ContextGraph, or a plain+ ``{"entities": [...], "relationships": [...]}`` mapping)node_labels: List of node labels to include (None for all)relationship_types: List of relationship types to consider (None for all)max_iterations: Maximum number of iterations for convergence@@ -622,15 +629,10 @@ class CentralityCalculator:try:self.logger.info("Calculating PageRank scores")- # ContextGraph.nodes is a dict rather than a NetworkX NodeView,- # so an attribute presence test would skip the conversion and the- # node filter below would then call that dict.- needs_conversion = not callable(getattr(graph, "nodes", None))- if needs_conversion and hasattr(self, "_to_networkx"):- try:- graph = self._to_networkx(graph)- except Exception:- pass+ # No conversion here. _to_networkx re-adds nodes by id alone, so+ # converting first would strip every label and every relationship+ # type the filters below need. The _graph_view helpers read a+ # ContextGraph and a plain graph dictionary directly instead.# Filter nodes by labels if specifiednodes = self._filter_nodes_by_labels(graph, node_labels)@@ -698,21 +700,16 @@ class CentralityCalculator:def _filter_nodes_by_labels(self, graph: Any, node_labels: Optional[List[str]]) -> List[str]:"""Filter nodes by specified labels."""+ nodes = graph_node_ids(graph)+if node_labels is None:- return list(graph.nodes()) if hasattr(graph, 'nodes') else []-+ return nodes+filtered_nodes = []- for node in graph.nodes():- if hasattr(graph, 'nodes'):- node_data = graph.nodes[node]- if isinstance(node_data, dict):- node_label = node_data.get('label') or node_data.get('type')- if node_label in node_labels:- filtered_nodes.append(node)- else:- # Fallback - include all nodes if no label information- filtered_nodes.append(node)-+ for node in nodes:+ if graph_node_label(graph, node) in node_labels:+ filtered_nodes.append(node)+return filtered_nodesdef _get_filtered_neighbors(@@ -722,7 +719,12 @@ class CentralityCalculator:relationship_types: Optional[List[str]]) -> List[str]:"""Get neighbors filtered by relationship types."""- if hasattr(graph, 'neighbors'):+ 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, [])+ elif hasattr(graph, 'neighbors'):_raw = list(graph.neighbors(node))neighbors = [n.get("id") if isinstance(n, dict) else n for n in _raw]elif hasattr(graph, 'get_neighbors'):@@ -735,15 +737,19 @@ class CentralityCalculator:else:neighbors = []- # Filter by relationship types if specified- if relationship_types is not None and hasattr(graph, 'get_edge_data'):- filtered_neighbors = []- for neighbor in neighbors:- edge_data = graph.get_edge_data(node, neighbor)- if edge_data and isinstance(edge_data, dict):- edge_type = edge_data.get('type') or edge_data.get('relationship')- if edge_type in relationship_types:- filtered_neighbors.append(neighbor)- return filtered_neighbors-- return neighbors+ if relationship_types is None:+ return neighbors++ # Filter by relationship types if specified. The edge list is the only+ # view that shows every parallel edge of a pair, and a graph whose edge+ # types cannot be read keeps its neighbours rather than dropping them.+ # The neighbours come from an outgoing walk, so the lookup has to read+ # the edges in that direction: a reverse edge of another type is not a+ # link this node follows, and counting it flattens the ranking.+ wanted = set(relationship_types)+ filtered_neighbors = []+ for neighbor in neighbors:+ types = edge_types_between(graph, node, neighbor, directed=True)+ if types is None or types & wanted:+ filtered_neighbors.append(neighbor)+ return filtered_neighborsdiff --git a/semantica/kg/community_detector.py b/semantica/kg/community_detector.pyindex 9adab85d..92707e41 100644--- a/semantica/kg/community_detector.py+++ b/semantica/kg/community_detector.py@@ -49,7 +49,13 @@ from typing import Any, Dict, List, Optionalfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker-from ._graph_view import build_adjacency, build_graph_view+from ._graph_view import (+ build_adjacency,+ build_graph_view,+ edge_types_between,+ graph_node_ids,+ graph_node_label,+)def _is_hashable(value: Any) -> bool:@@ -844,97 +850,18 @@ class CommunityDetector:def _filter_nodes_by_labels(self, graph: Any, node_labels: Optional[List[str]]) -> List[str]:"""Filter nodes by specified labels."""- nodes = self._graph_node_ids(graph)+ nodes = graph_node_ids(graph)if node_labels is None:return nodesfiltered_nodes = []for node in nodes:- node_label = self._node_label(graph, node)- if node_label in node_labels:+ if graph_node_label(graph, node) in node_labels:filtered_nodes.append(node)return filtered_nodes- @staticmethod- def _graph_node_ids(graph: Any) -> List[str]:- """Return node ids for any supported graph.-- NetworkX exposes ``nodes`` as a callable view, while- :class:`~semantica.context.context_graph.ContextGraph` exposes it as a- mapping keyed by node id.- """- nodes = getattr(graph, "nodes", None)- if nodes is None:- return []- if callable(nodes):- return list(nodes())- return list(nodes)-- @staticmethod- def _node_label(graph: Any, node: str) -> Optional[str]:- """Read a node's label from either a mapping or an object.-- NetworkX stores node attributes in a dict, while ``ContextGraph``- stores a :class:`~semantica.context.context_graph.ContextNode` dataclass- whose label is ``node_type``.- """- node_data = graph.nodes[node]- if isinstance(node_data, dict):- return node_data.get("label") or node_data.get("type")- for attribute in ("node_type", "label", "type"):- label = getattr(node_data, attribute, None)- if label:- return label- return None-- @staticmethod- def _edge_types_between(graph: Any, source: str, target: str) -> set:- """Collect the relationship types of every edge between two nodes.-- ``ContextGraph`` keeps parallel edges and its ``get_edge_data()``- returns only the first one, so the edge list is the only view that- shows them all. NetworkX returns plain attributes for a simple graph- and a key-to-attributes mapping for a multigraph.- """- edges = getattr(graph, "edges", None)- if isinstance(edges, (list, tuple)) and any(- hasattr(edge, "source_id") for edge in edges- ):- types = set()- for edge in edges:- src = getattr(edge, "source_id", None)- dst = getattr(edge, "target_id", None)- if (src == source and dst == target) or (- src == target and dst == source- ):- edge_type = getattr(edge, "edge_type", None)- if edge_type:- types.add(edge_type)- return types-- if hasattr(graph, "get_edge_data"):- data = graph.get_edge_data(source, target)- if not isinstance(data, dict) or not data:- return set()- is_multigraph = getattr(graph, "is_multigraph", None)- if callable(is_multigraph) and is_multigraph():- candidates = data.values()- else:- candidates = [data]- types = set()- for attributes in candidates:- if isinstance(attributes, dict):- edge_type = attributes.get("type") or attributes.get(- "relationship"- )- if edge_type:- types.add(edge_type)- return types-- return set()-def _build_filtered_adjacency(self,graph: Any,@@ -960,12 +887,15 @@ class CommunityDetector:if isinstance(n, dict) and n.get("id")]- # Filter by relationship types if specified+ # Filter by relationship types if specified. A graph whose edge+ # types cannot be read keeps its neighbours, so the filter never+ # turns an unclassifiable link into a silent removal.if relationship_types is not None and hasattr(graph, 'get_edge_data'):wanted = set(relationship_types)for neighbor in all_neighbors:if neighbor in nodes: # Only include filtered nodes- if self._edge_types_between(graph, node, neighbor) & wanted:+ types = edge_types_between(graph, node, neighbor)+ if types is None or types & wanted:neighbors.append(neighbor)else:# Include all neighbors that are in the filtered node setdiff --git a/tests/kg/test_centrality_pagerank_node_labels.py b/tests/kg/test_centrality_pagerank_node_labels.pynew file mode 100644index 00000000..9b668dad--- /dev/null+++ b/tests/kg/test_centrality_pagerank_node_labels.py@@ -0,0 +1,254 @@+"""Regression tests for PageRank node-label filtering on a ContextGraph.++``CentralityCalculator._filter_nodes_by_labels`` called ``graph.nodes()``, the+NetworkX shape, so a ``ContextGraph`` — whose ``nodes`` is a mapping — raised+``TypeError: 'dict' object is not callable``. Fixing the call alone was not+enough: the filter also expected ``graph.nodes[node]`` to be an attribute dict,+while a ContextGraph stores a ``ContextNode`` dataclass, and its fallback branch+then included every node instead of filtering by ``node_type``.+"""++import networkx as nx+import pytest++from semantica.context.context_graph import ContextGraph+from semantica.kg import CentralityCalculator+++def _context_graph():+ graph = ContextGraph()+ graph.add_node("alice", "person", "Alice")+ graph.add_node("bob", "person", "Bob")+ graph.add_node("acme", "organization", "Acme")+ graph.add_edge("alice", "bob", "knows")+ graph.add_edge("bob", "acme", "works_at")+ return graph+++def test_pagerank_runs_on_a_context_graph():+ result = CentralityCalculator().calculate_pagerank(_context_graph())++ assert set(result["centrality"]) == {"alice", "bob", "acme"}+++def test_node_labels_restrict_the_context_graph_calculation():+ result = CentralityCalculator().calculate_pagerank(+ _context_graph(), node_labels=["person"]+ )++ assert set(result["centrality"]) == {"alice", "bob"}+++def test_node_labels_pick_the_other_type_too():+ result = CentralityCalculator().calculate_pagerank(+ _context_graph(), node_labels=["organization"]+ )++ assert set(result["centrality"]) == {"acme"}+++def test_unmatched_node_labels_raise():+ with pytest.raises(RuntimeError, match="No nodes found matching"):+ CentralityCalculator().calculate_pagerank(+ _context_graph(), node_labels=["nowhere"]+ )+++def test_filter_reads_context_node_types():+ nodes = CentralityCalculator()._filter_nodes_by_labels(_context_graph(), ["person"])++ assert sorted(nodes) == ["alice", "bob"]+++def test_an_untyped_node_is_not_swept_in():+ graph = ContextGraph()+ graph.add_node("alice", "person", "Alice")+ graph.add_node("ghost", "", "Ghost")++ nodes = CentralityCalculator()._filter_nodes_by_labels(graph, ["person"])++ assert nodes == ["alice"]+++def test_filter_returns_every_node_without_labels():+ nodes = CentralityCalculator()._filter_nodes_by_labels(_context_graph(), None)++ assert sorted(nodes) == ["acme", "alice", "bob"]+++def test_networkx_node_labels_are_unchanged():+ graph = nx.Graph()+ graph.add_node("alice", label="person")+ graph.add_node("acme", label="organization")+ graph.add_edge("alice", "acme")++ calculator = CentralityCalculator()++ assert set(calculator.calculate_pagerank(graph)["centrality"]) == {+ "alice",+ "acme",+ }+ filtered = calculator.calculate_pagerank(graph, node_labels=["person"])+ assert set(filtered["centrality"]) == {"alice"}+++def test_networkx_type_attribute_is_still_read():+ graph = nx.Graph()+ graph.add_node("alice", type="person")+ graph.add_node("acme", type="organization")+ graph.add_edge("alice", "acme")++ filtered = CentralityCalculator().calculate_pagerank(graph, node_labels=["person"])++ assert set(filtered["centrality"]) == {"alice"}+++def _parallel_edge_graph():+ """Alice and Bob joined twice, so one of the two types is not the first."""+ graph = ContextGraph()+ graph.add_node("alice", "person", "Alice")+ graph.add_node("bob", "person", "Bob")+ graph.add_node("acme", "organization", "Acme")+ graph.add_edge("alice", "bob", "knows")+ graph.add_edge("alice", "bob", "works_with")+ graph.add_edge("bob", "acme", "works_at")+ return graph+++def test_relationship_filter_reads_every_parallel_edge():+ """Both types of a pair match, not only the first edge inserted.++ ``ContextGraph.get_edge_data()`` returns the first parallel edge alone, so+ reading the type through it dropped the link whenever the requested type sat+ on the second edge (#1760).+ """+ graph = _parallel_edge_graph()+ calculator = CentralityCalculator()++ assert calculator._get_filtered_neighbors(graph, "alice", ["works_with"]) == ["bob"]+ assert calculator._get_filtered_neighbors(graph, "alice", ["knows"]) == ["bob"]+ assert calculator._get_filtered_neighbors(graph, "alice", ["mentors"]) == []+++def test_pagerank_keeps_the_link_the_filter_asked_for():+ graph = _parallel_edge_graph()++ ranked = CentralityCalculator().calculate_pagerank(+ graph, relationship_types=["works_with"]+ )++ # Only alice→bob survives, so bob still receives score from alice. Dropping+ # that link leaves every node on the same base score instead.+ assert ranked["centrality"]["bob"] > ranked["centrality"]["alice"]+++def _opposite_direction_graph():+ """Alice links to Bob one way, Bob links back with another type.++ ``ContextGraph._adjacency`` is outgoing-only, so the two edges are two+ separate neighbours in two separate directions, not one symmetric pair.+ """+ graph = ContextGraph()+ graph.add_node("alice", "person", "Alice")+ graph.add_node("bob", "person", "Bob")+ graph.add_edge("alice", "bob", "knows")+ graph.add_edge("bob", "alice", "responds_to")+ return graph+++def test_relationship_filter_is_direction_aware():+ """A reverse edge of another type never matches the requested type.++ The edge-list lookup used to read the pair symmetrically, so+ ``bob→alice responds_to`` matched ``alice→bob knows`` and Bob kept a link he+ does not follow. On an outgoing adjacency walk only ``alice→bob`` counts.+ """+ graph = _opposite_direction_graph()+ calculator = CentralityCalculator()++ assert calculator._get_filtered_neighbors(graph, "alice", ["knows"]) == ["bob"]+ assert calculator._get_filtered_neighbors(graph, "bob", ["knows"]) == []+++def test_pagerank_direction_is_respected_by_relationship_filter():+ graph = _opposite_direction_graph()++ ranked = CentralityCalculator().calculate_pagerank(+ graph, relationship_types=["knows"]+ )++ # Only alice→bob carries "knows", so Bob keeps the score he receives and+ # Alice does not get a phantom link back from Bob's "responds_to" edge.+ assert ranked["centrality"]["bob"] > ranked["centrality"]["alice"]+++def _graph_dict():+ """``_context_graph()`` in its plain-dictionary shape."""+ return {+ "entities": [+ {"id": "alice", "type": "person"},+ {"id": "bob", "type": "person"},+ {"id": "acme", "type": "organization"},+ ],+ "relationships": [+ {"source_id": "alice", "target_id": "bob", "type": "knows"},+ {"source_id": "bob", "target_id": "acme", "type": "works_at"},+ ],+ }+++def test_pagerank_reads_a_plain_graph_dict():+ """A ``{"entities": ..., "relationships": ...}`` mapping stays a valid input.++ ``graph_node_ids``, ``graph_node_label`` and ``edge_types_between`` only+ understood ``graph.nodes``/``graph.edges``, so the dictionary shape that+ ``build_graph_view`` has always handled raised+ ``RuntimeError: No nodes found matching the specified criteria`` (#1835).+ """+ calculator = CentralityCalculator()++ dict_scores = calculator.calculate_pagerank(_graph_dict())["centrality"]+ context_scores = calculator.calculate_pagerank(_context_graph())["centrality"]++ assert set(dict_scores) == {"alice", "bob", "acme"}+ assert dict_scores == pytest.approx(context_scores)+++def test_node_labels_filter_a_plain_graph_dict():+ result = CentralityCalculator().calculate_pagerank(+ _graph_dict(), node_labels=["person"]+ )++ assert set(result["centrality"]) == {"alice", "bob"}+++def test_a_dict_entity_without_a_label_is_not_swept_in():+ graph = _graph_dict()+ graph["entities"].append({"id": "ghost"})++ result = CentralityCalculator().calculate_pagerank(graph, node_labels=["person"])++ assert set(result["centrality"]) == {"alice", "bob"}+++def test_dict_neighbour_walk_is_direction_aware():+ calculator = CentralityCalculator()++ assert calculator._get_filtered_neighbors(_graph_dict(), "alice", None) == ["bob"]+ assert calculator._get_filtered_neighbors(_graph_dict(), "acme", None) == []+++def test_relationship_types_filter_a_plain_graph_dict():+ """The dict's edge types are read, not silently dropped.++ Reading the types through a NetworkX conversion strips them, and every+ neighbour then falls to the same base score — a uniform, plausible-looking+ result instead of the link the filter asked for.+ """+ ranked = CentralityCalculator().calculate_pagerank(+ _graph_dict(), relationship_types=["knows"]+ )++ scores = ranked["centrality"]+ assert scores["bob"] > scores["alice"]+ assert scores["bob"] > scores["acme"]