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: make cross-graph links durable across save/load
KaifAhmad1867ecfda1b8c
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex f5d3b560..3f51b9ca 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -270,6 +270,9 @@ class ContextGraph:self.entity_linker = self.config.get("entity_linker") or EntityLinker()+ # Stable identifier so this graph can be referenced after save/load+ self.graph_id: str = str(uuid.uuid4())+# Graph structureself.nodes: Dict[str, ContextNode] = {}self.edges: List[ContextEdge] = []@@ -283,6 +286,8 @@ class ContextGraph:# Cross-graph navigation: link_id -> (other_graph, source_node_id, target_node_id)self._linked_graphs: Dict[str, Tuple["ContextGraph", str, str]] = {}+ # Unresolved link metadata (populated after load_from_file, before resolve_links)+ self._unresolved_links: Dict[str, Dict[str, str]] = {}# Progress trackerself.progress_tracker = get_progress_tracker()@@ -613,9 +618,24 @@ class ContextGraph:"""import json+ # Serialise cross-graph link metadata (object references are not serialisable,+ # so we store other_graph_id; callers can reconnect with resolve_links()).+ links_data = []+ for link_id, (other_graph, source_node_id, target_node_id) in self._linked_graphs.items():+ links_data.append(+ {+ "link_id": link_id,+ "source_node_id": source_node_id,+ "target_node_id": target_node_id,+ "other_graph_id": other_graph.graph_id,+ }+ )+data = {+ "graph_id": self.graph_id,"nodes": [node.to_dict() for node in self.nodes.values()],"edges": [edge.to_dict() for edge in self.edges],+ "links": links_data,}with open(path, "w", encoding="utf-8") as f:@@ -646,6 +666,12 @@ class ContextGraph:self._adjacency.clear()self.node_type_index.clear()self.edge_type_index.clear()+ self._linked_graphs.clear()+ self._unresolved_links.clear()++ # Restore stable graph identity+ if "graph_id" in data:+ self.graph_id = data["graph_id"]# Load nodesnodes = data.get("nodes", [])@@ -655,6 +681,12 @@ class ContextGraph:edges = data.get("edges", [])self.add_edges(edges)+ # Restore link metadata — object references require resolve_links() to reconnect+ for link_meta in data.get("links", []):+ link_id = link_meta.get("link_id")+ if link_id:+ self._unresolved_links[link_id] = link_meta+self.logger.info(f"Loaded context graph from {path}")def find_node(self, node_id: str) -> Optional[Dict[str, Any]]:@@ -804,6 +836,13 @@ class ContextGraph:KeyError: If link_id is not registered on this graph."""if link_id not in self._linked_graphs:+ if link_id in self._unresolved_links:+ meta = self._unresolved_links[link_id]+ raise KeyError(+ f"Cross-graph link '{link_id}' exists but its target graph "+ f"(graph_id={meta.get('other_graph_id')!r}) has not been reconnected. "+ "Call resolve_links({graph_id: graph_instance, ...}) to restore navigation."+ )raise KeyError(f"No cross-graph link '{link_id}' found. ""Call link_graph() first to create the link."@@ -811,6 +850,49 @@ class ContextGraph:other_graph, _, target_node_id = self._linked_graphs[link_id]return other_graph, target_node_id+ def resolve_links(self, graphs: Dict[str, "ContextGraph"]) -> int:+ """+ Reconnect cross-graph links after a :meth:`load_from_file` call.++ Since ``other_graph`` object references cannot be serialised, links are stored+ as metadata only (``other_graph_id``). Call this method with a mapping of+ ``{graph_id: graph_instance}`` to restore live navigation.++ Args:+ graphs: Mapping of graph_id strings to ContextGraph instances.++ Returns:+ Number of links successfully resolved.++ Example::++ g1.save_to_file("g1.json")+ g2.save_to_file("g2.json")++ g1b, g2b = ContextGraph(), ContextGraph()+ g1b.load_from_file("g1.json")+ g2b.load_from_file("g2.json")+ resolved = g1b.resolve_links({g2b.graph_id: g2b})+ """+ resolved = 0+ for link_id, meta in list(self._unresolved_links.items()):+ other_graph_id = meta.get("other_graph_id")+ if other_graph_id in graphs:+ other_graph = graphs[other_graph_id]+ source_node_id = meta["source_node_id"]+ target_node_id = meta["target_node_id"]+ # Validate target node still exists in the restored graph+ if target_node_id in other_graph.nodes:+ self._linked_graphs[link_id] = (other_graph, source_node_id, target_node_id)+ del self._unresolved_links[link_id]+ resolved += 1+ else:+ self.logger.warning(+ f"resolve_links: target node '{target_node_id}' not found in "+ f"graph '{other_graph_id}' for link '{link_id}'"+ )+ return resolved+def find_edges(self, edge_type: Optional[str] = None) -> List[Dict[str, Any]]:"""Find edges, optionally filtered by type."""if edge_type:diff --git a/tests/context/test_cross_graph_navigation.py b/tests/context/test_cross_graph_navigation.pynew file mode 100644index 00000000..e256912e--- /dev/null+++ b/tests/context/test_cross_graph_navigation.py@@ -0,0 +1,231 @@+"""Tests for cross-graph linking, navigation, and save/load persistence."""++import json+import os+import tempfile++import pytest++from semantica.context.context_graph import ContextGraph+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _two_graphs():+ """Return two graphs each with one node."""+ g1 = ContextGraph()+ g2 = ContextGraph()+ g1.add_node("src", "entity", content="source entity")+ g2.add_node("dst", "entity", content="destination entity")+ return g1, g2+++# ---------------------------------------------------------------------------+# link_graph / navigate_to — basic contract+# ---------------------------------------------------------------------------+++class TestLinkGraph:+ def test_returns_link_id(self):+ g1, g2 = _two_graphs()+ link_id = g1.link_graph(g2, "src", "dst")+ assert isinstance(link_id, str) and len(link_id) > 0++ def test_navigate_to_returns_correct_graph_and_node(self):+ g1, g2 = _two_graphs()+ link_id = g1.link_graph(g2, "src", "dst")+ other, entry = g1.navigate_to(link_id)+ assert other is g2+ assert entry == "dst"++ def test_navigate_to_unknown_link_raises(self):+ g1, _ = _two_graphs()+ with pytest.raises(KeyError):+ g1.navigate_to("nonexistent-link-id")++ def test_source_not_in_graph_raises(self):+ g1, g2 = _two_graphs()+ with pytest.raises(KeyError):+ g1.link_graph(g2, "missing", "dst")++ def test_target_not_in_other_graph_raises(self):+ g1, g2 = _two_graphs()+ with pytest.raises(KeyError):+ g1.link_graph(g2, "src", "missing")++ def test_marker_node_has_cross_graph_link_type(self):+ """link_graph() must NOT pollute graph with phantom 'entity' nodes."""+ g1, g2 = _two_graphs()+ link_id = g1.link_graph(g2, "src", "dst")+ marker_id = f"__cross_graph_{link_id}"+ assert marker_id in g1.nodes+ assert g1.nodes[marker_id].node_type == "cross_graph_link"++ def test_no_phantom_entity_nodes(self):+ """Only 'src' and the typed marker should exist in g1."""+ g1, g2 = _two_graphs()+ link_id = g1.link_graph(g2, "src", "dst")+ entity_nodes = [n for n in g1.nodes.values() if n.node_type == "entity"]+ assert len(entity_nodes) == 1 # only 'src'++ def test_multiple_links_from_same_source(self):+ g1 = ContextGraph()+ g2 = ContextGraph()+ g3 = ContextGraph()+ g1.add_node("hub", "entity")+ g2.add_node("a", "entity")+ g3.add_node("b", "entity")+ lid1 = g1.link_graph(g2, "hub", "a")+ lid2 = g1.link_graph(g3, "hub", "b")+ other1, entry1 = g1.navigate_to(lid1)+ other2, entry2 = g1.navigate_to(lid2)+ assert other1 is g2 and entry1 == "a"+ assert other2 is g3 and entry2 == "b"+++# ---------------------------------------------------------------------------+# Persistence: save_to_file / load_from_file + resolve_links+# ---------------------------------------------------------------------------+++class TestCrossGraphPersistence:+ def test_graph_id_preserved_after_save_load(self):+ g1, _ = _two_graphs()+ original_id = g1.graph_id+ with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:+ path = f.name+ try:+ g1.save_to_file(path)+ g1b = ContextGraph()+ g1b.load_from_file(path)+ assert g1b.graph_id == original_id+ finally:+ os.unlink(path)++ def test_links_section_written_to_file(self):+ g1, g2 = _two_graphs()+ link_id = g1.link_graph(g2, "src", "dst")+ with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:+ path = f.name+ try:+ g1.save_to_file(path)+ with open(path) as fp:+ data = json.load(fp)+ assert "links" in data+ assert len(data["links"]) == 1+ lk = data["links"][0]+ assert lk["link_id"] == link_id+ assert lk["source_node_id"] == "src"+ assert lk["target_node_id"] == "dst"+ assert lk["other_graph_id"] == g2.graph_id+ finally:+ os.unlink(path)++ def test_navigate_to_raises_helpful_error_before_resolve(self):+ g1, g2 = _two_graphs()+ link_id = g1.link_graph(g2, "src", "dst")+ with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:+ path = f.name+ try:+ g1.save_to_file(path)+ g1b = ContextGraph()+ g1b.load_from_file(path)+ with pytest.raises(KeyError, match="resolve_links"):+ g1b.navigate_to(link_id)+ finally:+ os.unlink(path)++ def test_resolve_links_restores_navigation(self):+ g1, g2 = _two_graphs()+ link_id = g1.link_graph(g2, "src", "dst")++ with (+ tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f1,+ tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f2,+ ):+ path1, path2 = f1.name, f2.name++ try:+ g1.save_to_file(path1)+ g2.save_to_file(path2)++ g1b = ContextGraph()+ g2b = ContextGraph()+ g1b.load_from_file(path1)+ g2b.load_from_file(path2)++ resolved = g1b.resolve_links({g2b.graph_id: g2b})+ assert resolved == 1++ other, entry = g1b.navigate_to(link_id)+ assert other is g2b+ assert entry == "dst"+ finally:+ os.unlink(path1)+ os.unlink(path2)++ def test_resolve_links_returns_count(self):+ g1 = ContextGraph()+ g2 = ContextGraph()+ g3 = ContextGraph()+ g1.add_node("h", "entity")+ g2.add_node("a", "entity")+ g3.add_node("b", "entity")+ g1.link_graph(g2, "h", "a")+ g1.link_graph(g3, "h", "b")++ with (+ tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f1,+ tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f2,+ tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f3,+ ):+ p1, p2, p3 = f1.name, f2.name, f3.name+ try:+ g1.save_to_file(p1); g2.save_to_file(p2); g3.save_to_file(p3)+ g1b, g2b, g3b = ContextGraph(), ContextGraph(), ContextGraph()+ g1b.load_from_file(p1); g2b.load_from_file(p2); g3b.load_from_file(p3)+ resolved = g1b.resolve_links({g2b.graph_id: g2b, g3b.graph_id: g3b})+ assert resolved == 2+ finally:+ for p in (p1, p2, p3):+ os.unlink(p)++ def test_resolve_links_partial_registry_leaves_unresolved(self):+ """Passing only one graph to resolve_links should resolve only that link."""+ g1 = ContextGraph()+ g2 = ContextGraph()+ g3 = ContextGraph()+ g1.add_node("h", "entity")+ g2.add_node("a", "entity")+ g3.add_node("b", "entity")+ lid1 = g1.link_graph(g2, "h", "a")+ lid2 = g1.link_graph(g3, "h", "b")++ with (+ tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f1,+ tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f2,+ tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f3,+ ):+ p1, p2, p3 = f1.name, f2.name, f3.name+ try:+ g1.save_to_file(p1); g2.save_to_file(p2); g3.save_to_file(p3)+ g1b, g2b, g3b = ContextGraph(), ContextGraph(), ContextGraph()+ g1b.load_from_file(p1); g2b.load_from_file(p2); g3b.load_from_file(p3)++ # Only resolve g2+ resolved = g1b.resolve_links({g2b.graph_id: g2b})+ assert resolved == 1++ # lid1 navigable+ other, entry = g1b.navigate_to(lid1)+ assert other is g2b and entry == "a"++ # lid2 still unresolved — must raise with hint+ with pytest.raises(KeyError, match="resolve_links"):+ g1b.navigate_to(lid2)+ finally:+ for p in (p1, p2, p3):+ os.unlink(p)