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(ontology): address quality gate review findings
T1mn6a55b8c3ee9d
diff --git a/semantica/kg/graph_validator.py b/semantica/kg/graph_validator.pyindex a24fd16e..77685c13 100644--- a/semantica/kg/graph_validator.py+++ b/semantica/kg/graph_validator.py@@ -301,7 +301,10 @@ class GraphValidator:code="ORPHAN_NODES",message=f"Found {len(isolates)} orphan nodes (no relationships).",severity=ValidationSeverity.WARNING,- details={"count": len(isolates), "ids": isolates[:10]} # Limit output+ details={+ "count": len(isolates),+ "ids": sorted(isolates, key=str)[:10],+ } # Limit output deterministically))except Exception as e:diff --git a/semantica/ontology/quality_gate.py b/semantica/ontology/quality_gate.pyindex 83596054..fa600c1b 100644--- a/semantica/ontology/quality_gate.py+++ b/semantica/ontology/quality_gate.py@@ -1,5 +1,6 @@"""Deterministic quality checks for ontology and KG pipelines."""+import mathfrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Dict, Iterable, List, Mapping, Optional, Set, Tuple@@ -198,6 +199,14 @@ class OntologyQualityGate:QualitySeverity.ERROR,element_type="ontology",)+ for message in getattr(validation, "warnings", []) or []:+ self._add_issue(+ issues,+ "VALIDATOR_WARNING",+ str(message),+ QualitySeverity.WARNING,+ element_type="ontology",+ )classes = self._read_collection(ontology, "classes", issues)properties = self._read_collection(ontology, "properties", issues)@@ -350,8 +359,11 @@ class OntologyQualityGate:"validator_valid": 1.0 if getattr(validation, "valid", True) else 0.0,}if competency_questions is not None:+ evaluation_ontology = self._prepare_for_evaluation(+ ontology, classes, properties+ )evaluation = self.evaluator.evaluate_ontology(- ontology, competency_questions=competency_questions+ evaluation_ontology, competency_questions=competency_questions)metrics["competency_question_coverage"] = evaluation.coverage_scoremetrics["completeness"] = evaluation.completeness_score@@ -468,12 +480,47 @@ class OntologyQualityGate:max_errors = float(thresholds.get("max_errors", 0.0) or 0.0)warning_value = thresholds.get("max_warnings")max_warnings = None if warning_value is None else float(warning_value)+ if not all(+ math.isfinite(value)+ for value in (min_coverage, max_errors)+ if value is not None+ ) or (max_warnings is not None and not math.isfinite(max_warnings)):+ raise ValueError("quality thresholds must be finite numbers")if not 0.0 <= min_coverage <= 1.0:raise ValueError("min_coverage must be between 0.0 and 1.0")if max_errors < 0 or (max_warnings is not None and max_warnings < 0):raise ValueError("error and warning thresholds cannot be negative")return min_coverage, max_errors, max_warnings+ @classmethod+ def _prepare_for_evaluation(+ cls,+ ontology: Dict[str, Any],+ classes: Iterable[Any],+ properties: Iterable[Any],+ ) -> Dict[str, Any]:+ """Make a shallow, evaluator-safe view without changing caller data."""+ prepared = dict(ontology)+ prepared["classes"] = [+ cls._prepare_element(element)+ for element in classes+ if isinstance(element, dict)+ ]+ prepared["properties"] = [+ cls._prepare_element(element)+ for element in properties+ if isinstance(element, dict)+ ]+ return prepared++ @classmethod+ def _prepare_element(cls, element: Dict[str, Any]) -> Dict[str, Any]:+ prepared = dict(element)+ identifier = cls._identifier(prepared)+ if identifier is not None and not str(prepared.get("name", "")).strip():+ prepared["name"] = identifier+ return prepared+@classmethoddef _read_collection(cls, ontology: Dict[str, Any], key: str, issues: List[QualityIssue]@@ -522,7 +569,10 @@ class OntologyQualityGate:)continueidentifiers.append(identifier)- for alias in cls._term_aliases(identifier):+ aliases_for_element: Set[str] = set()+ for candidate in cls._identifiers(element):+ aliases_for_element.update(cls._term_aliases(candidate))+ for alias in sorted(aliases_for_element):aliases.setdefault(alias, identifier)return aliases, identifiers@@ -537,7 +587,13 @@ class OntologyQualityGate:if not isinstance(class_entry, dict):continueidentifier = cls._identifier(class_entry)- for key in ("subClassOf", "parent", "superclass", "superclasses"):+ for key in (+ "subClassOf",+ "subclassOf",+ "parent",+ "superclass",+ "superclasses",+ ):parents = cls._values(class_entry, key)if parents and identifier:referenced.add(identifier)@@ -563,7 +619,8 @@ class OntologyQualityGate:@classmethoddef _check_graph(cls, graph: Dict[str, Any], issues: List[QualityIssue]) -> None:- result = GraphValidator().validate(graph)+ safe_graph = cls._prepare_graph_for_validation(graph, issues)+ result = GraphValidator().validate(safe_graph)code_map = {"DANGLING_EDGE": "UNRESOLVED_RELATIONSHIP_ENDPOINT","ORPHAN_NODES": "ORPHAN_ENTITY",@@ -578,6 +635,9 @@ class OntologyQualityGate:severity = severity_map.get(graph_issue.severity.value, QualitySeverity.ERROR)+ details = dict(graph_issue.details or {})+ if graph_issue.code == "ORPHAN_NODES" and "ids" in details:+ details["ids"] = sorted(details["ids"], key=str)cls._add_issue(issues,code_map.get(graph_issue.code, graph_issue.code),@@ -585,9 +645,47 @@ class OntologyQualityGate:severity,element_id=graph_issue.element_id,element_type=graph_issue.element_type,- details=graph_issue.details,+ details=details,)+ @classmethod+ def _prepare_graph_for_validation(+ cls, graph: Dict[str, Any], issues: List[QualityIssue]+ ) -> Dict[str, List[Dict[str, Any]]]:+ """Normalize supported graph aliases and isolate malformed members."""+ entities: List[Dict[str, Any]] = []+ for index, entity in enumerate(graph.get("entities", [])):+ if not isinstance(entity, dict):+ cls._add_issue(+ issues,+ "INVALID_ENTITY",+ f"Entity at index {index} must be a dictionary.",+ QualitySeverity.ERROR,+ element_type="entity",+ details={"index": index},+ )+ continue+ normalized = dict(entity)+ if not normalized.get("name") and normalized.get("text") is not None:+ normalized["name"] = normalized["text"]+ entities.append(normalized)++ relationships: List[Dict[str, Any]] = []+ for index, relationship in enumerate(graph.get("relationships", [])):+ if not isinstance(relationship, dict):+ cls._add_issue(+ issues,+ "INVALID_RELATIONSHIP",+ f"Relationship at index {index} must be a dictionary.",+ QualitySeverity.ERROR,+ element_type="relationship",+ details={"index": index},+ )+ continue+ relationships.append(dict(relationship))++ return {"entities": entities, "relationships": relationships}+@classmethoddef _read_graph(cls, graph: Optional[Dict[str, Any]], issues: List[QualityIssue]@@ -618,15 +716,21 @@ class OntologyQualityGate:@staticmethoddef _identifier(element: Any) -> Optional[str]:+ identifiers = OntologyQualityGate._identifiers(element)+ return identifiers[0] if identifiers else None++ @staticmethod+ def _identifiers(element: Any) -> List[str]:if isinstance(element, dict):+ values = []for key in ("name", "uri", "id", "@id"):value = element.get(key)if value is not None and str(value).strip():- return str(value).strip()- return None+ values.append(str(value).strip())+ return valuesif isinstance(element, str) and element.strip():- return element.strip()- return None+ return [element.strip()]+ return []@staticmethoddef _values(element: Dict[str, Any], key: str) -> List[Any]:@@ -634,7 +738,8 @@ class OntologyQualityGate:if value is None:return []if isinstance(value, (list, tuple, set)):- return [item for item in value if item is not None and str(item).strip()]+ values = [item for item in value if item is not None and str(item).strip()]+ return sorted(values, key=str) if isinstance(value, set) else valuesreturn [value] if str(value).strip() else []@classmethod@@ -658,7 +763,7 @@ class OntologyQualityGate:@classmethoddef _match_class(cls, value: Any, aliases: Mapping[str, str]) -> Optional[str]:- for alias in cls._term_aliases(value):+ for alias in sorted(cls._term_aliases(value)):if alias in aliases:return aliases[alias]return Nonediff --git a/tests/ontology/test_ontology_quality_gate.py b/tests/ontology/test_ontology_quality_gate.pyindex ef8d84be..6cfc21f4 100644--- a/tests/ontology/test_ontology_quality_gate.py+++ b/tests/ontology/test_ontology_quality_gate.py@@ -1,3 +1,7 @@+from types import SimpleNamespace++import pytest+from semantica.ontology import (OntologyEngine,OntologyQualityGate,@@ -111,3 +115,131 @@ def test_engine_exposes_quality_check():report = OntologyEngine().quality_check(_ontology())assert report.passed+++def test_quality_gate_accepts_canonical_context_graph_entities_without_mutation():+ graph = {+ "entities": [+ {"id": "p1", "text": "Alice", "type": "Person"},+ {"id": "c1", "text": "Acme", "type": "Company"},+ ],+ "relationships": [{"source_id": "p1", "target_id": "c1", "type": "worksFor"}],+ }++ report = OntologyQualityGate().check(_ontology(), graph_data=graph)++ assert report.passed+ assert "name" not in graph["entities"][0]+++def test_quality_gate_returns_structured_findings_for_malformed_graph_members():+ report = OntologyQualityGate().check(+ _ontology(), graph_data={"entities": [None], "relationships": [None]}+ )+ codes = {issue.code for issue in report.issues}++ assert not report.passed+ assert {"INVALID_ENTITY", "INVALID_RELATIONSHIP"} <= codes+++def test_quality_gate_indexes_all_class_identifier_aliases():+ ontology = {+ "classes": [{"name": "Person", "uri": "https://example.org/PersonType"}],+ "properties": [+ {+ "name": "name",+ "type": "data",+ "domain": "https://example.org/PersonType",+ "range": "string",+ }+ ],+ }++ report = OntologyQualityGate().check(ontology)+ codes = {issue.code for issue in report.issues}++ assert "UNKNOWN_DOMAIN" not in codes+++def test_quality_gate_recognizes_subclass_of_hierarchies():+ ontology = {+ "classes": [+ {"name": "Person"},+ {"name": "Employee", "subclassOf": "Person"},+ ],+ "properties": [+ {+ "name": "name",+ "type": "data",+ "domain": "Employee",+ "range": "string",+ }+ ],+ }++ report = OntologyQualityGate().check(ontology)++ assert not any(issue.code == "ORPHAN_CLASS" for issue in report.issues)+++def test_quality_gate_keeps_competency_evaluation_safe_for_malformed_members():+ ontology = {+ "classes": [None, {"uri": "https://example.org/Person"}],+ "properties": [+ None,+ {+ "uri": "https://example.org/name",+ "type": "data",+ "domain": "Person",+ "range": "string",+ },+ ],+ }++ report = OntologyQualityGate().check(+ ontology, competency_questions=["What is a person's name?"]+ )++ assert isinstance(report.metrics["competency_question_coverage"], float)+++def test_quality_gate_reports_validator_warnings_and_can_fail_on_them():+ class WarningValidator:+ def validate(self, ontology):+ return SimpleNamespace(valid=True, errors=[], warnings=["review me"])++ report = OntologyQualityGate(+ validator=WarningValidator(), fail_on_warnings=True+ ).check(_ontology())++ assert report.warning_count == 1+ assert "VALIDATOR_WARNING" in {issue.code for issue in report.issues}+ assert "fail_on_warnings" in report.threshold_failures+++def test_quality_gate_normalizes_orphan_ids_for_deterministic_reports():+ graph = {+ "entities": [+ {"id": "p2", "name": "Bob", "type": "Person"},+ {"id": "p1", "name": "Alice", "type": "Person"},+ ],+ "relationships": [],+ }++ report = OntologyQualityGate().check(_ontology(), graph_data=graph)+ orphan = next(issue for issue in report.issues if issue.code == "ORPHAN_ENTITY")++ assert orphan.details["ids"] == ["p1", "p2"]+++ "thresholds",+ [+ {"min_coverage": float("nan")},+ {"max_errors": float("inf")},+ {"max_warnings": float("-inf")},+ ],+)+def test_quality_gate_rejects_non_finite_thresholds(thresholds):+ with pytest.raises(ValueError, match="finite"):+ OntologyQualityGate().check(_ontology(), thresholds=thresholds)