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): resolve endpoints in direct property inference (#1229)
Guofang.Tangfb69b033bef2
diff --git a/semantica/ontology/ontology_generator.py b/semantica/ontology/ontology_generator.pyindex 73c73a5f..baa4035b 100644--- a/semantica/ontology/ontology_generator.py+++ b/semantica/ontology/ontology_generator.py@@ -43,6 +43,11 @@ from .class_inferrer import ClassInferrerfrom .namespace_manager import NamespaceManagerfrom .naming_conventions import NamingConventionsfrom .property_generator import PropertyGenerator+from .relationship_utils import (+ build_entity_aliases,+ get_relationship_endpoint,+ resolve_relationship_endpoint_type,+)from .ontology_validator import OntologyValidator@@ -383,56 +388,18 @@ class OntologyGenerator:@staticmethoddef _build_entity_aliases(entities: List[Dict[str, Any]]) -> Dict[str, set]:"""Build an unambiguous alias-to-type index for relationship endpoints."""- aliases: Dict[str, set] = {}- for entity in entities:- entity_type = entity.get("type") or entity.get("entity_type")- if not entity_type:- continue-- for key in ("id", "entity_id", "name", "text", "label"):- if key not in entity or entity[key] is None or entity[key] == "":- continue- aliases.setdefault(str(entity[key]), set()).add(entity_type)-- return aliases+ return build_entity_aliases(entities)@staticmethoddef _get_relationship_endpoint(rel: Dict[str, Any], endpoint: str) -> Any:"""Return an endpoint value from either ID or legacy relationship fields."""- for key in (f"{endpoint}_id", endpoint):- if key not in rel:- continue-- value = rel[key]- if value is None or value == "":- continue- if isinstance(value, dict):- for alias_key in ("id", "entity_id", "name", "text", "label"):- if alias_key not in value:- continue- alias_value = value[alias_key]- if alias_value is not None and alias_value != "":- return alias_value- continue- return value-- return None+ return get_relationship_endpoint(rel, endpoint)def _resolve_relationship_endpoint_type(self, rel: Dict[str, Any], endpoint: str, aliases: Dict[str, set]) -> Optional[str]:"""Resolve an endpoint type without treating missing fields as aliases."""- explicit_type = rel.get(f"{endpoint}_type")- if explicit_type and explicit_type != "Entity":- return explicit_type-- endpoint_value = self._get_relationship_endpoint(rel, endpoint)- if endpoint_value is not None:- candidates = aliases.get(str(endpoint_value), set())- if len(candidates) == 1:- return next(iter(candidates))-- return explicit_type+ return resolve_relationship_endpoint_type(rel, endpoint, aliases)def _stage2_yaml_to_definition(self, semantic_network: Dict[str, Any], **optionsdiff --git a/semantica/ontology/property_generator.py b/semantica/ontology/property_generator.pyindex fdc36c96..f90bf739 100644--- a/semantica/ontology/property_generator.py+++ b/semantica/ontology/property_generator.py@@ -34,6 +34,7 @@ from ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_trackerfrom .naming_conventions import NamingConventions+from .relationship_utils import build_entity_aliases, resolve_relationship_endpoint_typeclass PropertyGenerator:@@ -106,7 +107,7 @@ class PropertyGenerator:tracking_id, message="Inferring object properties from relationships...")object_properties = self._infer_object_properties(- relationships, classes, **options+ relationships, classes, entities=entities, **options)properties.extend(object_properties)@@ -136,6 +137,7 @@ class PropertyGenerator:self,relationships: List[Dict[str, Any]],classes: List[Dict[str, Any]],+ entities: Optional[List[Dict[str, Any]]] = None,**options,) -> List[Dict[str, Any]]:"""Infer object properties from relationships."""@@ -147,6 +149,7 @@ class PropertyGenerator:# Create class mapclass_map = {cls["name"]: cls for cls in classes}+ entity_aliases = build_entity_aliases(entities or [])properties = []for rel_type, rels in rel_types.items():@@ -156,12 +159,12 @@ class PropertyGenerator:ranges = set()for rel in rels:- source_type = rel.get(- "source_type"- ) or self._infer_class_from_entity(rel.get("source_id"), classes)- target_type = rel.get(- "target_type"- ) or self._infer_class_from_entity(rel.get("target_id"), classes)+ source_type = resolve_relationship_endpoint_type(+ rel, "source", entity_aliases+ )+ target_type = resolve_relationship_endpoint_type(+ rel, "target", entity_aliases+ )if source_type:domains.add(source_type)diff --git a/semantica/ontology/relationship_utils.py b/semantica/ontology/relationship_utils.pynew file mode 100644index 00000000..46d7afef--- /dev/null+++ b/semantica/ontology/relationship_utils.py@@ -0,0 +1,58 @@+"""Shared helpers for resolving ontology relationship endpoints."""++from typing import Any, Dict, List, Optional, Set+++def build_entity_aliases(entities: List[Dict[str, Any]]) -> Dict[str, Set[str]]:+ """Build an alias-to-type index for relationship endpoints."""+ aliases: Dict[str, Set[str]] = {}+ for entity in entities:+ entity_type = entity.get("type") or entity.get("entity_type")+ if not entity_type:+ continue++ for key in ("id", "entity_id", "name", "text", "label"):+ if key not in entity or entity[key] is None or entity[key] == "":+ continue+ aliases.setdefault(str(entity[key]), set()).add(str(entity_type))++ return aliases+++def get_relationship_endpoint(rel: Dict[str, Any], endpoint: str) -> Any:+ """Return an endpoint value from either ID or legacy relationship fields."""+ for key in (f"{endpoint}_id", endpoint):+ if key not in rel:+ continue++ value = rel[key]+ if value is None or value == "":+ continue+ if isinstance(value, dict):+ for alias_key in ("id", "entity_id", "name", "text", "label"):+ if alias_key not in value:+ continue+ alias_value = value[alias_key]+ if alias_value is not None and alias_value != "":+ return alias_value+ continue+ return value++ return None+++def resolve_relationship_endpoint_type(+ rel: Dict[str, Any], endpoint: str, aliases: Dict[str, Set[str]]+) -> Optional[str]:+ """Resolve an endpoint type without treating missing fields as aliases."""+ explicit_type = rel.get(f"{endpoint}_type")+ if explicit_type and explicit_type != "Entity":+ return str(explicit_type)++ endpoint_value = get_relationship_endpoint(rel, endpoint)+ if endpoint_value is not None:+ candidates = aliases.get(str(endpoint_value), set())+ if len(candidates) == 1:+ return next(iter(candidates))++ return str(explicit_type) if explicit_type else Nonediff --git a/tests/ontology/test_ontology_relationship_endpoints.py b/tests/ontology/test_ontology_relationship_endpoints.pyindex a1251daf..c81cf9e9 100644--- a/tests/ontology/test_ontology_relationship_endpoints.py+++ b/tests/ontology/test_ontology_relationship_endpoints.py@@ -96,3 +96,29 @@ def test_nested_endpoint_alias_skips_empty_id_and_uses_name():works_for = _object_property(ontology, "worksFor")assert works_for["domain"] == ["Person"]assert works_for["range"] == ["Organization"]+++def test_public_infer_properties_resolves_id_endpoints():+ data = {+ "entities": [+ {"id": "p1", "type": "Person", "name": "Alice"},+ {"id": "p2", "type": "Person", "name": "Bob"},+ {"id": "o1", "type": "Organization", "name": "Acme"},+ {"id": "o2", "type": "Organization", "name": "Beta"},+ ],+ "relationships": [+ {"source_id": "p1", "target_id": "o1", "type": "works_for"},+ {"source_id": "p2", "target_id": "o2", "type": "works_for"},+ ],+ }+ generator = OntologyGenerator()+ classes = generator.infer_classes(data)++ works_for = next(+ prop+ for prop in generator.infer_properties(data, classes)+ if prop["name"] == "worksFor"+ )++ assert works_for["domain"] == ["Person"]+ assert works_for["range"] == ["Organization"]