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(context): index causal neighbours once in get_causal_chain (#2121)
ordinary beingb8f3713833bf
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex 4ea567c5..63184ff8 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -4036,6 +4036,23 @@ class ContextGraph:if direction not in ["upstream", "downstream"]:raise ValueError("Direction must be 'upstream', 'downstream' or 'both'")+ # Build the causal adjacency once. The traversal below used to loop+ # over ``self.edges`` for every decision it dequeued, which is O(V*E)+ # on a wide causal graph. One pass over the edge list is enough, and+ # keeps the per-node neighbour order identical to the old scan.+ causal_neighbors: Dict[str, List[str]] = defaultdict(list)+ for edge in self.edges:+ edge_type = edge.edge_type+ if (+ not isinstance(edge_type, str)+ or edge_type.upper() not in _CAUSAL_TRAVERSAL_TYPES+ ):+ continue+ if direction == "upstream":+ causal_neighbors[edge.target_id].append(edge.source_id)+ else:+ causal_neighbors[edge.source_id].append(edge.target_id)+# BFS traversalvisited = set()queue = deque([(decision_id, 0)])@@ -4079,16 +4096,10 @@ class ContextGraph:decision.metadata["causal_distance"] = depthdecisions.append(decision)- # Find connected decisions- for edge in self.edges:- if direction == "upstream":- if edge.target_id == current_id and edge.edge_type.upper() in _CAUSAL_TRAVERSAL_TYPES:- if edge.source_id not in visited and depth < max_depth:- queue.append((edge.source_id, depth + 1))- else: # downstream- if edge.source_id == current_id and edge.edge_type.upper() in _CAUSAL_TRAVERSAL_TYPES:- if edge.target_id not in visited and depth < max_depth:- queue.append((edge.target_id, depth + 1))+ # Find connected decisions from the adjacency built once above.+ for next_id in causal_neighbors.get(current_id, ()):+ if next_id not in visited and depth < max_depth:+ queue.append((next_id, depth + 1))# Sort by depth for upstream (most distant first) and downstream (closest first)if direction == "upstream":diff --git a/tests/context/test_context_graph_causal_chain_scaling.py b/tests/context/test_context_graph_causal_chain_scaling.pynew file mode 100644index 00000000..421e411b--- /dev/null+++ b/tests/context/test_context_graph_causal_chain_scaling.py@@ -0,0 +1,101 @@+"""Causal-chain traversal must not rescan the whole edge list per decision.++``ContextGraph.get_causal_chain`` used to loop over ``self.edges`` for every+node it dequeued. A wide causal graph (one decision with many direct causes+or effects) therefore cost O(V * E); one pass over the edge list is enough.+"""++from types import SimpleNamespace++import pytest++from semantica.context.context_graph import ContextGraph+++class _CountingEdgeList(list):+ """A list that records how many times it is fully iterated."""++ def __init__(self, edges):+ super().__init__(edges)+ self.iterations = 0++ def __iter__(self):+ self.iterations += 1+ return super().__iter__()+++def _decision(graph: ContextGraph, node_id: str) -> None:+ graph.add_node(+ node_id=node_id,+ node_type="decision",+ content=f"scenario for {node_id}",+ properties={+ "category": "test",+ "scenario": f"scenario for {node_id}",+ "reasoning": "reasoning",+ "outcome": "approved",+ "confidence": 0.9,+ },+ )+++def _star_graph(width: int, direction: str) -> ContextGraph:+ """A star with ``width`` spokes around ``root`` in ``direction``."""+ graph = ContextGraph()+ _decision(graph, "root")+ for i in range(width):+ node_id = f"spoke_{i}"+ _decision(graph, node_id)+ if direction == "upstream":+ # spoke -> root, so every spoke is an upstream cause of root.+ graph.add_edge(source_id=node_id, target_id="root", edge_type="CAUSED")+ else:+ # root -> spoke, so every spoke is a downstream effect of root.+ graph.add_edge(source_id="root", target_id=node_id, edge_type="CAUSED")+ return graph++[email protected]("direction", ["upstream", "downstream"])+def test_causal_chain_does_not_rescan_edges_per_visited_node(direction):+ scans = []+ for width in (10, 40):+ graph = _star_graph(width, direction)+ counted_edges = _CountingEdgeList(graph.edges)+ graph.edges = counted_edges++ chain = graph.get_causal_chain("root", direction=direction, max_depth=5)++ assert {+ decision.decision_id: decision.metadata["causal_distance"]+ for decision in chain+ } == {f"spoke_{i}": 1 for i in range(width)}+ scans.append(counted_edges.iterations)++ # The number of full edge-list scans must not grow with the graph. Before+ # the fix this was width + 1 (one scan for root and one per spoke).+ assert scans[0] == scans[1]+ assert scans[0] <= 1+++def test_unrelated_malformed_edges_do_not_break_causal_chain():+ """A non-string edge type on an unrelated edge must not abort traversal.++ ``edges`` is a public, mutable list. The old per-node scan only touched+ ``edge_type`` after the endpoint matched, so an unrelated malformed edge+ was tolerated; building the adjacency up front must preserve that.+ """+ graph = _star_graph(3, "upstream")+ graph.edges.append(+ SimpleNamespace(source_id="unrelated", target_id="elsewhere", edge_type=None)+ )+ graph.edges.append(+ SimpleNamespace(source_id="unrelated", target_id="elsewhere", edge_type=42)+ )++ chain = graph.get_causal_chain("root", direction="upstream", max_depth=5)++ assert {decision.decision_id for decision in chain} == {+ "spoke_0",+ "spoke_1",+ "spoke_2",+ }