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(kg): honor exact entity resolution (#1026)
Guofang.Tang17d878cbf3e9
diff --git a/semantica/kg/entity_resolver.py b/semantica/kg/entity_resolver.pyindex 62619862..a56c8cdd 100644--- a/semantica/kg/entity_resolver.py+++ b/semantica/kg/entity_resolver.py@@ -22,7 +22,7 @@ License: MITfrom typing import Any, Dict, List, Optional-from ..deduplication.duplicate_detector import DuplicateDetector+from ..deduplication.duplicate_detector import DuplicateDetector, DuplicateGroupfrom ..deduplication.entity_merger import EntityMergerfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker@@ -138,9 +138,7 @@ class EntityResolver:self.logger.debug(f"Detecting duplicate groups with threshold {self.similarity_threshold}")- duplicate_groups = self.duplicate_detector.detect_duplicate_groups(- entities, threshold=self.similarity_threshold- )+ duplicate_groups = self._detect_duplicate_groups(entities)self.logger.debug(f"Found {len(duplicate_groups)} duplicate group(s)")@@ -150,6 +148,7 @@ class EntityResolver:# Step 2: Merge duplicates in each groupmerged_entities = []processed_entity_ids = set() # Track which entities have been merged+ processed_entity_objects = set()for group in duplicate_groups:# Skip groups with less than 2 entities (not duplicates)@@ -157,9 +156,16 @@ class EntityResolver:continue# Merge the duplicate group into a single canonical entity- merge_operations = self.entity_merger.merge_duplicates(- group.entities, **self.config- )+ if self.resolution_strategy == "exact":+ merge_operations = [+ self.entity_merger.merge_entity_group(+ group.entities, **self.config+ )+ ]+ else:+ merge_operations = self.entity_merger.merge_duplicates(+ group.entities, **self.config+ )# Process each merge operationfor operation in merge_operations:@@ -168,30 +174,26 @@ class EntityResolver:# Mark all source entities as processedfor source_entity in operation.source_entities:- entity_id = (- source_entity.get("id")- if isinstance(source_entity, dict)- else getattr(source_entity, "id", None)- ) or (- source_entity.get("entity_id")- if isinstance(source_entity, dict)- else getattr(source_entity, "entity_id", None)- )- if entity_id:+ entity_id = self._get_entity_id(source_entity)+ if entity_id is None:+ processed_entity_objects.add(id(source_entity))+ continue+ try:processed_entity_ids.add(entity_id)+ except TypeError:+ processed_entity_objects.add(id(source_entity))# Step 3: Add non-duplicate entities (entities not in any duplicate group)for entity in entities:- entity_id = (- entity.get("id")- if isinstance(entity, dict)- else getattr(entity, "id", None)- ) or (- entity.get("entity_id")- if isinstance(entity, dict)- else getattr(entity, "entity_id", None)- )- if entity_id and entity_id not in processed_entity_ids:+ entity_id = self._get_entity_id(entity)+ if entity_id is None:+ is_unprocessed = id(entity) not in processed_entity_objects+ else:+ try:+ is_unprocessed = entity_id not in processed_entity_ids+ except TypeError:+ is_unprocessed = id(entity) not in processed_entity_objects+ if is_unprocessed:# This entity was not merged, add it as-ismerged_entities.append(entity)@@ -213,6 +215,50 @@ class EntityResolver:)raise+ def _detect_duplicate_groups(+ self, entities: List[Dict[str, Any]]+ ) -> List[DuplicateGroup]:+ """Detect duplicate groups according to the configured strategy."""+ if self.resolution_strategy != "exact":+ return self.duplicate_detector.detect_duplicate_groups(+ entities, threshold=self.similarity_threshold+ )++ groups = {}+ for entity in entities:+ name = self._get_entity_name(entity)+ normalized = str(name).strip() if name is not None else ""+ if normalized:+ groups.setdefault(normalized.casefold(), []).append(entity)++ return [+ DuplicateGroup(entities=group, confidence=1.0)+ for group in groups.values()+ if len(group) > 1+ ]++ @staticmethod+ def _get_entity_id(entity: Any) -> Any:+ """Return an entity ID while supporting dictionary and object inputs."""+ if isinstance(entity, dict):+ return entity.get("id") or entity.get("entity_id")+ return getattr(entity, "id", None) or getattr(entity, "entity_id", None)++ @staticmethod+ def _get_entity_name(entity: Any) -> Optional[str]:+ """Return an entity name, falling back to text-based entity input."""+ if isinstance(entity, dict):+ name = entity.get("name")+ return (+ name if name is not None and str(name).strip() else entity.get("text")+ )+ name = getattr(entity, "name", None)+ return (+ name+ if name is not None and str(name).strip()+ else getattr(entity, "text", None)+ )+def merge_duplicates(self, entities: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Merge duplicate entities.diff --git a/tests/kg/test_entity_resolver_exact.py b/tests/kg/test_entity_resolver_exact.pynew file mode 100644index 00000000..dfb73fb6--- /dev/null+++ b/tests/kg/test_entity_resolver_exact.py@@ -0,0 +1,56 @@+from semantica.kg.entity_resolver import EntityResolver+++def test_exact_resolution_does_not_merge_similar_names():+ entities = [+ {"id": "1", "name": "Alice"},+ {"id": "2", "name": "Alicia"},+ ]++ resolved = EntityResolver(strategy="exact").resolve_entities(entities)++ assert {entity["id"] for entity in resolved} == {"1", "2"}+++def test_exact_resolution_merges_case_and_whitespace_variants():+ entities = [+ {"id": "1", "name": " Alice "},+ {"id": "2", "name": "alice"},+ ]++ resolved = EntityResolver(strategy="exact").resolve_entities(entities)++ assert len(resolved) == 1+++def test_resolution_preserves_non_duplicate_entities_without_ids():+ entities = [+ {"name": "Alice"},+ {"name": "Bob"},+ ]++ resolved = EntityResolver(strategy="exact").resolve_entities(entities)++ assert resolved == entities+++def test_exact_resolution_does_not_merge_whitespace_only_names():+ entities = [+ {"id": "1", "name": " "},+ {"id": "2", "name": "\t"},+ ]++ resolved = EntityResolver(strategy="exact").resolve_entities(entities)++ assert {entity["id"] for entity in resolved} == {"1", "2"}+++def test_exact_resolution_falls_back_to_text_when_name_is_blank():+ entities = [+ {"id": "1", "name": " ", "text": "Alice"},+ {"id": "2", "name": "Alice"},+ ]++ resolved = EntityResolver(strategy="exact").resolve_entities(entities)++ assert len(resolved) == 1