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(change-management): preserve snapshot compatibility and audit integrity
OpenAI Codexe2b79ada9ad3
diff --git a/semantica/change_management/managers.py b/semantica/change_management/managers.pyindex b251a703..de1bdb3a 100644--- a/semantica/change_management/managers.py+++ b/semantica/change_management/managers.py@@ -114,6 +114,7 @@ class TemporalVersionManager(BaseVersionManager):"""super().__init__(storage_path)self.config = config+ self._attached_graphs: List[Any] = []def create_snapshot(self,@@ -127,7 +128,8 @@ class TemporalVersionManager(BaseVersionManager):Create and store snapshot with checksum and metadata.Args:- graph: Knowledge graph dict with "entities" and "relationships"+ graph: Knowledge graph dict with "nodes"/"edges" or+ legacy "entities"/"relationships"version_label: Version string (e.g., "v1.0")author: Email address of the change authordescription: Change description (max 500 chars)@@ -140,33 +142,20 @@ class TemporalVersionManager(BaseVersionManager):ValidationError: If input validation failsProcessingError: If storage operation fails"""- from .change_log import ChangeLogEntry- from ..utils.exceptions import ValidationError-change_entry = ChangeLogEntry(timestamp=datetime.now().isoformat(), author=author, description=description)+ entities, relationships = self._extract_graph_collections(graph)-- valid_keys = {"nodes", "edges", "entities", "relationships"}- if not any(key in graph for key in valid_keys):- raise ValidationError(- "Graph dictionary is missing required schema keys. "- "Must contain 'nodes'/'edges' or 'entities'/'relationships'."- )--- nodes_data = graph.get("nodes") or graph.get("entities") or []- edges_data = graph.get("edges") or graph.get("relationships") or []--snapshot = {"label": version_label,"timestamp": change_entry.timestamp,"author": change_entry.author,"description": change_entry.description,- "nodes": nodes_data.copy() if nodes_data else [],- "edges": edges_data.copy() if edges_data else [],+ "nodes": entities.copy(),+ "edges": relationships.copy(),+ "entities": entities.copy(),+ "relationships": relationships.copy(),"metadata": options.get("metadata", {}),}@@ -175,10 +164,36 @@ class TemporalVersionManager(BaseVersionManager):# Store snapshotself.storage.save(snapshot)+ self.storage.assign_version_to_unlabeled_mutations(version_label)self.logger.info(f"Created snapshot '{version_label}' by {author}")return snapshot+ def _extract_graph_collections(+ self, graph: Dict[str, Any]+ ) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:+ """Normalize graph payloads to entity/relationship collections."""+ if not isinstance(graph, dict):+ raise ValidationError("Graph must be provided as a dictionary")++ has_node_schema = "nodes" in graph or "edges" in graph+ has_legacy_schema = "entities" in graph or "relationships" in graph+ if not (has_node_schema or has_legacy_schema):+ raise ValidationError(+ "Graph dictionary is missing required schema keys. "+ "Must contain 'nodes'/'edges' or 'entities'/'relationships'."+ )++ entities = graph.get("nodes")+ if entities is None:+ entities = graph.get("entities", [])++ relationships = graph.get("edges")+ if relationships is None:+ relationships = graph.get("relationships", [])++ return list(entities or []), list(relationships or [])+def compare_versions(self,v1_label_or_dict,@@ -215,6 +230,12 @@ class TemporalVersionManager(BaseVersionManager):detailed_diff = self._compute_detailed_diff(version1, version2)summary = {+ "entities_added": len(detailed_diff["entities_added"]),+ "entities_removed": len(detailed_diff["entities_removed"]),+ "entities_modified": len(detailed_diff["entities_modified"]),+ "relationships_added": len(detailed_diff["relationships_added"]),+ "relationships_removed": len(detailed_diff["relationships_removed"]),+ "relationships_modified": len(detailed_diff["relationships_modified"]),"nodes_added": len(detailed_diff["nodes_added"]),"nodes_removed": len(detailed_diff["nodes_removed"]),"nodes_modified": len(detailed_diff["nodes_modified"]),@@ -243,11 +264,18 @@ class TemporalVersionManager(BaseVersionManager):Returns:Dict with detailed diff information"""- nodes1 = {n.get("id", str(i)): n for i, n in enumerate(version1.get("nodes", []))}- nodes2 = {n.get("id", str(i)): n for i, n in enumerate(version2.get("nodes", []))}+ version1_entities, version1_relationships = self._extract_graph_collections(+ version1+ )+ version2_entities, version2_relationships = self._extract_graph_collections(+ version2+ )- edges1 = {self._relationship_key(e): e for e in version1.get("edges", [])}- edges2 = {self._relationship_key(e): e for e in version2.get("edges", [])}+ nodes1 = {n.get("id", str(i)): n for i, n in enumerate(version1_entities)}+ nodes2 = {n.get("id", str(i)): n for i, n in enumerate(version2_entities)}++ edges1 = {self._relationship_key(e): e for e in version1_relationships}+ edges2 = {self._relationship_key(e): e for e in version2_relationships}node_ids1 = set(nodes1.keys())@@ -278,6 +306,12 @@ class TemporalVersionManager(BaseVersionManager):})return {+ "entities_added": nodes_added,+ "entities_removed": nodes_removed,+ "entities_modified": nodes_modified,+ "relationships_added": edges_added,+ "relationships_removed": edges_removed,+ "relationships_modified": edges_modified,"nodes_added": nodes_added,"nodes_removed": nodes_removed,"nodes_modified": nodes_modified,@@ -376,6 +410,8 @@ class TemporalVersionManager(BaseVersionManager):Injects the mutation callback into the graph to capture all node/edge changes."""graph.mutation_callback = self.record_mutation+ if graph not in self._attached_graphs:+ self._attached_graphs.append(graph)self.logger.info(f"Attached mutation tracking to graph: {getattr(graph, 'graph_id', 'unknown')}")def record_mutation(@@ -455,12 +491,15 @@ class TemporalVersionManager(BaseVersionManager):self.logger.warning(f"Restoring graph to version '{target_version}' - clearing current state.")- graph_payload = {- "nodes": snapshot.get("nodes", []),- "edges": snapshot.get("edges", [])- }-- graph.from_dict(graph_payload)+ entities, relationships = self._extract_graph_collections(snapshot)+ graph_payload = {"nodes": entities, "edges": relationships}++ previous_state = getattr(graph, "_suspend_mutation_callback", False)+ graph._suspend_mutation_callback = True+ try:+ graph.from_dict(graph_payload)+ finally:+ graph._suspend_mutation_callback = previous_stateself.logger.info(f"Successfully restored graph to version '{target_version}'.")return Truediff --git a/semantica/change_management/version_storage.py b/semantica/change_management/version_storage.pyindex a71b94f1..98074784 100644--- a/semantica/change_management/version_storage.py+++ b/semantica/change_management/version_storage.py@@ -40,6 +40,19 @@ from ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+def _snapshot_collections(snapshot: Dict[str, Any]) -> tuple[List[Any], List[Any]]:+ """Normalize snapshot collections for compatibility-aware reads."""+ entities = snapshot.get("entities")+ if entities is None:+ entities = snapshot.get("nodes", [])++ relationships = snapshot.get("relationships")+ if relationships is None:+ relationships = snapshot.get("edges", [])++ return list(entities or []), list(relationships or [])++def create_graph_snapshot_record(version_id: str,@@ -132,6 +145,11 @@ class VersionStorage(ABC):"""Retrieve the chronological mutation history for a specific entity."""pass+ @abstractmethod+ def assign_version_to_unlabeled_mutations(self, version_label: str) -> None:+ """Attach a version label to unlabeled mutations recorded since the last snapshot."""+ pass+class InMemoryVersionStorage(VersionStorage):"""@@ -178,6 +196,7 @@ class InMemoryVersionStorage(VersionStorage):# Return metadata only (without full graph data)metadata_list = []for label, snapshot in self._storage.items():+ entities, relationships = _snapshot_collections(snapshot)metadata = {"label": snapshot.get("label"),"version_id": snapshot.get("version_id", snapshot.get("label")),@@ -186,8 +205,8 @@ class InMemoryVersionStorage(VersionStorage):"author": snapshot.get("author"),"description": snapshot.get("description"),"checksum": snapshot.get("checksum"),- "entity_count": len(snapshot.get("entities", [])),- "relationship_count": len(snapshot.get("relationships", [])),+ "entity_count": len(entities),+ "relationship_count": len(relationships),}metadata_list.append(metadata)return metadata_list@@ -226,6 +245,12 @@ class InMemoryVersionStorage(VersionStorage):with self._lock:return [m for m in self._mutations if m.get("entity_id") == entity_id]+ def assign_version_to_unlabeled_mutations(self, version_label: str) -> None:+ with self._lock:+ for mutation in self._mutations:+ if mutation.get("version_label") is None:+ mutation["version_label"] = version_label+class SQLiteVersionStorage(VersionStorage):"""@@ -370,6 +395,7 @@ class SQLiteVersionStorage(VersionStorage):metadata_list = []for row in cursor.fetchall():snapshot = json.loads(row[0])+ entities, relationships = _snapshot_collections(snapshot)metadata = {"label": snapshot.get("label"),@@ -379,8 +405,8 @@ class SQLiteVersionStorage(VersionStorage):"author": snapshot.get("author"),"description": snapshot.get("description"),"checksum": snapshot.get("checksum"),- "entity_count": len(snapshot.get("entities", [])),- "relationship_count": len(snapshot.get("relationships", [])),+ "entity_count": len(entities),+ "relationship_count": len(relationships),}metadata_list.append(metadata)@@ -521,6 +547,27 @@ class SQLiteVersionStorage(VersionStorage):finally:conn.close()+ def assign_version_to_unlabeled_mutations(self, version_label: str) -> None:+ with self._lock:+ conn = sqlite3.connect(str(self.storage_path))+ try:+ cursor = conn.cursor()+ cursor.execute(+ """+ UPDATE mutation_log+ SET version_label = ?+ WHERE version_label IS NULL+ """,+ (version_label,),+ )+ conn.commit()+ except sqlite3.Error as e:+ raise ProcessingError(+ f"Failed to assign version label to mutations: {e}"+ )+ finally:+ conn.close()+def compute_checksum(data: Dict[str, Any]) -> str:"""@@ -556,4 +603,4 @@ def verify_checksum(snapshot: Dict[str, Any]) -> bool:data_copy.pop("checksum", None)computed_checksum = compute_checksum(data_copy)- return stored_checksum == computed_checksum\ No newline at end of file+ return stored_checksum == computed_checksumdiff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex 86ccb985..50804cf3 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -300,6 +300,7 @@ class ContextGraph:self._analytics_cache = {}self.mutation_callback = self.config.get("mutation_callback", None)+ self._suspend_mutation_callback = Falseenable_advanced = self.config.get("advanced_analytics", True)@@ -456,7 +457,9 @@ class ContextGraph:node.metadata.update(attributes)- if getattr(self, "mutation_callback", None):+ if getattr(self, "mutation_callback", None) and not getattr(+ self, "_suspend_mutation_callback", False+ ):self.mutation_callback("UPDATE_NODE", node_id, node.to_dict())def get_edge_data(self, source_id: str, target_id: str) -> Dict[str, Any]:@@ -1007,7 +1010,9 @@ class ContextGraph:else:self.node_type_index['unknown'].add(node.node_id)- if getattr(self, "mutation_callback", None):+ if getattr(self, "mutation_callback", None) and not getattr(+ self, "_suspend_mutation_callback", False+ ):try:self.mutation_callback("ADD_NODE", node.node_id, node.to_dict())except Exception as e:@@ -1030,7 +1035,9 @@ class ContextGraph:self.edge_type_index[edge.edge_type].append(edge)self._adjacency[edge.source_id].append(edge)- if getattr(self, "mutation_callback", None):+ if getattr(self, "mutation_callback", None) and not getattr(+ self, "_suspend_mutation_callback", False+ ):import jsonedge_id = json.dumps([edge.source_id, edge.edge_type, edge.target_id])try:diff --git a/tests/change_management/test_audit_trail.py b/tests/change_management/test_audit_trail.pyindex 5f43e765..e703f755 100644--- a/tests/change_management/test_audit_trail.py+++ b/tests/change_management/test_audit_trail.py@@ -41,6 +41,8 @@ def test_version_tagging_and_retrieval(setup_env):tags = manager.list_tags()assert "production-ready" in tagsassert tags["production-ready"] == "v1.0"+ history = manager.get_node_history("node_1")+ assert history[0]["version_label"] == "v1.0"def test_tagging_nonexistent_version_fails(setup_env):_, manager = setup_env@@ -64,4 +66,23 @@ def test_rollback_protection_enforcement(setup_env):success = manager.restore_snapshot(graph, "v1.0", require_confirmation=False)assert success is True- assert len(graph.nodes) == 1\ No newline at end of file+ assert len(graph.nodes) == 1++def test_restore_snapshot_does_not_record_replay_mutations(setup_env):+ graph, manager = setup_env+ graph.add_node("node_1", "concept")+ manager.create_snapshot(+ graph.to_dict(),+ version_label="v1.0",+ author="[email protected]",+ description="Initial snapshot",+ )+ graph.add_node_attribute("node_1", {"status": "changed"})++ history_before_restore = manager.get_node_history("node_1")+ assert len(history_before_restore) == 2++ manager.restore_snapshot(graph, "v1.0", require_confirmation=False)++ history_after_restore = manager.get_node_history("node_1")+ assert len(history_after_restore) == 2diff --git a/tests/change_management/test_managers.py b/tests/change_management/test_managers.pyindex 34d78d56..984883b2 100644--- a/tests/change_management/test_managers.py+++ b/tests/change_management/test_managers.py@@ -71,6 +71,8 @@ class TestTemporalVersionManager:assert "timestamp" in snapshotassert len(snapshot["entities"]) == 2assert len(snapshot["relationships"]) == 1+ assert len(snapshot["nodes"]) == 2+ assert len(snapshot["edges"]) == 1def test_create_snapshot_with_invalid_author(self):"""Test snapshot creation with invalid author email."""@@ -117,6 +119,8 @@ class TestTemporalVersionManager:versions = manager.list_versions()assert len(versions) == 1assert versions[0]["label"] == "test_v1.0"+ assert versions[0]["entity_count"] == 2+ assert versions[0]["relationship_count"] == 1def test_get_version(self):"""Test retrieving specific version."""@@ -206,6 +210,51 @@ class TestTemporalVersionManager:assert diff["entities_modified"][0]["id"] == "entity1"assert diff["entities_modified"][0]["changes"]["name"]["from"] == "Entity 1"assert diff["entities_modified"][0]["changes"]["name"]["to"] == "Entity 1 Updated"+ assert diff["summary"]["nodes_added"] == 1+ assert diff["summary"]["edges_added"] == 1++ def test_create_snapshot_accepts_nodes_and_edges(self):+ """Test ContextGraph-style node/edge payload support."""+ manager = TemporalVersionManager()+ graph = {+ "nodes": [+ {"id": "entity1", "name": "Entity 1", "type": "Person"},+ {"id": "entity2", "name": "Entity 2", "type": "Organization"},+ ],+ "edges": [+ {"source": "entity1", "target": "entity2", "type": "works_for"}+ ],+ }++ snapshot = manager.create_snapshot(+ graph, "nodes_v1", "[email protected]", "Node/edge snapshot"+ )++ assert len(snapshot["nodes"]) == 2+ assert len(snapshot["edges"]) == 1+ assert len(snapshot["entities"]) == 2+ assert len(snapshot["relationships"]) == 1++ def test_compare_versions_supports_mixed_snapshot_schemas(self):+ """Test diff compatibility between legacy and node/edge snapshots."""+ manager = TemporalVersionManager()+ manager.create_snapshot(+ {"entities": [{"id": "entity1"}], "relationships": []},+ "v1.0",+ "[email protected]",+ "Version 1",+ )+ manager.create_snapshot(+ {"nodes": [{"id": "entity1"}, {"id": "entity2"}], "edges": []},+ "v2.0",+ "[email protected]",+ "Version 2",+ )++ diff = manager.compare_versions("v1.0", "v2.0")+ assert diff["summary"]["entities_added"] == 1+ assert diff["summary"]["nodes_added"] == 1+ assert diff["entities_added"][0]["id"] == "entity2"class TestOntologyVersionManager: