Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

WIP: Foundation

ZohaibHassan16b1e5c9e3c9aa
diff --git a/semantica/change_management/change_log.py b/semantica/change_management/change_log.py
index 3e099a7b..772d65ed 100644
--- a/semantica/change_management/change_log.py
+++ b/semantica/change_management/change_log.py
@@ -9,12 +9,14 @@ Key Features:
- Email validation for authors
- Timestamp handling in ISO 8601 format
- Optional change linking and tracking
+ - Granular MutationRecord for per-entity audit trails
Main Classes:
- ChangeLogEntry: Standard metadata for version changes
+ - MutationRecord: Granular log of node/edge level changes
Example Usage:
- >>> from semantica.common.change_log import ChangeLogEntry
+ >>> from semantica.change_management.change_log import ChangeLogEntry
>>> entry = ChangeLogEntry(
... timestamp="2024-01-15T10:30:00Z",
... author="[email protected]",
@@ -28,7 +30,7 @@ License: MIT
import re
from dataclasses import dataclass, field
from datetime import datetime
-from typing import List, Optional
+from typing import List, Optional, Dict, Any
from ..utils.exceptions import ValidationError
@@ -106,3 +108,22 @@ class ChangeLogEntry:
change_id=change_id,
related_changes=related_changes or []
)
+
+
+@dataclass
+class MutationRecord:
+ """
+ Granular record of a single change to a graph entity (node or edge).
+
+ Attributes:
+ timestamp: ISO 8601 timestamp of the mutation
+ operation: 'ADD_NODE', 'UPDATE_NODE', 'REMOVE_NODE', 'ADD_EDGE', 'UPDATE_EDGE', 'REMOVE_EDGE'
+ entity_id: The ID of the affected node or edge
+ payload: The state of the entity after the mutation
+ version_label: Optional association with a specific saved snapshot version
+ """
+ timestamp: str
+ operation: str
+ entity_id: str
+ payload: Dict[str, Any]
+ version_label: Optional[str] = None
\ No newline at end of file
diff --git a/semantica/change_management/managers.py b/semantica/change_management/managers.py
index bbbdc74c..9984f971 100644
--- a/semantica/change_management/managers.py
+++ b/semantica/change_management/managers.py
@@ -377,6 +377,93 @@ class TemporalVersionManager(BaseVersionManager):
"pruned_versions": deleted_labels,
"retained_count": len(all_versions) - len(deleted_labels)
}
+
+ # Git-like audit trails
+
+ def attach_to_graph(self, graph: Any) -> None:
+ """
+ Attach this manager to a ContextGraph to enable mutation tracking.
+ Injects the mutation callback into the graph to capture all node/edge changes.
+ """
+ graph.mutation_callback = self.record_mutation
+ self.logger.info(f"Attached mutation tracking to graph: {getattr(graph, 'graph_id', 'unknown')}")
+
+ def record_mutation(self, operation: str, entity_id: str, payload: Dict[str, Any]) -> None:
+ """
+ Callback triggered by the graph to record granular mutations.
+ """
+ from .change_log import MutationRecord
+ record = MutationRecord(
+ timestamp=datetime.now().isoformat(),
+ operation=operation,
+ entity_id=entity_id,
+ payload=payload
+ )
+
+ mutation_dict = {
+ "timestamp": record.timestamp,
+ "operation": record.operation,
+ "entity_id": record.entity_id,
+ "payload": record.payload,
+ "version_label": record.version_label
+ }
+ self.storage.save_mutation(mutation_dict)
+ self.logger.debug(f"Recorded mutation: {operation} on {entity_id}")
+
+ def tag_version(self, version_label: str, tag_name: str) -> None:
+ """
+ Create a named tag (e.g., 'v1.0-approved') for a specific version.
+ """
+ if not self.storage.exists(version_label):
+ raise ValidationError(f"Cannot tag non-existent version: '{version_label}'")
+
+ self.storage.save_tag(tag_name, version_label)
+ self.logger.info(f"Tagged version '{version_label}' as '{tag_name}'")
+
+ def list_tags(self) -> Dict[str, str]:
+ """
+ Return a mapping of all tag names to their version labels.
+ """
+ return self.storage.list_tags()
+
+ def diff(self, version_a: str, version_b: str) -> Dict[str, Any]:
+ """
+ Git-like alias for compare_versions. Computes added/removed/modified entities.
+ """
+ return self.compare_versions(version_a, version_b)
+
+ def get_node_history(self, node_id: str) -> List[Dict[str, Any]]:
+ """
+ Retrieve the complete chronological mutation history for a specific node.
+ """
+ return self.storage.get_entity_history(node_id)
+
+ def restore_snapshot(self, graph: Any, target_version: str, require_confirmation: bool = True) -> bool:
+ """
+ Restore the graph to a specific version snapshot.
+
+ Args:
+ graph: The ContextGraph instance to restore.
+ target_version: The version label to restore to.
+ require_confirmation: If True, raises ProcessingError to prevent accidental data loss.
+ """
+ if require_confirmation:
+ raise ProcessingError(
+ "Rollback protection active. Explicitly set require_confirmation=False "
+ "to overwrite the current graph state."
+ )
+
+ snapshot = self.storage.get(target_version)
+ if not snapshot:
+ raise ValidationError(f"Version '{target_version}' not found in storage.")
+
+ self.logger.warning(f"Restoring graph to version '{target_version}' - clearing current state.")
+
+
+ graph.from_dict(snapshot)
+
+ self.logger.info(f"Successfully restored graph to version '{target_version}'.")
+ return True
diff --git a/semantica/change_management/version_storage.py b/semantica/change_management/version_storage.py
index 69767233..a71b94f1 100644
--- a/semantica/change_management/version_storage.py
+++ b/semantica/change_management/version_storage.py
@@ -10,6 +10,7 @@ Key Features:
- SQLite-based persistent storage implementation
- Checksum computation and validation
- Thread-safe operations
+ - Tagging and Granular Mutation Logging (Audit Trail)
Main Classes:
- VersionStorage: Abstract base class for storage backends
@@ -17,7 +18,7 @@ Main Classes:
- SQLiteVersionStorage: SQLite-based persistent storage
Example Usage:
- >>> from semantica.common.version_storage import SQLiteVersionStorage
+ >>> from semantica.change_management.version_storage import SQLiteVersionStorage
>>> storage = SQLiteVersionStorage("versions.db")
>>> storage.save(snapshot)
>>> versions = storage.list_all()
@@ -82,65 +83,53 @@ class VersionStorage(ABC):
@abstractmethod
def save(self, snapshot: Dict[str, Any]) -> None:
- """
- Save a version snapshot.
-
- Args:
- snapshot: Version snapshot dictionary with metadata
-
- Raises:
- ValidationError: If snapshot data is invalid
- ProcessingError: If save operation fails
- """
+ """Save a version snapshot."""
pass
@abstractmethod
def get(self, label: str) -> Optional[Dict[str, Any]]:
- """
- Retrieve a version snapshot by label.
-
- Args:
- label: Version label to retrieve
-
- Returns:
- Snapshot dictionary or None if not found
- """
+ """Retrieve a version snapshot by label."""
pass
@abstractmethod
def list_all(self) -> List[Dict[str, Any]]:
- """
- List all version snapshots.
-
- Returns:
- List of snapshot metadata dictionaries
- """
+ """List all version snapshots."""
pass
@abstractmethod
def exists(self, label: str) -> bool:
- """
- Check if a version exists.
+ """Check if a version exists."""
+ pass
- Args:
- label: Version label to check
+ @abstractmethod
+ def delete(self, label: str) -> bool:
+ """Delete a version snapshot."""
+ pass
- Returns:
- True if version exists, False otherwise
- """
+
+ @abstractmethod
+ def save_tag(self, tag_name: str, version_label: str) -> None:
+ """Save a named tag pointing to a specific version."""
pass
@abstractmethod
- def delete(self, label: str) -> bool:
- """
- Delete a version snapshot.
+ def get_tag(self, tag_name: str) -> Optional[str]:
+ """Retrieve the version label associated with a tag."""
+ pass
- Args:
- label: Version label to delete
+ @abstractmethod
+ def list_tags(self) -> Dict[str, str]:
+ """List all tags as a mapping of tag_name -> version_label."""
+ pass
- Returns:
- True if deleted, False if not found
- """
+ @abstractmethod
+ def save_mutation(self, mutation: Dict[str, Any]) -> None:
+ """Save a granular mutation record for the audit trail."""
+ pass
+
+ @abstractmethod
+ def get_entity_history(self, entity_id: str) -> List[Dict[str, Any]]:
+ """Retrieve the chronological mutation history for a specific entity."""
pass
@@ -155,6 +144,8 @@ class InMemoryVersionStorage(VersionStorage):
def __init__(self):
"""Initialize in-memory storage."""
self._storage: Dict[str, Dict[str, Any]] = {}
+ self._tags: Dict[str, str] = {}
+ self._mutations: List[Dict[str, Any]] = []
self._lock = threading.RLock()
self.logger = get_logger("in_memory_storage")
@@ -215,6 +206,26 @@ class InMemoryVersionStorage(VersionStorage):
return True
return False
+ def save_tag(self, tag_name: str, version_label: str) -> None:
+ with self._lock:
+ self._tags[tag_name] = version_label
+
+ def get_tag(self, tag_name: str) -> Optional[str]:
+ with self._lock:
+ return self._tags.get(tag_name)
+
+ def list_tags(self) -> Dict[str, str]:
+ with self._lock:
+ return self._tags.copy()
+
+ def save_mutation(self, mutation: Dict[str, Any]) -> None:
+ with self._lock:
+ self._mutations.append(json.loads(json.dumps(mutation)))
+
+ def get_entity_history(self, entity_id: str) -> List[Dict[str, Any]]:
+ with self._lock:
+ return [m for m in self._mutations if m.get("entity_id") == entity_id]
+
class SQLiteVersionStorage(VersionStorage):
"""
@@ -258,6 +269,23 @@ class SQLiteVersionStorage(VersionStorage):
created_at TEXT NOT NULL
)
""")
+
+ cursor.execute("""
+ CREATE TABLE IF NOT EXISTS version_tags (
+ tag_name TEXT PRIMARY KEY,
+ version_label TEXT NOT NULL
+ )
+ """)
+ cursor.execute("""
+ CREATE TABLE IF NOT EXISTS mutation_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ timestamp TEXT,
+ operation TEXT,
+ entity_id TEXT,
+ payload TEXT,
+ version_label TEXT
+ )
+ """)
conn.commit()
self.logger.debug(f"Initialized SQLite database at {self.storage_path}")
finally:
@@ -396,6 +424,103 @@ class SQLiteVersionStorage(VersionStorage):
finally:
conn.close()
+ def save_tag(self, tag_name: str, version_label: str) -> None:
+ with self._lock:
+ conn = sqlite3.connect(str(self.storage_path))
+ try:
+ cursor = conn.cursor()
+ cursor.execute(
+ """
+ INSERT OR REPLACE INTO version_tags (tag_name, version_label)
+ VALUES (?, ?)
+ """,
+ (tag_name, version_label)
+ )
+ conn.commit()
+ except sqlite3.Error as e:
+ raise ProcessingError(f"Failed to save tag: {e}")
+ finally:
+ conn.close()
+
+ def get_tag(self, tag_name: str) -> Optional[str]:
+ with self._lock:
+ conn = sqlite3.connect(str(self.storage_path))
+ try:
+ cursor = conn.cursor()
+ cursor.execute("SELECT version_label FROM version_tags WHERE tag_name = ?", (tag_name,))
+ row = cursor.fetchone()
+ return row[0] if row else None
+ except sqlite3.Error as e:
+ raise ProcessingError(f"Failed to get tag: {e}")
+ finally:
+ conn.close()
+
+ def list_tags(self) -> Dict[str, str]:
+ with self._lock:
+ conn = sqlite3.connect(str(self.storage_path))
+ try:
+ cursor = conn.cursor()
+ cursor.execute("SELECT tag_name, version_label FROM version_tags")
+ return {row[0]: row[1] for row in cursor.fetchall()}
+ except sqlite3.Error as e:
+ raise ProcessingError(f"Failed to list tags: {e}")
+ finally:
+ conn.close()
+
+ def save_mutation(self, mutation: Dict[str, Any]) -> None:
+ with self._lock:
+ conn = sqlite3.connect(str(self.storage_path))
+ try:
+ cursor = conn.cursor()
+ cursor.execute(
+ """
+ INSERT INTO mutation_log
+ (timestamp, operation, entity_id, payload, version_label)
+ VALUES (?, ?, ?, ?, ?)
+ """,
+ (
+ mutation.get("timestamp"),
+ mutation.get("operation"),
+ mutation.get("entity_id"),
+ json.dumps(mutation.get("payload", {})),
+ mutation.get("version_label")
+ )
+ )
+ conn.commit()
+ except sqlite3.Error as e:
+ raise ProcessingError(f"Failed to save mutation: {e}")
+ finally:
+ conn.close()
+
+ def get_entity_history(self, entity_id: str) -> List[Dict[str, Any]]:
+ with self._lock:
+ conn = sqlite3.connect(str(self.storage_path))
+ try:
+ cursor = conn.cursor()
+ cursor.execute(
+ """
+ SELECT timestamp, operation, entity_id, payload, version_label
+ FROM mutation_log
+ WHERE entity_id = ?
+ ORDER BY id ASC
+ """,
+ (entity_id,)
+ )
+ history = []
+ for row in cursor.fetchall():
+ history.append({
+ "timestamp": row[0],
+ "operation": row[1],
+ "entity_id": row[2],
+ "payload": json.loads(row[3]) if row[3] else {},
+ "version_label": row[4]
+ })
+ return history
+ except sqlite3.Error as e:
+ raise ProcessingError(f"Failed to get entity history: {e}")
+ finally:
+ conn.close()
+
def compute_checksum(data: Dict[str, Any]) -> str:
"""
@@ -431,4 +556,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
+ return stored_checksum == computed_checksum
\ No newline at end of file
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.py
index 6cae5ff9..6b43d544 100644
--- a/semantica/context/context_graph.py
+++ b/semantica/context/context_graph.py
@@ -299,6 +299,8 @@ class ContextGraph:
self.kg_components = {}
self._analytics_cache = {}
+ self.mutation_callback = self.config.get("mutation_callback", None)
+
enable_advanced = self.config.get("advanced_analytics", True)
if KG_AVAILABLE and enable_advanced:
@@ -453,6 +455,10 @@ class ContextGraph:
node.properties.update(attributes)
node.metadata.update(attributes)
+
+ if getattr(self, "mutation_callback", None):
+ self.mutation_callback("UPDATE_NODE", node_id, node.to_dict())
+
def get_edge_data(self, source_id: str, target_id: str) -> Dict[str, Any]:
for edge in self._adjacency.get(source_id, []):
if edge.target_id == target_id:
@@ -978,17 +984,20 @@ class ContextGraph:
def _add_internal_node(self, node: ContextNode) -> bool:
"""Internal method to add a node."""
self.nodes[node.node_id] = node
- # Handle edge case where node_type might be None or not a string
+
if hasattr(node, 'node_type') and isinstance(node.node_type, str):
self.node_type_index[node.node_type].add(node.node_id)
else:
- # Use 'unknown' as fallback for invalid node_type
self.node_type_index['unknown'].add(node.node_id)
- return True
+ if getattr(self, "mutation_callback", None):
+ self.mutation_callback("ADD_NODE", node.node_id, node.to_dict())
+
+ return True
+
def _add_internal_edge(self, edge: ContextEdge) -> bool:
"""Internal method to add an edge."""
- # Ensure nodes exist
+
if edge.source_id not in self.nodes:
self._add_internal_node(
ContextNode(edge.source_id, "entity", edge.source_id)
@@ -1001,6 +1010,11 @@ class ContextGraph:
self.edges.append(edge)
self.edge_type_index[edge.edge_type].append(edge)
self._adjacency[edge.source_id].append(edge)
+
+ if getattr(self, "mutation_callback", None):
+ edge_id = f"{edge.source_id}|{edge.edge_type}|{edge.target_id}"
+ self.mutation_callback("ADD_EDGE", edge_id, edge.to_dict())
+
return True
# --- Builder Methods (Legacy/Utility) ---