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(context): index temporal causal trace and accept edge aliases (#2124)
ordinary being9bbc94675e2f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b4d8f2bf..386b3e37 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -47,6 +47,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **`get_causal_chain` rejected `direction="both"`, which the MCP tool schema advertises** (fixes #1815) by @costajohnt- `ContextGraph.get_causal_chain` and `CausalChainAnalyzer.get_causal_chain` now accept `"both"` and return the upstream chain followed by the downstream one, each walked up to `max_depth`. Causes come farthest first and effects nearest first on both backends, each decision is listed once (the nearest copy within each direction; a decision reachable both ways is listed as upstream) and carries `metadata["causal_direction"]`. The MCP `get_causal_chain` tool (and the legacy `semantica.mcp_server` one, whose schema now lists `"both"`) no longer errors for this value.+- **`CausalChainAnalyzer.trace_at_time()` scanned every causal edge per visited decision and ignored alias edge types** (fixes #2123) by @Tong-bit-art+ - The ContextGraph path now builds a time-eligible causal adjacency once per call, using the same `_CAUSAL_TRAVERSAL_TYPES` union as `get_causal_chain`, so a wide temporal graph is no longer O(V*E). The `recorded_at` cutoff, depth limit, result order and `causal_distance` metadata are unchanged.+ - Edges recorded with the analyzer vocabulary (`causes`, `influences`, `leads_to`, `supports`) are now visible, matching `ContextGraph.get_causal_chain()`. This affects the in-memory graph path; the Cypher path keeps its existing canonical-only filter.+- **`semantica pipeline validate` reported a partly malformed file valid, and `--json` had no structured result** (fixes #2026) by @ALDRIN121- `PipelineBuilder.build_pipeline()` keeps a step only when both `name` and `type` are truthy, so a half-written step was dropped before the validator saw it and the file was reported valid. `_load_pipeline_file()` now checks every entry while the index is still known and rejects the file, naming the offending one (`steps[1] ('broken') is missing a non-empty 'type'`). A step that is not a mapping used to reach `dict()` inside `deserialize_pipeline()` and surface as `dictionary update sequence element #0 has length 1; 2 is required`; it is now reported as `steps[0] is not a mapping (got str)`. `pipeline run` loads through the same helper, so it no longer executes a pipeline that is silently missing a step- `validate --json` now always emits `{valid, errors, warnings, pipeline}` on stdout — including when the loader or the builder inside it rejects the file, which previously fell through to the generic `{"error": ...}` envelope on stderr. When the builder raises, its `Pipeline validation failed: [...]` message is split back into one string per error instead of one reprdiff --git a/semantica/context/causal_analyzer.py b/semantica/context/causal_analyzer.pyindex 9d396e11..c23857e4 100644--- a/semantica/context/causal_analyzer.py+++ b/semantica/context/causal_analyzer.py@@ -658,9 +658,20 @@ class CausalChainAnalyzer:max_depth: int,) -> List[Decision]:"""Trace transaction-time causal chains against an in-memory ContextGraph."""- eligible_edges = []+ from .context_graph import _CAUSAL_TRAVERSAL_TYPES++ # Build the time-eligible causal adjacency once. The traversal below+ # used to scan ``eligible_edges`` for every visited decision, which is+ # O(V*E) on a wide temporal graph. The type set is the same union the+ # other causal traversals accept, so aliases such as "causes" are not+ # invisible here.+ causal_neighbors: Dict[str, List[str]] = {}for edge in getattr(self.graph_store, "edges", []):- if edge.edge_type not in ["CAUSED", "INFLUENCED", "PRECEDENT_FOR"]:+ edge_type = getattr(edge, "edge_type", None)+ if (+ not isinstance(edge_type, str)+ or edge_type.upper() not in _CAUSAL_TRAVERSAL_TYPES+ ):continuerecorded_at = (edge.metadata or {}).get("recorded_at")if recorded_at is None:@@ -669,10 +680,14 @@ class CausalChainAnalyzer:edge_recorded_at = self._normalize_at_time(recorded_at)except ValueError:continue- if edge_recorded_at <= cutoff:- eligible_edges.append(edge)+ if edge_recorded_at > cutoff:+ continue+ if direction == "upstream":+ causal_neighbors.setdefault(edge.target_id, []).append(edge.source_id)+ else:+ causal_neighbors.setdefault(edge.source_id, []).append(edge.target_id)- if not eligible_edges:+ if not causal_neighbors:return []visited = set()@@ -704,11 +719,9 @@ class CausalChainAnalyzer:decision.metadata["causal_distance"] = depthdecisions.append(decision)- for edge in eligible_edges:- if direction == "upstream" and edge.target_id == current_id and depth < max_depth:- queue.append((edge.source_id, depth + 1))- if direction == "downstream" and edge.source_id == current_id and depth < max_depth:- queue.append((edge.target_id, depth + 1))+ for next_id in causal_neighbors.get(current_id, ()):+ if depth < max_depth:+ queue.append((next_id, depth + 1))if direction == "upstream":decisions.sort(key=lambda d: d.metadata.get("causal_distance", 0), reverse=True)diff --git a/tests/context/test_causal_analyzer_temporal_trace.py b/tests/context/test_causal_analyzer_temporal_trace.pynew file mode 100644index 00000000..8026092c--- /dev/null+++ b/tests/context/test_causal_analyzer_temporal_trace.py@@ -0,0 +1,131 @@+"""Temporal causal tracing must index time-eligible edges once.++``CausalChainAnalyzer.trace_at_time()`` filtered the causal edge list once and+then scanned that whole list for every visited decision. A wide temporal+causal graph therefore cost O(V * E). It also matched only the canonical+uppercase causal types, so edges recorded with the analyzer vocabulary+(``causes``/``influences``) were invisible.+"""++from semantica.context import ContextGraph+from semantica.context.causal_analyzer import CausalChainAnalyzer+++class _AccessCountingEdge:+ """Proxy that counts reads of the two endpoint fields."""++ def __init__(self, edge):+ self._edge = edge+ self.source_reads = 0+ self.target_reads = 0++ @property+ def source_id(self):+ self.source_reads += 1+ return self._edge.source_id++ @property+ def target_id(self):+ self.target_reads += 1+ return self._edge.target_id++ def __getattr__(self, name):+ return getattr(self._edge, name)+++def _decision(graph: ContextGraph, node_id: str) -> None:+ graph.add_node(+ node_id=node_id,+ node_type="decision",+ content=node_id,+ properties={+ "category": "test",+ "scenario": node_id,+ "reasoning": "reasoning",+ "outcome": "approved",+ "confidence": 0.9,+ },+ )+++def _star_graph(width: int) -> ContextGraph:+ graph = ContextGraph()+ _decision(graph, "root")+ for i in range(width):+ node_id = f"spoke_{i}"+ _decision(graph, node_id)+ graph.add_edge(+ source_id=node_id,+ target_id="root",+ edge_type="CAUSED",+ recorded_at="2024-01-01T00:00:00",+ )+ graph.add_edge(+ source_id=node_id,+ target_id=f"spoke_{(i + 1) % width}",+ edge_type="RELATED",+ recorded_at="2024-01-01T00:00:00",+ )+ return graph+++def test_trace_at_time_does_not_rescan_eligible_edges_per_visited_decision():+ endpoint_reads = []+ for width in (10, 40):+ graph = _star_graph(width)+ wrappers = [_AccessCountingEdge(edge) for edge in graph.edges]+ graph.edges = wrappers++ chain = CausalChainAnalyzer(graph_store=graph).trace_at_time(+ "root", "2024-02-01T00:00:00", direction="upstream", max_depth=5+ )++ assert {decision.decision_id for decision in chain} == {+ f"spoke_{i}" for i in range(width)+ }+ endpoint_reads.append(+ sum(wrapper.source_reads + wrapper.target_reads for wrapper in wrappers)+ )++ # Before the fix, each visited decision scanned every eligible edge, so+ # endpoint reads grew quadratically with width. The one-time adjacency+ # build is O(E), so the per-edge read count stays constant.+ assert endpoint_reads[0] * 40 == endpoint_reads[1] * 10+++def test_trace_at_time_accepts_alias_causal_edge_types():+ graph = ContextGraph()+ _decision(graph, "cause")+ _decision(graph, "effect")+ graph.add_edge(+ source_id="cause",+ target_id="effect",+ edge_type="causes",+ recorded_at="2024-01-01T00:00:00",+ )++ chain = CausalChainAnalyzer(graph_store=graph).trace_at_time(+ "effect", "2024-02-01T00:00:00", direction="upstream"+ )++ assert [decision.decision_id for decision in chain] == ["cause"]+++def test_trace_at_time_still_honours_the_recorded_at_cutoff():+ graph = ContextGraph()+ _decision(graph, "cause")+ _decision(graph, "effect")+ graph.add_edge(+ source_id="cause",+ target_id="effect",+ edge_type="causes",+ recorded_at="2024-02-01T00:00:00",+ )++ analyzer = CausalChainAnalyzer(graph_store=graph)++ assert analyzer.trace_at_time("effect", "2024-01-01T00:00:00") == []+ assert [+ decision.decision_id+ for decision in analyzer.trace_at_time("effect", "2024-03-01T00:00:00")+ ] == ["cause"]