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): preserve entity_id aliases during entity merging (#1086)
Guofang.Tangb77e3e8c3cc3
diff --git a/semantica/deduplication/entity_merger.py b/semantica/deduplication/entity_merger.pyindex b19447cd..6552f8cd 100644--- a/semantica/deduplication/entity_merger.py+++ b/semantica/deduplication/entity_merger.py@@ -45,6 +45,7 @@ License: MITfrom dataclasses import dataclassfrom typing import Any, Dict, List, Optional, Union+from ..utils.entity_ids import get_entity_idfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker@@ -504,7 +505,7 @@ class EntityMerger:# Record source entitiesprovenance["merged_from"] = [{- "id": self._get_entity_value(e, "id"),+ "id": get_entity_id(e),"name": self._get_entity_value(e, "name"),"source": self._get_entity_value(e, "metadata", {}).get("source") if hasattr(e, "metadata") or isinstance(e, dict) else None,}diff --git a/semantica/deduplication/merge_strategy.py b/semantica/deduplication/merge_strategy.pyindex b5c2b29e..610aecb2 100644--- a/semantica/deduplication/merge_strategy.py+++ b/semantica/deduplication/merge_strategy.py@@ -45,6 +45,7 @@ from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union+from ..utils.entity_ids import get_entity_idfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker@@ -317,14 +318,20 @@ class MergeStrategyManager:message=f"Building merged entity... ({current_step}/{total_steps}, remaining: {remaining_steps} steps)")# Build merged entity+ merged_from = []+ for entity in entities:+ entity_id = get_entity_id(entity)+ if entity_id is not None:+ merged_from.append(entity_id)+merged_entity = {- "id": base_entity.get("id"),+ "id": get_entity_id(base_entity),"name": self._merge_top_level_field("name", entities, base_entity),"type": self._merge_top_level_field("type", entities, base_entity),"properties": merged_properties,"relationships": merged_relationships,"metadata": self._merge_metadata(entities, base_entity),- "merged_from": [e.get("id") for e in entities if e.get("id")],+ "merged_from": merged_from,"merge_strategy": strategy.value,}diff --git a/semantica/kg/entity_resolver.py b/semantica/kg/entity_resolver.pyindex a56c8cdd..06f4d299 100644--- a/semantica/kg/entity_resolver.py+++ b/semantica/kg/entity_resolver.py@@ -24,6 +24,7 @@ from typing import Any, Dict, List, Optionalfrom ..deduplication.duplicate_detector import DuplicateDetector, DuplicateGroupfrom ..deduplication.entity_merger import EntityMerger+from ..utils.entity_ids import get_entity_idfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker@@ -240,9 +241,7 @@ class EntityResolver:@staticmethoddef _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)+ return get_entity_id(entity)@staticmethoddef _get_entity_name(entity: Any) -> Optional[str]:@@ -279,13 +278,13 @@ class EntityResolver:processed_ids = set()for op in merge_operations:for source_entity in op.source_entities:- entity_id = source_entity.get("id") or source_entity.get("entity_id")- if entity_id:+ entity_id = get_entity_id(source_entity)+ if entity_id is not None:processed_ids.add(entity_id)for entity in entities:- entity_id = entity.get("id") or entity.get("entity_id")- if entity_id and entity_id not in processed_ids:+ entity_id = get_entity_id(entity)+ if entity_id is not None and entity_id not in processed_ids:merged_entities.append(entity)self.logger.info(f"Merged to {len(merged_entities)} entities")diff --git a/semantica/utils/entity_ids.py b/semantica/utils/entity_ids.pynew file mode 100644index 00000000..e33b965e--- /dev/null+++ b/semantica/utils/entity_ids.py@@ -0,0 +1,16 @@+"""Helpers for reading entity identifiers consistently across the KG pipeline."""++from typing import Any+++def get_entity_id(entity: Any) -> Any:+ """Return a truthy identifier from either supported entity ID field.++ The KG pipeline treats empty and otherwise falsy identifiers as missing.+ Prefer the canonical ``id`` field when it is populated, then fall back to+ the compatible ``entity_id`` alias.+ """+ if isinstance(entity, dict):+ return entity.get("id") or entity.get("entity_id") or None++ return getattr(entity, "id", None) or getattr(entity, "entity_id", None) or Nonediff --git a/tests/kg/test_entity_pipeline.py b/tests/kg/test_entity_pipeline.pyindex ec345286..7823ea1a 100644--- a/tests/kg/test_entity_pipeline.py+++ b/tests/kg/test_entity_pipeline.py@@ -1,9 +1,10 @@import pytest-from semantica.utils.types import Entityfrom semantica.kg.graph_builder import GraphBuilderfrom semantica.kg.entity_resolver import EntityResolverfrom semantica.kg.graph_analyzer import GraphAnalyzer+from semantica.utils.entity_ids import get_entity_id+from semantica.utils.types import Entitydef test_full_entity_pipeline():"""@@ -107,6 +108,60 @@ def test_direct_entity_objects_in_analyzer():print("Direct Entity objects test passed successfully!")++def test_entity_id_only_merge_remaps_relationship_endpoints():+ """Entity aliases must survive merging and relationship remapping."""+ builder = GraphBuilder(+ merge_entities=True,+ entity_resolution_strategy="exact",+ resolve_conflicts=False,+ )++ graph = builder.build(+ {+ "entities": [+ {"entity_id": "alice:1", "name": "Alice", "type": "Person"},+ {"entity_id": "alice:2", "name": " Alice ", "type": "Person"},+ {"entity_id": "org:1", "name": "Acme", "type": "Organization"},+ ],+ "relationships": [+ {+ "source_id": "alice:2",+ "target_id": "org:1",+ "type": "WORKS_FOR",+ }+ ],+ }+ )++ merged_alice = next(+ entity for entity in graph["entities"] if entity["name"] == "Alice"+ )+ relationship = graph["relationships"][0]+ entity_ids = {+ entity.get("id") or entity.get("entity_id") for entity in graph["entities"]+ }++ assert merged_alice["id"] == "alice:1"+ assert set(merged_alice["merged_from"]) == {"alice:1", "alice:2"}+ assert {+ item["id"] for item in merged_alice["metadata"]["provenance"]["merged_from"]+ } == {"alice:1", "alice:2"}+ assert relationship["source"] == "alice:1"+ assert relationship["target"] == "org:1"+ assert {relationship["source"], relationship["target"]} <= entity_ids+++def test_entity_id_helper_ignores_falsy_identifiers():+ """ID extraction must match the KG pipeline's falsy-ID contract."""+ assert get_entity_id({"id": "", "entity_id": "alias:1"}) == "alias:1"+ assert get_entity_id({"id": 0, "entity_id": "alias:2"}) == "alias:2"+ assert (+ get_entity_id({"id": "primary:1", "entity_id": "alias:3"})+ == "primary:1"+ )+ assert get_entity_id({"id": "", "entity_id": 0}) is None+if __name__ == "__main__":test_full_entity_pipeline()test_direct_entity_objects_in_analyzer()