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
perf(kg): index a ContextGraph's edge types once for relationship filtering (#1932)
Raashish Aggarwal4f348c6328f1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 379c4d83..af01b59d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,6 +34,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Relationship filtering on a `ContextGraph` rescanned the edge list for every node pair** (fixes #1927)+ - `edge_types_between` read every edge of a `ContextGraph` for each (node, neighbour) pair it classified, so `detect_communities_label_propagation` and `calculate_pagerank` with `relationship_types` were O(E^2): about 21 s each on a 6,000-edge graph. `build_edge_type_index` now indexes a `ContextGraph`'s edge list as well, and both callers build the index once per call (1.4 s and 0.09 s on the same graph). The per-pair answers are unchanged. New `tests/kg/test_context_graph_edge_type_index.py`+- **TOML config files were silently ignored on Python 3.11+**- `GraphStoreConfig`, `TripletStoreConfig` and `VectorStoreConfig` loaded `.toml` files with the `tomli` backport, which Semantica never declared and which is usually absent on 3.11+. The `ImportError` was caught, logged and the file's settings dropped. With 3.11 as the floor, all four config classes (including `VisualizationConfig`, which had a two-level fallback) use the stdlib `tomllib`. New `tests/test_toml_config_loading.py`diff --git a/semantica/kg/_graph_view.py b/semantica/kg/_graph_view.pyindex 9c0c99e4..2a62349b 100644--- a/semantica/kg/_graph_view.py+++ b/semantica/kg/_graph_view.py@@ -1,7 +1,7 @@"""Internal graph view helpers shared by KG analytics modules."""from dataclasses import dataclass-from typing import Any, Dict, Iterable, List, Optional, Set, Tuple+from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple@dataclass@@ -185,12 +185,14 @@ def _edge_type_of(edge: Any) -> Any:@dataclassclass EdgeTypeIndex:- """The declared edge types of a plain graph dictionary, read once.+ """The declared edge types of a graph's edge list, read once.``typed`` records whether any edge record declares a type at all;``by_pair`` maps each ``(source, target)`` to the types declared from``source`` to ``target``; ``untyped`` holds every ``(source, target)``- joined by at least one edge that declares no type.+ joined by at least one edge that declares no type. The index records the+ edges as declared; :func:`edge_types_between` decides what an untyped edge+ means for each kind of graph."""typed: bool@@ -198,14 +200,18 @@ class EdgeTypeIndex:untyped: Set[Tuple[Any, Any]]-def build_edge_type_index(graph: Dict[str, Any]) -> EdgeTypeIndex:- """Read a graph dictionary's edge records once for repeated type lookups.+def _context_edges(graph: Any) -> Optional[Sequence[Any]]:+ """Return a ``ContextGraph``-style edge list, or ``None`` for other graphs."""+ edges = getattr(graph, "edges", None)+ if isinstance(edges, (list, tuple)) and any(+ hasattr(edge, "source_id") for edge in edges+ ):+ return edges+ return None- A caller that classifies many links passes the result to- :func:`edge_types_between`, so the edge list is scanned once per graph- instead of once per link.- """- edges = _extract_edges(graph)++def _index_edges(edges: Iterable[Any]) -> EdgeTypeIndex:+ """Read edge records once into an :class:`EdgeTypeIndex`."""by_pair: Dict[Tuple[Any, Any], Set[Any]] = {}untyped: Set[Tuple[Any, Any]] = set()typed = False@@ -228,6 +234,33 @@ def build_edge_type_index(graph: Dict[str, Any]) -> EdgeTypeIndex:return EdgeTypeIndex(typed=typed, by_pair=by_pair, untyped=untyped)+def build_edge_type_index(graph: Any) -> Optional[EdgeTypeIndex]:+ """Read a graph's edge records once for repeated type lookups.++ A caller that classifies many links passes the result to+ :func:`edge_types_between`, so the edge list is scanned once per graph+ instead of once per link. A plain graph dictionary and a ``ContextGraph``+ are indexed; any other graph is answered through ``get_edge_data()`` and+ gets ``None``.+ """+ if isinstance(graph, dict):+ return _index_edges(_extract_edges(graph))+ context_edges = _context_edges(graph)+ if context_edges is None:+ return None+ return _index_edges(context_edges)+++def _pair_types(+ index: EdgeTypeIndex, source: Any, target: Any, directed: bool+) -> Set[Any]:+ """Union a pair's indexed types, reading both ways unless ``directed``."""+ types: Set[Any] = set(index.by_pair.get((source, target), ()))+ if not directed:+ types |= index.by_pair.get((target, source), set())+ return types++def _dict_edge_types(graph: Dict[str, Any],source: Any,@@ -243,18 +276,14 @@ def _dict_edge_types(edge, so typed records elsewhere in the graph do not change it."""if index is None:- index = build_edge_type_index(graph)+ index = _index_edges(_extract_edges(graph))if not index.typed:return Noneif (source, target) in index.untyped or (not directed and (target, source) in index.untyped):return None-- types: Set[Any] = set(index.by_pair.get((source, target), ()))- if not directed:- types |= index.by_pair.get((target, source), set())- return types+ return _pair_types(index, source, target, directed)def _node_id(value: Any) -> Any:@@ -377,27 +406,18 @@ def edge_types_between(mapping for a multigraph.``edge_types`` is an optional :func:`build_edge_type_index` result for a- plain graph dictionary. A caller classifying many links builds it once, so- the lookup does not rescan the edge list for every pair.+ plain graph dictionary or a ``ContextGraph``. A caller classifying many+ links builds it once, so the lookup does not rescan the edge list for every+ pair."""if isinstance(graph, dict):return _dict_edge_types(graph, source, target, directed, edge_types)- 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+ # Only a ContextGraph has an index here. It answers for the pair as a+ # whole, so its untyped edges add nothing and such a pair gets an empty set.+ index = edge_types if edge_types is not None else build_edge_type_index(graph)+ if index is not None:+ return _pair_types(index, source, target, directed)if hasattr(graph, "get_edge_data"):data = graph.get_edge_data(source, target)diff --git a/semantica/kg/centrality_calculator.py b/semantica/kg/centrality_calculator.pyindex 4356052c..82e3f182 100644--- a/semantica/kg/centrality_calculator.py+++ b/semantica/kg/centrality_calculator.py@@ -666,12 +666,11 @@ class CentralityCalculator:if isinstance(graph, dict)else None)- # Its edge types are read once too, so the relationship filter- # costs O(E) rather than one edge-list scan per neighbour.+ # The edge types of a graph dictionary or a ContextGraph are read+ # once too, so the relationship filter costs O(E) rather than one+ # edge-list scan per neighbour.edge_types = (- build_edge_type_index(graph)- if relationship_types is not None and isinstance(graph, dict)- else None+ build_edge_type_index(graph) if relationship_types is not None else None)for node in nodes:diff --git a/semantica/kg/community_detector.py b/semantica/kg/community_detector.pyindex f20055a3..aeffa4d7 100644--- a/semantica/kg/community_detector.py+++ b/semantica/kg/community_detector.py@@ -952,12 +952,11 @@ class CommunityDetector:if hasattr(graph, "neighbors") or hasattr(graph, "get_neighbors")else build_adjacency(graph))- # Its edge types are read once too, so the filter below costs O(E)- # rather than one edge-list scan per neighbour.+ # The edge types of a graph dictionary or a ContextGraph are read once+ # too, so the filter below costs O(E) rather than one edge-list scan+ # per neighbour.edge_types = (- build_edge_type_index(graph)- if relationship_types is not None and isinstance(graph, dict)- else None+ build_edge_type_index(graph) if relationship_types is not None else None)for node in rows:diff --git a/tests/kg/test_context_graph_edge_type_index.py b/tests/kg/test_context_graph_edge_type_index.pynew file mode 100644index 00000000..bd706709--- /dev/null+++ b/tests/kg/test_context_graph_edge_type_index.py@@ -0,0 +1,89 @@+"""Relationship filtering on a ContextGraph reads its edge list once.++``edge_types_between`` scanned the whole edge list for every (node, neighbour)+pair it classified, so filtering on ``relationship_types`` was O(E^2) for label+propagation and PageRank on a ContextGraph (#1927).+"""++import pytest++from semantica.context.context_graph import ContextGraph+from semantica.kg import CentralityCalculator+from semantica.kg._graph_view import build_edge_type_index, edge_types_between+from semantica.kg.community_detector import CommunityDetector+++class _CountingEdges(list):+ """An edge list that counts how many edges are read from it."""++ reads = 0++ def __iter__(self):+ for edge in super().__iter__():+ self.reads += 1+ yield edge+++def _ring(n=40):+ graph = ContextGraph()+ for i in range(n):+ graph.add_node(f"n{i}", "thing")+ for i in range(n):+ graph.add_edge(f"n{i}", f"n{(i + 1) % n}", "next")+ graph.edges = _CountingEdges(graph.edges)+ return graph+++def _mixed_graph():+ """Parallel edges of two types, a reverse edge and an unrelated pair."""+ graph = ContextGraph()+ for node in ("a", "b", "c"):+ graph.add_node(node, "thing")+ graph.add_edge("a", "b", "knows")+ graph.add_edge("a", "b", "likes")+ graph.add_edge("b", "a", "follows")+ graph.add_edge("b", "c", "knows")+ return graph+++ "source, target, directed, expected",+ [+ ("a", "b", True, {"knows", "likes"}),+ ("a", "b", False, {"knows", "likes", "follows"}),+ ("b", "a", True, {"follows"}),+ ("c", "b", True, set()),+ ("c", "b", False, {"knows"}),+ ("a", "c", False, set()),+ ],+)+def test_index_gives_the_per_pair_answers(source, target, directed, expected):+ graph = _mixed_graph()+ index = build_edge_type_index(graph)++ assert index is not None+ assert edge_types_between(graph, source, target, directed, index) == expected+ assert edge_types_between(graph, source, target, directed) == expected+++def test_label_propagation_reads_the_edge_list_once():+ graph = _ring()++ result = CommunityDetector().detect_communities_label_propagation(+ graph, relationship_types=["next"], random_seed=0+ )++ assert set(result["node_assignments"]) == set(graph.nodes)+ assert graph.edges.reads < 2 * len(graph.edges)+++def test_pagerank_reads_the_edge_list_once():+ graph = _ring()++ scores = CentralityCalculator().calculate_pagerank(+ graph, relationship_types=["next"]+ )["centrality"]++ # Every node of a directed ring has the same rank.+ assert scores == {node: pytest.approx(1 / len(graph.nodes)) for node in graph.nodes}+ assert graph.edges.reads < 2 * len(graph.edges)