Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(change-management): preserve snapshot schema compatibility

OpenAI Codexadac6f7a7bd1
diff --git a/semantica/change_management/managers.py b/semantica/change_management/managers.py
index e0bec29c..b236dd3d 100644
--- a/semantica/change_management/managers.py
+++ b/semantica/change_management/managers.py
@@ -127,7 +127,8 @@ class TemporalVersionManager(BaseVersionManager):
Create and store snapshot with checksum and metadata.
Args:
- graph: Knowledge graph dict with "nodes"/"edges" (or legacy "entities"/"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 author
description: Change description (max 500 chars)
@@ -140,31 +141,22 @@ class TemporalVersionManager(BaseVersionManager):
ValidationError: If input validation fails
ProcessingError: 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
)
-
-
- 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 []
+ entities, relationships = self._extract_graph_collections(graph)
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 [],
+ # Store both key shapes during the migration window so older
+ # readers and newer ContextGraph restore paths both work.
+ "nodes": entities.copy(),
+ "edges": relationships.copy(),
+ "entities": entities.copy(),
+ "relationships": relationships.copy(),
"metadata": options.get("metadata", {}),
}
@@ -173,6 +165,31 @@ class TemporalVersionManager(BaseVersionManager):
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 supported graph payload shapes to entities/relationships."""
+ 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 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,
@@ -240,18 +257,25 @@ class TemporalVersionManager(BaseVersionManager):
Returns:
Dict with detailed diff information
"""
+ version1_entities, version1_relationships = self._extract_graph_collections(
+ version1
+ )
+ version2_entities, version2_relationships = self._extract_graph_collections(
+ version2
+ )
+
entities1 = {
- e.get("id", str(i)): e for i, e in enumerate(version1.get("entities", []))
+ e.get("id", str(i)): e for i, e in enumerate(version1_entities)
}
entities2 = {
- e.get("id", str(i)): e for i, e in enumerate(version2.get("entities", []))
+ e.get("id", str(i)): e for i, e in enumerate(version2_entities)
}
relationships1 = {
- self._relationship_key(r): r for r in version1.get("relationships", [])
+ self._relationship_key(r): r for r in version1_relationships
}
relationships2 = {
- self._relationship_key(r): r for r in version2.get("relationships", [])
+ self._relationship_key(r): r for r in version2_relationships
}
# Entity differences
@@ -438,8 +462,6 @@ class OntologyVersionManager(BaseVersionManager):
Returns:
dict: Ontology version snapshot
"""
- from .change_log import ChangeLogEntry
-
change_entry = ChangeLogEntry(
timestamp=datetime.now().isoformat(), author=author, description=description
)
@@ -449,14 +471,16 @@ class OntologyVersionManager(BaseVersionManager):
"timestamp": change_entry.timestamp,
"author": change_entry.author,
"description": change_entry.description,
- "ontology_data": ontology_data,
- "structure": ontology_data.get("structure", {}),
+ "ontology_iri": ontology_data.get("uri", ""),
+ "version_info": ontology_data.get("version_info", {}),
+ "structure": ontology_data.get("structure", {}),
"metadata": options.get("metadata", {}),
}
-
+
snapshot["checksum"] = compute_checksum(snapshot)
self.storage.save(snapshot)
- self.logger.info(f"Created snapshot '{version_label}' by {author}")
+ self.versions[version_label] = snapshot
+ self.logger.info(f"Created ontology snapshot '{version_label}' by {author}")
return snapshot
def compare_versions(
diff --git a/semantica/change_management/version_storage.py b/semantica/change_management/version_storage.py
index 69767233..c7e84ca9 100644
--- a/semantica/change_management/version_storage.py
+++ b/semantica/change_management/version_storage.py
@@ -39,6 +39,18 @@ from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
+def _snapshot_collections(snapshot: Dict[str, Any]) -> tuple[List[Any], List[Any]]:
+ """Normalize supported snapshot shapes for metadata summaries."""
+ 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,
@@ -187,6 +199,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")),
@@ -195,8 +208,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
@@ -342,6 +355,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"),
@@ -351,8 +365,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)
diff --git a/tests/change_management/test_managers.py b/tests/change_management/test_managers.py
index 2adcf6fe..b9210f50 100644
--- a/tests/change_management/test_managers.py
+++ b/tests/change_management/test_managers.py
@@ -68,6 +68,45 @@ class TestTemporalVersionManager:
assert "timestamp" in snapshot
assert len(snapshot["entities"]) == 2
assert len(snapshot["relationships"]) == 1
+ assert len(snapshot["nodes"]) == 2
+ assert len(snapshot["edges"]) == 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,
+ "test_nodes_v1.0",
+ "Test node edge snapshot creation",
+ )
+
+ assert len(snapshot["nodes"]) == 2
+ assert len(snapshot["edges"]) == 1
+ assert len(snapshot["entities"]) == 2
+ assert len(snapshot["relationships"]) == 1
+
+ def test_create_snapshot_requires_supported_schema(self):
+ """Test schema validation for unsupported graph payloads."""
+ manager = TemporalVersionManager()
+
+ with pytest.raises(ValidationError, match="Graph dictionary must contain"):
+ manager.create_snapshot(
+ {"foo": []},
+ "invalid_v1.0",
+ "Invalid graph payload",
+ )
def test_create_snapshot_with_invalid_author(self):
"""Test snapshot creation with invalid author email."""
@@ -114,6 +153,29 @@ class TestTemporalVersionManager:
versions = manager.list_versions()
assert len(versions) == 1
assert versions[0]["label"] == "test_v1.0"
+
+ def test_list_versions_counts_nodes_and_edges(self):
+ """Test version metadata counts for node/edge snapshots."""
+ manager = TemporalVersionManager()
+ manager.create_snapshot(
+ {
+ "nodes": [
+ {"id": "entity1", "name": "Entity 1", "type": "Person"},
+ {"id": "entity2", "name": "Entity 2", "type": "Organization"},
+ ],
+ "edges": [
+ {"source": "entity1", "target": "entity2", "type": "works_for"}
+ ],
+ },
+ "test_nodes_v1.0",
+ "Test metadata counts",
+ )
+
+ versions = manager.list_versions()
+ assert len(versions) == 1
+ assert versions[0]["entity_count"] == 2
+ assert versions[0]["relationship_count"] == 1
def test_get_version(self):
"""Test retrieving specific version."""
@@ -204,6 +266,60 @@ class TestTemporalVersionManager:
assert diff["entities_modified"][0]["changes"]["name"]["from"] == "Entity 1"
assert diff["entities_modified"][0]["changes"]["name"]["to"] == "Entity 1 Updated"
+ def test_compare_versions_with_nodes_and_edges(self):
+ """Test detailed comparison for ContextGraph-style snapshots."""
+ manager = TemporalVersionManager()
+ graph_v1 = {
+ "nodes": [
+ {"id": "entity1", "name": "Entity 1", "type": "Person"},
+ {"id": "entity2", "name": "Entity 2", "type": "Organization"},
+ ],
+ "edges": [
+ {"source": "entity1", "target": "entity2", "type": "works_for"}
+ ],
+ }
+ graph_v2 = {
+ "nodes": [
+ {"id": "entity1", "name": "Entity 1 Updated", "type": "Person"},
+ {"id": "entity3", "name": "Entity 3", "type": "Project"},
+ ],
+ "edges": [
+ {"source": "entity1", "target": "entity3", "type": "manages"}
+ ],
+ }
+
+ manager.create_snapshot(graph_v1, "v1.0", "[email protected]", "Version 1")
+ manager.create_snapshot(graph_v2, "v2.0", "[email protected]", "Version 2")
+
+ diff = manager.compare_versions("v1.0", "v2.0")
+ assert diff["summary"]["entities_added"] == 1
+ assert diff["summary"]["entities_removed"] == 1
+ assert diff["summary"]["entities_modified"] == 1
+ assert diff["summary"]["relationships_added"] == 1
+ assert diff["summary"]["relationships_removed"] == 1
+
+ def test_compare_versions_with_mixed_snapshot_schemas(self):
+ """Test diff compatibility between legacy and node/edge snapshots."""
+ manager = TemporalVersionManager()
+ graph_v1 = {
+ "entities": [{"id": "entity1", "name": "Entity 1", "type": "Person"}],
+ "relationships": [],
+ }
+ graph_v2 = {
+ "nodes": [
+ {"id": "entity1", "name": "Entity 1", "type": "Person"},
+ {"id": "entity2", "name": "Entity 2", "type": "Organization"},
+ ],
+ "edges": [],
+ }
+
+ manager.create_snapshot(graph_v1, "v1.0", "[email protected]", "Version 1")
+ manager.create_snapshot(graph_v2, "v2.0", "[email protected]", "Version 2")
+
+ diff = manager.compare_versions("v1.0", "v2.0")
+ assert diff["summary"]["entities_added"] == 1
+ assert diff["entities_added"][0]["id"] == "entity2"
+
class TestOntologyVersionManager:
"""Test cases for OntologyVersionManager."""