Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: implement ontology dif

ZohaibHassan16c842af65d0b1
diff --git a/docs/reference/change_management.md b/docs/reference/change_management.md
index 012072f9..d03df6da 100644
--- a/docs/reference/change_management.md
+++ b/docs/reference/change_management.md
@@ -391,3 +391,28 @@ prod_manager = TemporalVersionManager(
for version in prod_manager.list_versions():
print(f"{version['timestamp']}: {version['description']} by {version['author']}")
```
+
+---
+
+## Ontology Diff & Migration
+
+Semantica allows you to treat ontology schema changes with the same rigor as database migrations. By comparing two versions, you can generate a machine-readable diff and a structured impact report to catch breaking changes before they reach production.
+
+
+### Comparing Versions
+
+The `OntologyEngine` provides a high-level API to orchestrate the comparison of two schema versions.
+
+```python
+from semantica.ontology.engine import OntologyEngine
+
+engine = OntologyEngine()
+
+# Generate a migration impact report between v1.0 and v2.0
+report = engine.compare_versions(
+ base_id="v1.0",
+ target_id="v2.0"
+)
+
+print(f"Total changes detected: {report['summary']['total_changes']}")
+```
diff --git a/semantica/change_management/change_log.py b/semantica/change_management/change_log.py
index 3e099a7b..822f6928 100644
--- a/semantica/change_management/change_log.py
+++ b/semantica/change_management/change_log.py
@@ -28,7 +28,8 @@ License: MIT
import re
from dataclasses import dataclass, field
from datetime import datetime
-from typing import List, Optional
+from typing import List, Optional, Any, Dict, Tuple, Union, Set
+from enum import Enum
from ..utils.exceptions import ValidationError
@@ -106,3 +107,154 @@ class ChangeLogEntry:
change_id=change_id,
related_changes=related_changes or []
)
+
+class Severity(Enum):
+ CRITICAL = "critical"
+ HIGH = "high"
+ MEDIUM = "medium"
+ LOW = "low"
+ INFO = "info"
+
+class ChangeCategory(Enum):
+ BREAKING = "breaking"
+ POTENTIALLY_BREAKING = "potenitally_breaking"
+ NON_BREAKING = "non_breaking"
+ UNKNOWN = "unknown"
+
+@dataclass
+class ImpactReport:
+ """ Structured impact analysis report."""
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
+ summary: Dict[str, Any] = field(default_factory=dict)
+ breaking_changes: List[Dict[str, Any]] = field(default_factory=list)
+ potentially_breaking: List[Dict[str, Any]] = field(default_factory=list)
+ safe_changes: List[Dict[str, Any]] = field(default_factory=list)
+ recommendations: List[str] = field(default_factory=list)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "timestamp": self.timestamp,
+ "summary": self.summary,
+ "impact_classification": {
+ "breaking": self.breaking_changes,
+ "potentially_breaking": self.potentially_breaking,
+ "safe": self.safe_changes
+ },
+ "recommendations": self.recommendations
+ }
+
+class ChangeLogAnalyzer:
+ """
+ Analyzes ontology diffs and classifies impact severity.
+ """
+
+ VALIDITY_CONSTRAINTS = {'domain', 'range', 'cardinality', 'max_cardinality'}
+ STRUCTURAL_FIELDS = {'subclasses', 'superclasses', 'equivalent_to', 'disjoint_with'}
+
+ def __init__(self):
+ self.report = ImpactReport()
+
+ def analyze(self, diff: Dict[str, Any]) -> ImpactReport:
+ if not diff:
+ self.report.summary = {"error": "Empty diff provided"}
+ return self.report
+
+ all_changes = []
+
+ for key, entity_type, change_type in [
+ ("added_classes", "class", "added"), ("added_properties", "property", "added"),
+ ("removed_classes", "class", "removed"), ("removed_properties", "property", "removed"),
+ ("changed_classes", "class", "modified"), ("changed_properties", "property", "modified")
+ ]:
+ for item in diff.get(key, []):
+ all_changes.append({
+ "uri": item.get("uri", item.get("name", "unknown")),
+ "entity_type": entity_type,
+ "change_type": change_type,
+ "changes": item.get("changes", {})
+ })
+
+ self.report.summary = {"total_changes": len(all_changes)}
+
+ # Classify each change
+
+ for change in all_changes:
+ severity, category, description, mitigation = self._classify_change(change)
+ entry = {
+ "entity_uri": change['uri'],
+ "entity_type": change['entity_type'],
+ "change_type": change['change_type'],
+ "description": description,
+ "severity": severity.value,
+ "mitigation": mitigation
+ }
+
+ if category == ChangeCategory.BREAKING:
+ self.report.breaking_changes.append(entry)
+ elif category == ChangeCategory.POTENTIALLY_BREAKING:
+ self.report.potentially_breaking.append(entry)
+ else:
+ self.report.safe_changes.append(entry)
+
+ self._generate_recommendations()
+ return self.report
+
+
+ def _classify_change(self, change: Dict[str, Any]) -> Tuple[Severity, ChangeCategory, str, str]:
+ change_type = change.get('change_type')
+ entity_type = change.get('entity_type')
+ uri = change.get('uri')
+
+ if change_type == 'removed':
+ if entity_type == 'class':
+ return (Severity.CRITICAL, ChangeCategory.BREAKING, f"Class {uri} removed.", "Migrate orphaned instances.")
+ return (Severity.CRITICAL, ChangeCategory.BREAKING, f"Property {uri} removed.", "Migrate property values.")
+
+ if change_type == 'added':
+ return (Severity.INFO, ChangeCategory.NON_BREAKING, f"New{entity_type} {uri} added.", "No action required.")
+
+ if change_type == 'modified':
+ return self._analyze_field_changes(uri, change.get('changes', {}))
+
+ return (Severity.LOW, ChangeCategory.UNKNOWN, f"Unknown change for {uri}", "Manual review required.")
+
+ def _analyze_field_changes(self, uri: str, field_changes: Dict[str, Any]) -> Tuple[Severity, ChangeCategory, str, str]:
+ has_restriction = False
+ has_structural = False
+
+ for field, vals in field_changes.items():
+ if field in self.VALIDITY_CONSTRAINTS:
+ old_val, new_val = vals.get("old"), vals.get("new")
+
+ # if new constraint is smaller, it is a restriction
+ old_set = set(old_val) if isinstance(old_val, list) else {old_val}
+ new_set = set(new_val) if isinstance(new_val, list) else {new_val}
+
+ if new_set < old_set:
+ has_restriction = True
+
+ elif field in self.STRUCTURAL_FIELDS:
+ has_structural = True
+
+ if has_restriction:
+ return (Severity.HIGH, ChangeCategory.BREAKING, f"Domain/range restricted on {uri}", "Validate existing data against new constraints.")
+ if has_structural:
+ return (Severity.MEDIUM, ChangeCategory.POTENTIALLY_BREAKING, f"Hierarchy modified for {uri}", "Check dependent reasoning chains.")
+
+ return (Severity.LOW, ChangeCategory.NON_BREAKING, f"Safe annotations updated for {uri}", "No action required.")
+
+ def _generate_recommendations(self):
+ if self.report.breaking_changes:
+ self.report.recommendations.append("✘✘✘ BREAKING: Schedule downtime or validate existing data.")
+ if self.report.potentially_breaking:
+ self.report.recommendations.append("¤¤¤ POTENTIAL IMPACT: Run full regression tests on queries.")
+ if not self.report.breaking_changes and not self.report.potentially_breaking:
+ self.report.recommendations.append("☺☺☺ Safe Migration: Minor version bump sufficient.")
+
+
+
+
+def generate_change_report(diff: Dict[str, Any]) -> Dict[str, Any]:
+ """Public API for generating impact reports from diffs."""
+ analyzer = ChangeLogAnalyzer()
+ return analyzer.analyze(diff).to_dict()
\ No newline at end of file
diff --git a/semantica/change_management/ontology_version_manager.py b/semantica/change_management/ontology_version_manager.py
index 57cdbf98..19ee7f28 100644
--- a/semantica/change_management/ontology_version_manager.py
+++ b/semantica/change_management/ontology_version_manager.py
@@ -295,6 +295,84 @@ class VersionManager:
"axioms_removed": len(axioms_removed)
}
}
+
+ def diff_ontologies(self, base: Dict[str, Any], target: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Computes a structured diff between two ontology versions.
+ """
+ def _compute_section_diff(base_list, target_list):
+
+ base_map = {}
+ for item in base_list:
+ if isinstance(item, dict) and (item.get("uri") or item.get("name")):
+ base_map[item.get("uri", item.get("name"))] = item
+ elif isinstance(item, str):
+ base_map[item] = {"uri": item}
+
+ target_map = {}
+ for item in target_list:
+ if isinstance(item, dict) and (item.get("uri") or item.get("name")):
+ target_map[item.get("uri", item.get("name"))] = item
+ elif isinstance(item, str):
+ target_map[item] = {"uri": item}
+
+ added, removed, changed = [], [], []
+
+ # Find Added and Changed
+ for key, t_item in target_map.items():
+ if key not in base_map:
+ added.append(t_item)
+ else:
+ b_item = base_map[key]
+ changes = {}
+
+ all_fields = set(b_item.keys()).union(t_item.keys())
+ for field in all_fields:
+ if field in ["uri", "name"]:
+ continue
+
+ b_val = b_item.get(field)
+ t_val = t_item.get(field)
+
+ # Deep equality check for lists
+ if isinstance(b_val, list) and isinstance(t_val, list):
+ if set(str(x) for x in b_val) != set(str(x) for x in t_val):
+ changes[field] = {"old": b_val, "new": t_val}
+ elif b_val != t_val:
+ changes[field] = {"old": b_val, "new": t_val}
+
+ if changes:
+ changed.append({
+ "uri": t_item.get("uri", key),
+ "name": t_item.get("name", key),
+ "changes": changes
+ })
+
+ # Find deleted
+ for key, b_item in base_map.items():
+ if key not in target_map:
+ removed.append(b_item)
+
+ return added, removed, changed
+
+
+ classes_added, classes_removed, classes_changed = _compute_section_diff(
+ base.get("classes", []), target.get("classes", [])
+ )
+ props_added, props_removed, props_changed = _compute_section_diff(
+ base.get("properties", []), target.get("properties", [])
+ )
+
+ return {
+ "added_classes": classes_added,
+ "removed_classes": classes_removed,
+ "changed_classes": classes_changed,
+ "added_properties": props_added,
+ "removed_properties": props_removed,
+ "changed_properties": props_changed
+ }
+
+
def get_version(self, version: str) -> Optional[OntologyVersion]:
"""Get version by version string."""
diff --git a/semantica/ontology/engine.py b/semantica/ontology/engine.py
index 6635d03b..2a7b1b36 100644
--- a/semantica/ontology/engine.py
+++ b/semantica/ontology/engine.py
@@ -25,6 +25,10 @@ class OntologyEngine:
self.evaluator = OntologyEvaluator(**config)
self.validator = OntologyValidator(**config)
self.llm = LLMOntologyGenerator(**config)
+ self.store = config.get("store")
+
+ from ..change_management.ontology_version_manager import VersionManager
+ self.version_manager = config.get("version_manager") or VersionManager(**config)
def from_data(self, data: Dict[str, Any], **options) -> Dict[str, Any]:
tracking_id = self.progress.start_tracking(
@@ -68,4 +72,57 @@ class OntologyEngine:
def export_owl(self, ontology: Dict[str, Any], path: str, format: str = "turtle"):
return self.owl.export_owl(ontology, path, format=format)
-
+
+ def get_ontology_version_dict(self, version_id: str) -> Dict[str, Any]:
+ """ Utility to load an ontology version as plain dict ready for diffing."""
+
+ version_record = self.version_manager.get_version(version_id)
+ if not version_record:
+ raise ProcessingError(f"Version {version_id} not found.")
+
+ return version_record.metadata.get("structure", {"classes": [], "properties": []})
+
+ def compare_versions(self, base_id: str, target_id: str, **options) -> Dict[str, Any]:
+ """
+ Orchestrates version loading, diff computation, and report generation.
+
+ Args:
+ base_id: Version ID of the old ontology
+ target_id: Version ID of the new ontology
+ **options: Can pass 'base_dict' and 'target_dict' directly to bypass loading.
+
+ Returns:
+ A structured ImpactReport dictionary containing breaking/safe changes.
+ """
+
+ tracking_id = self.progress.start_tracking(
+ module="ontology",
+ submodule="OntologyEngine",
+ message=f"Comparing ontology versions: {base_id} -> {target_id}"
+ )
+
+ try:
+ from ..change_management.change_log import generate_change_report
+
+ base_dict = options.get("base_dict") or self.get_ontology_version_dict(base_id)
+ target_dict = options.get("target_dict") or self.get_ontology_version_dict(target_id)
+
+ diff_result = self.version_manager.diff_ontologies(base_dict, target_dict)
+
+ report = generate_change_report(diff_result)
+
+ if options.get("run_validation"):
+ self.progress.update_tracking(tracking_id, message="Running validation on target schema...")
+
+ validation_results = self.validate(target_dict, **options)
+
+ report["validation_results"] = validation_results
+
+ self.progress.stop_tracking(tracking_id, status="completed", message="Comparison complete")
+
+ return report
+
+ except Exception as e:
+ self.progress.stop_tracking(tracking_id, status="failed", message=str(e))
+ self.logger.error(f"Failed to compare versions: {e}")
+ raise ProcessingError(f"Version comparison failed: {e}")
\ No newline at end of file
diff --git a/tests/change_management/test_managers.py b/tests/change_management/test_managers.py
index 2adcf6fe..0205bbe7 100644
--- a/tests/change_management/test_managers.py
+++ b/tests/change_management/test_managers.py
@@ -1,3 +1,4 @@
+from semantica.change_management.ontology_version_manager import VersionManager
"""
Tests for Enhanced Version Managers
@@ -13,6 +14,8 @@ from semantica.change_management import (
OntologyVersionManager,
ChangeLogEntry
)
+from semantica.change_management.change_log import generate_change_report, ChangeLogAnalyzer
+from semantica.ontology.engine import OntologyEngine
from semantica.utils.exceptions import ValidationError, ProcessingError
@@ -330,3 +333,96 @@ class TestOntologyVersionManager:
finally:
if os.path.exists(db_path):
os.remove(db_path)
+
+
+ def test_diff_empty_ontologies(self):
+ """Test diffing entirely empty dictionaries."""
+ manager = VersionManager()
+ diff = manager.diff_ontologies({}, {})
+
+ assert len(diff["added_classes"]) == 0
+ assert len(diff["removed_classes"]) == 0
+ assert len(diff["changed_classes"]) == 0
+
+ def test_diff_unordered_list_equality(self):
+ """Test that list order doesn't trigger a false positive change."""
+ manager = VersionManager()
+ base = {"classes": [{"uri": "http://ex.org/C1", "domain": ["A", "B"]}]}
+ target = {"classes": [{"uri": "http://ex.org/C1", "domain": ["B", "A"]}]}
+
+ diff = manager.diff_ontologies(base, target)
+ assert len(diff["changed_classes"]) == 0
+
+ def test_diff_missing_uris(self):
+ """Tests whether missing URIs fallback to 'name' deterministically."""
+ manager = VersionManager()
+ base = {"classes": [{"name": "Person", "label": "Human"}]}
+ target = {"classes": [{"name": "Person", "label": "Homo Sapiens"}]}
+
+ diff = manager.diff_ontologies(base, target)
+ assert len(diff["changed_classes"]) == 1
+
+ change = diff["changed_classes"][0]
+ assert change["name"] == "Person"
+ assert change["changes"]["label"]["old"] == "Human"
+ assert change["changes"]["label"]["new"] == "Homo Sapiens"
+
+
+class TestChangeLogAnalyzer:
+ """Test cases for Impact Analysis & Reporting."""
+
+ def test_breaking_change_removed_class(self):
+ """Test that removing a class is flagged as CRITICAL/BREAKING."""
+ diff = {"removed_classes": [{"uri": "http://ex.org/Person"}]}
+ report = generate_change_report(diff)
+
+ assert len(report["impact_classification"]["breaking"]) == 1
+ assert report["impact_classification"]["breaking"][0]["severity"] == "critical"
+ assert "removed" in report["impact_classification"]["breaking"][0]["description"]
+
+ def test_breaking_change_narrowed_domain(self):
+ """Test that narrowing a domain is flagged as HIGH/BREAKING."""
+ diff = {
+ "changed_properties": [{
+ "uri": "http://ex.org/worksFor",
+ "changes": {"domain": {"old": ["Person", "Organization"], "new": ["Person"]}}
+ }]
+ }
+ report = generate_change_report(diff)
+
+ assert len(report["impact_classification"]["breaking"]) == 1
+ assert report["impact_classification"]["breaking"][0]["severity"] == "high"
+ assert "restricted" in report["impact_classification"]["breaking"][0]["description"]
+
+ def test_safe_change_added_class_and_label(self):
+ """Test that adding classes and changing annotations is SAFE."""
+ diff = {
+ "added_classes": [{"uri": "http://ex.org/NewClass"}],
+ "changed_properties": [{
+ "uri": "http://ex.org/name",
+ "changes": {"label": {"old": "Name", "new": "Full Name"}}
+ }]
+ }
+ report = generate_change_report(diff)
+
+ assert len(report["impact_classification"]["safe"]) == 2
+ assert len(report["impact_classification"]["breaking"]) == 0
+ assert len(report["impact_classification"]["potentially_breaking"]) == 0
+
+
+class TestOntologyEngineMigration:
+ """Test cases for Public API Orchestration."""
+
+ def test_compare_versions_with_dicts_override(self):
+ """Test for bypassing the DB fetch by passing dicts directly."""
+ engine = OntologyEngine()
+
+ base_dict = {"classes": [{"uri": "http://ex.org/C1", "label": "Old"}]}
+ target_dict = {"classes": [{"uri": "http://ex.org/C1", "label": "New"}]}
+
+ # We pass fake version IDs ("v1", "v2"), but the engine should use our dicts
+ report = engine.compare_versions("v1", "v2", base_dict=base_dict, target_dict=target_dict)
+
+ assert report["summary"]["total_changes"] == 1
+ assert len(report["impact_classification"]["safe"]) == 1
+ assert report["impact_classification"]["safe"][0]["entity_uri"] == "http://ex.org/C1"