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): promote synthetic relation endpoints into the graph (#1464)
Kevin1ec8de5d2581
diff --git a/semantica/kg/config.py b/semantica/kg/config.pyindex d7f7a065..12248ab8 100644--- a/semantica/kg/config.py+++ b/semantica/kg/config.py@@ -50,7 +50,14 @@ class KGConfig:"""Initialize configuration manager."""self.logger = get_logger("kg_config")self._configs: Dict[str, Any] = {}- self._method_configs: Dict[str, Dict] = {}+ self._method_configs: Dict[str, Dict] = {+ "build": {+ # How GraphBuilder treats a relationship endpoint that points at+ # an entity absent from the extracted set: "include" promotes a+ # synthetic UNKNOWN entity (default), "reject" drops the edge.+ "unknown_relation_endpoint": "include",+ },+ }self._load_config_file(config_file)self._load_env_vars()diff --git a/semantica/kg/graph_builder.py b/semantica/kg/graph_builder.pyindex 6fe5b45e..33745c7f 100644--- a/semantica/kg/graph_builder.py+++ b/semantica/kg/graph_builder.py@@ -23,7 +23,7 @@ License: MIT"""from datetime import datetime-from typing import Any, Dict, List, Optional, Tuple, Union+from typing import Any, Dict, List, Optional, Set, Tuple, Unionimport time@@ -89,7 +89,29 @@ class GraphBuilder:self.track_history = track_historyself.version_snapshots = version_snapshotsself.graph_store = graph_store- self.config = kwargs # Store additional config for extractors+ # The orchestrator builds with GraphBuilder(config=self.config.get("kg", {})).+ # That lands as a nested "config" keyword, so fold it into the option+ # mapping once here: every option ({entity_resolution,+ # conflict_detection, unknown_relation_endpoint, ...}) is then read the+ # same way whether it was given top-level or via the orchestrator path.+ kwargs = dict(kwargs)+ _nested = kwargs.pop("config", None)+ if isinstance(_nested, dict):+ for _key, _value in _nested.items():+ kwargs.setdefault(_key, _value)+ self.config = kwargs+ # unknown_relation_endpoint lives in the per-module build config+ # (semantica/kg/config.py); fall back to it so the option has a single+ # documented home. Popped out of kwargs so it is not forwarded to+ # extractors as an unused **config key.+ from .config import kg_config++ self.unknown_relation_endpoint = kwargs.pop(+ "unknown_relation_endpoint",+ kg_config.get_method_config("build").get(+ "unknown_relation_endpoint", "include"+ ),+ )# Extractors are reused across texts: NERExtractor loads its spaCy model# eagerly in __init__, so constructing one per text would reload the# model on every source in a multi-document build.@@ -102,6 +124,8 @@ class GraphBuilder:"extracted_relations": 0,"extracted_triplets": 0,}+ # Counts relationships dropped by the reject policy per build() call.+ self._rejected_relationships: int = 0# Initialize loggingfrom ..utils.logging import get_logger@@ -159,9 +183,81 @@ class GraphBuilder:}all_entities.append(entity_dict)elif hasattr(item, "subject") and hasattr(item, "predicate") and hasattr(item, "object"):- # It's likely a Relation object+ # It's likely a Relation or Triplet objectsubj = item.subjectobj = item.object+ # Relation extraction synthesizes an UNKNOWN Entity for an endpoint+ # that is absent from the NER entity list (metadata synthetic=True).+ # Triplet extraction does the same, but its endpoints are strings, so+ # the extractor records the absent endpoint texts instead. Only the+ # id/text survives in the relationship today, so the synthetic object+ # never reaches the entity collection and graph validation reports+ # DANGLING_EDGE. Promote those endpoint entities into the graph here.+ item_metadata = getattr(item, "metadata", None) or {}+ # Triplet LLM path tags endpoint texts it could not match to an entity.+ triplet_synthetic = [+ text+ for text in item_metadata.get("synthetic_endpoints", [])+ if isinstance(text, str)+ ]+ synthetic_endpoints = []+ for endpoint in (subj, obj):+ if (+ not isinstance(endpoint, str)+ and isinstance(getattr(endpoint, "metadata", None), dict)+ and endpoint.metadata.get("synthetic")+ ):+ synthetic_endpoints.append(endpoint)+ elif isinstance(endpoint, str) and endpoint in triplet_synthetic:+ synthetic_endpoints.append(endpoint)+ if synthetic_endpoints:+ endpoint_policy = self.unknown_relation_endpoint+ if endpoint_policy == "reject":+ self.logger.warning(+ "Dropping relationship %r->%r (%s): endpoint is synthetic and "+ "unknown_relation_endpoint='reject'",+ subj,+ obj,+ item.predicate,+ )+ self._rejected_relationships += 1+ return+ # The promoted set is rebuilt only for relationships that actually+ # carry a synthetic endpoint. Ordinary relationships (the common+ # case) must not pay an O(all_entities) scan per item, which made+ # build() quadratic on dense relation inputs.+ existing_ids: Set[Any] = set()+ for _ent in all_entities:+ if not isinstance(_ent, dict):+ continue+ for _key in ("id", "entity_id"):+ _cid = _ent.get(_key)+ if _cid is None:+ continue+ try:+ existing_ids.add(_cid)+ except TypeError:+ # Invalid/unhashable IDs are left for graph validation.+ continue+ for endpoint in synthetic_endpoints:+ if isinstance(endpoint, str):+ endpoint_id = endpoint+ endpoint_text = endpoint+ else:+ endpoint_id = endpoint.id if hasattr(endpoint, "id") else endpoint.text+ endpoint_text = endpoint.text+ if endpoint_id in existing_ids:+ continue+ all_entities.append(+ {+ "id": endpoint_id,+ "name": endpoint_text,+ "type": "UNKNOWN",+ "confidence": 0.8,+ "metadata": {"synthetic": True},+ }+ )+ existing_ids.add(endpoint_id)subj_id = getattr(subj, "id", getattr(subj, "text", str(subj))) if not isinstance(subj, str) else subjobj_id = getattr(obj, "id", getattr(obj, "text", str(obj))) if not isinstance(obj, str) else objrel_dict = {@@ -543,6 +639,8 @@ class GraphBuilder:"extracted_relations": 0,"extracted_triplets": 0}+ # Reset per-run rejection counter.+ self._rejected_relationships = 0tracking_id = self.progress_tracker.start_tracking(module="kg",@@ -782,6 +880,39 @@ class GraphBuilder:if has_merged_entities:self._remap_relationship_endpoints(resolved_entities, all_relationships)+ # When a synthetic endpoint is promoted before the real entity arrives+ # (e.g. relation data precedes NER entity data for the same text),+ # the same id can appear once as synthetic and once as real. Prefer+ # the real entity so the graph does not carry a duplicated,+ # lower-confidence duplicate.+ _real_ids: Set[Any] = set()+ for _entity in resolved_entities:+ if (+ isinstance(_entity, dict)+ and not (_entity.get("metadata") or {}).get("synthetic")+ ):+ for _cid in (_entity.get("id"), _entity.get("entity_id")):+ if _cid is None:+ continue+ try:+ _real_ids.add(_cid)+ except TypeError:+ # Invalid/unhashable IDs are left for graph validation+ # to report rather than failing graph construction here.+ continue+ if _real_ids:+ filtered = []+ for _entity in resolved_entities:+ if (+ isinstance(_entity, dict)+ and (_entity.get("metadata") or {}).get("synthetic")+ ):+ _eid = _entity.get("id")+ if _eid in _real_ids:+ continue+ filtered.append(_entity)+ resolved_entities = filtered+if input_relationships_count > 0 and len(all_relationships) == 0:warning_msg = (f"All relationships were dropped during graph building: "@@ -801,6 +932,7 @@ class GraphBuilder:"temporal_enabled": self.enable_temporal,"timestamp": self._get_timestamp(),"entity_resolution_applied": resolver_to_use is not None,+ "rejected_relationships": self._rejected_relationships,},}structure_time = time.time() - structure_startdiff --git a/semantica/kg/kg_usage.md b/semantica/kg/kg_usage.mdindex 47aaf234..7695d89d 100644--- a/semantica/kg/kg_usage.md+++ b/semantica/kg/kg_usage.md@@ -132,6 +132,53 @@ kg1 = builder.build(initial_sources)kg2 = builder.build(additional_sources)```+### Unknown relation endpoints++When a relationship endpoint names an entity that is absent from the extracted+entity set (for example an LLM/HuggingFace extraction that synthesizes an+endpoint), `GraphBuilder` promotes a synthetic `UNKNOWN` entity so the edge is+not left dangling. This is the default (`"include"`). To drop such+relationships instead, set `unknown_relation_endpoint="reject"`:++```python+builder = GraphBuilder(+ unknown_relation_endpoint="reject",+)+kg = builder.build(sources) # edges with unknown endpoints are dropped+```++Rejected relationships are observable at two levels:++- A **`WARNING`-level log** is emitted for every dropped edge, including the+ source/target and predicate, so it is visible without debug logging enabled.+- `graph["metadata"]["rejected_relationships"]` holds the count of edges+ dropped in that build call, giving callers a machine-readable signal:++```python+kg = builder.build(sources)+if kg["metadata"]["rejected_relationships"]:+ print(f"{kg['metadata']['rejected_relationships']} edge(s) were rejected "+ f"because of unknown endpoints.")+```++The option can also be set process-wide via the module's build configuration,+which is the documented home for it:++```python+from semantica.kg.config import kg_config++kg_config.set_method_config("build", unknown_relation_endpoint="reject")+# All subsequent GraphBuilder instances use "reject" as the default.+```++In a YAML/JSON/TOML config file, place it under the `kg_methods.build` key:++```yaml+kg_methods:+ build:+ unknown_relation_endpoint: reject+```+## Graph AlgorithmsThe knowledge graph module provides advanced algorithms for node embeddings, similarity calculations, path finding, link prediction, centrality measures, and community detection.diff --git a/semantica/semantic_extract/methods.py b/semantica/semantic_extract/methods.pyindex 00482df1..c38bcf88 100644--- a/semantica/semantic_extract/methods.py+++ b/semantica/semantic_extract/methods.py@@ -2316,7 +2316,7 @@ def extract_triplets_rules(def extract_triplets_huggingface(- text: str, model: str, device: Optional[str] = None, **kwargs+ text: str, model: str, device: Optional[str] = None, entities: Optional[List[Entity]] = None, **kwargs) -> List[Triplet]:"""HuggingFace triplet extraction."""loader = HuggingFaceModelLoader(device=device)@@ -2348,16 +2348,30 @@ def extract_triplets_huggingface(tail = match.group("tail").strip()if head and relation and tail:+ # Head/tail are raw decoded strings from the model. Tag any+ # that match no known entity so the GraphBuilder promotes+ # them instead of leaving a dangling edge (#1463).+ # TripletExtractor dispatches with entities=..., so this is+ # the real NER list here, not a dead comparison.+ hf_entities = entities or []+ synthetic_endpoints = [+ endpoint_text+ for endpoint_text in (head, tail)+ if not match_entity(endpoint_text, hf_entities)+ ]+ hf_metadata = {+ "model": model,+ "extraction_method": "huggingface_rebel",+ }+ if synthetic_endpoints:+ hf_metadata["synthetic_endpoints"] = synthetic_endpointstriplets.append(Triplet(subject=head,predicate=relation,object=tail,confidence=0.9, # Model generation doesn't provide per-triplet confidence- metadata={- "model": model,- "extraction_method": "huggingface_rebel"- }+ metadata=hf_metadata))@@ -2517,16 +2531,27 @@ Text to extract from:# Convert back to internal Triplet formattriplets = []for t_out in result_obj.triplets:+ # An LLM triple may reference an endpoint that does not match any+ # entity extracted by NER. Record those endpoints so the GraphBuilder+ # can promote them as synthetic entities instead of leaving a+ # dangling edge (see issue #1463).+ synthetic_endpoints = []+ for endpoint_text in (t_out.subject, t_out.object):+ if not match_entity(endpoint_text, entities or []):+ synthetic_endpoints.append(endpoint_text)+ metadata = {+ "provider": provider,+ "model": model,+ "extraction_method": "llm_typed",+ }+ if synthetic_endpoints:+ metadata["synthetic_endpoints"] = synthetic_endpointstriplets.append(Triplet(subject=t_out.subject,predicate=t_out.predicate,object=t_out.object,confidence=t_out.confidence,- metadata={- "provider": provider,- "model": model,- "extraction_method": "llm_typed"- }+ metadata=metadata,))logger.info(f"Successfully extracted {len(triplets)} triplets using {provider}/{model} (typed)")diff --git a/tests/kg/test_dangling_synthetic_endpoint.py b/tests/kg/test_dangling_synthetic_endpoint.pynew file mode 100644index 00000000..735c5731--- /dev/null+++ b/tests/kg/test_dangling_synthetic_endpoint.py@@ -0,0 +1,460 @@+"""Tests for reconciling synthetic relation endpoints into the graph.++Relation extraction synthesizes ``UNKNOWN`` entities for endpoints that are+absent from the NER entity list, but ``GraphBuilder._process_item`` kept only+the endpoint string. The resulting graph then failed ``GraphValidator`` with+``DANGLING_EDGE``. See issue #1463.+"""++import pytest++from semantica.kg import GraphBuilder, GraphValidator+from semantica.semantic_extract import Entity, Relation, Triplet+++def _known(text="Known Entity", label="CONCEPT"):+ return Entity(text=text, label=label, start_char=0, end_char=len(text))+++def _synthetic(text):+ return Entity(+ text=text,+ label="UNKNOWN",+ start_char=0,+ end_char=len(text),+ confidence=0.8,+ metadata={"synthetic": True},+ )+++def _rel(subject, predicate, object_):+ return Relation(subject=subject, predicate=predicate, object=object_)+++def _issues(graph):+ return GraphValidator().validate(graph).to_dict()["issues"]+++def test_single_missing_endpoint_promoted():+ graph = GraphBuilder(resolve_conflicts=False).build(+ [_known(), _rel(_known(), "related_to", _synthetic("Synthetic Entity"))],+ extract=False,+ )++ entity_ids = {e["id"] for e in graph["entities"]}+ assert "Synthetic Entity" in entity_ids+ assert not [i for i in _issues(graph) if i.get("code") == "DANGLING_EDGE"]+++def test_two_missing_endpoints_promoted():+ graph = GraphBuilder(resolve_conflicts=False).build(+ [_rel(_synthetic("Org A"), "related_to", _synthetic("Org B"))],+ extract=False,+ )++ entity_ids = {e["id"] for e in graph["entities"]}+ assert {"Org A", "Org B"} <= entity_ids+++def test_promoted_default_confidence_is_0_8():+ graph = GraphBuilder(resolve_conflicts=False).build(+ [_rel(_known(), "related_to", _synthetic("Synthetic Entity"))],+ extract=False,+ )++ synthetic = next(e for e in graph["entities"] if e["id"] == "Synthetic Entity")+ assert synthetic["confidence"] == 0.8+ assert synthetic["metadata"].get("synthetic") is True+ assert synthetic["type"] == "UNKNOWN"+ assert synthetic["name"] == "Synthetic Entity"+++def test_no_duplicate_when_endpoint_already_present():+ # A synthetic endpoint sharing an id with an existing entity must not+ # create a duplicate node.+ known = _known("Shared", label="CONCEPT")+ graph = GraphBuilder(resolve_conflicts=False).build(+ [known, _rel(known, "related_to", _synthetic("Shared"))],+ extract=False,+ )++ ids = [e["id"] for e in graph["entities"] if e["id"] == "Shared"]+ assert len(ids) == 1+++def test_merge_entities_true_no_dangling_edge():+ # With entity merging explicitly enabled (and conflict resolution on, the+ # default), a promoted synthetic endpoint still must not leave a dangling+ # edge and must not duplicate the existing entity.+ graph = GraphBuilder(merge_entities=True).build(+ [_known(), _rel(_known(), "related_to", _synthetic("Synthetic Entity"))],+ extract=False,+ )++ assert not [i for i in _issues(graph) if i.get("code") == "DANGLING_EDGE"]+ synthetic = [e for e in graph["entities"] if e["id"] == "Synthetic Entity"]+ assert len(synthetic) == 1+++def test_reject_policy_drops_dangling_relationship():+ builder = GraphBuilder(+ resolve_conflicts=False,+ unknown_relation_endpoint="reject",+ )+ graph = builder.build(+ [_rel(_known(), "related_to", _synthetic("Synthetic Entity"))],+ extract=False,+ )++ assert graph["relationships"] == []+ assert "Synthetic Entity" not in {e["id"] for e in graph["entities"]}+++def test_reject_policy_requires_config_to_promote():+ # Same input as test_reject_policy but policies must be explicit; only+ # "reject" disables promotion, the default remains permissive.+ default_builder = GraphBuilder(resolve_conflicts=False)+ graph = default_builder.build(+ [_rel(_known(), "related_to", _synthetic("Synthetic Entity"))],+ extract=False,+ )+ assert "Synthetic Entity" in {e["id"] for e in graph["entities"]}+++def test_dict_source_relationship_with_all_endpoints_present():+ # Non-synthetic dict relationships with a legitimate entity set are left+ # untouched; endpoints already resolve so no dangling edge appears.+ graph = GraphBuilder(resolve_conflicts=False).build(+ {+ "entities": [{"id": "Known Entity", "name": "Known Entity"}],+ "relationships": [+ {+ "source": "Known Entity",+ "target": "Known Entity",+ "type": "related_to",+ }+ ],+ },+ extract=False,+ )++ assert "Known Entity" in {e["id"] for e in graph["entities"]}+ assert not [i for i in _issues(graph) if i.get("code") == "DANGLING_EDGE"]+++def test_reject_policy_via_nested_config():+ # The orchestrator constructs GraphBuilder(config=self.config.get("kg", {})),+ # which lands as a nested "config" keyword. The policy lookup must read+ # through that nesting so the reject option works end to end.+ builder = GraphBuilder(+ resolve_conflicts=False,+ config={"unknown_relation_endpoint": "reject"},+ )+ graph = builder.build(+ [_rel(_known(), "related_to", _synthetic("Synthetic Entity"))],+ extract=False,+ )++ assert graph["relationships"] == []+ assert "Synthetic Entity" not in {e["id"] for e in graph["entities"]}+++def test_real_entity_wins_over_prior_synthetic():+ # A synthetic endpoint promoted early must yield to a real entity with the+ # same id that arrives later (e.g. relation data precedes NER entity data).+ graph = GraphBuilder(resolve_conflicts=False).build(+ [_rel(_synthetic("Shared"), "related_to", _known("Other"))],+ extract=False,+ )+ # Force a real "Shared" entity to coexist with the promoted synthetic one and+ # confirm only the real one survives.+ real_graph = GraphBuilder(resolve_conflicts=False).build(+ [+ _synthetic("Shared"),+ _known("Shared"),+ _rel(_synthetic("Shared"), "related_to", _known("Other")),+ ],+ extract=False,+ )++ shared = [e for e in real_graph["entities"] if e["id"] == "Shared"]+ assert len(shared) == 1+ assert shared[0]["metadata"].get("synthetic") is not True+++def test_triplet_with_synthetic_endpoint_promoted():+ # The LLM triplet path tags endpoint texts it could not match, and the+ # GraphBuilder promotes them as synthetic entities (issue #1463).+ triplet = Triplet(+ subject="Missing Subj",+ predicate="related_to",+ object="Known Target",+ )+ triplet.metadata = {"synthetic_endpoints": ["Missing Subj"]}+ graph = GraphBuilder(resolve_conflicts=False).build(+ [_known("Known Target"), triplet],+ extract=False,+ )++ entity_ids = {e["id"] for e in graph["entities"]}+ assert "Missing Subj" in entity_ids+ assert not [i for i in _issues(graph) if i.get("code") == "DANGLING_EDGE"]+++def test_synthetic_endpoint_deduped_against_entity_id():+ # A dict entity may carry its canonical id under "entity_id". A synthetic+ # endpoint promoted with the same id must not create a duplicate node.+ graph = GraphBuilder(resolve_conflicts=False).build(+ [+ {"entity_id": "Shared", "name": "Shared"},+ _rel(_synthetic("Shared"), "related_to", _known("Other")),+ ],+ extract=False,+ )++ ids = [+ e.get("id")+ for e in graph["entities"]+ if e.get("id") == "Shared" or e.get("entity_id") == "Shared"+ ]+ assert len(ids) == 1+++def test_dict_relationship_unknown_endpoint_untouched_by_design():+ # Dictionary-form relationships stay out of the synthetic reconcile path by+ # design; they have no synthetic marker so no entity is invented on their+ # behalf.+ graph = GraphBuilder(resolve_conflicts=False).build(+ {+ "entities": [{"id": "Known"}],+ "relationships": [+ {"source": "Known", "target": "Absent", "type": "related_to"}+ ],+ },+ extract=False,+ )++ ids = {e["id"] for e in graph["entities"]}+ assert "Known" in ids+ assert "Absent" not in ids+++def test_entity_with_none_metadata_does_not_crash_build():+ # An entity carrying an explicit metadata=None must not raise in the+ # synthetic-reconcile pass; .get("metadata", {}) returns None, not {}.+ src = {+ "entities": [+ {"id": "a", "name": "a", "metadata": None},+ {"id": "b", "name": "b"},+ ],+ "relationships": [{"source": "a", "target": "b", "type": "rel"}],+ }+ graph = GraphBuilder(resolve_conflicts=False).build(src, extract=False)++ ids = {e["id"] for e in graph["entities"]}+ assert {"a", "b"} <= ids+ assert graph["relationships"][0]["type"] == "rel"+++def test_reject_policy_via_orchestrator_shaped_config_fold():+ # The orchestrator builds with GraphBuilder(config=self.config.get("kg", {})),+ # so config= carries flat kg options. Folding that dict into the option+ # mapping must make reject effective and leave the nested+ # entity_resolution/conflict_detection options readable too.+ builder = GraphBuilder(+ config={+ "unknown_relation_endpoint": "reject",+ "entity_resolution": {"enabled": False},+ "conflict_detection": {"enabled": False},+ },+ )+ graph = builder.build(+ [_rel(_known(), "related_to", _synthetic("Synthetic Entity"))],+ extract=False,+ )++ assert graph["relationships"] == []+ assert "Synthetic Entity" not in {e["id"] for e in graph["entities"]}+++def test_real_entity_with_entity_id_only_wins_over_prior_synthetic():+ # A real entity that carries its canonical id under ``entity_id`` (no ``id``+ # field) must win the real-entity-wins dedup pass in build().+ # The dedup collects real ids via both ``id`` and ``entity_id``, so a+ # synthetic entity promoted with id='Shared' must be dropped when a real+ # dict entity with entity_id='Shared' (no 'id') arrives.+ graph = GraphBuilder(resolve_conflicts=False).build(+ [+ _rel(_synthetic("Shared"), "related_to", _known("Other")),+ _known("Other"),+ # real entity uses entity_id only — no 'id' key+ {"entity_id": "Shared", "name": "Shared Real"},+ ],+ extract=False,+ )++ shared = [+ e for e in graph["entities"]+ if e.get("id") == "Shared" or e.get("entity_id") == "Shared"+ ]+ assert len(shared) == 1+ # The real dict entity (entity_id-only) must survive, not the synthetic one.+ assert shared[0].get("entity_id") == "Shared"+ assert not (shared[0].get("metadata") or {}).get("synthetic")+++def test_llm_relation_synthetic_endpoints_promoted():+ # _parse_relation_result marks unmatched relation endpoints as synthetic+ # Entity objects (label=UNKNOWN, metadata={'synthetic': True}).+ # GraphBuilder must promote those entities and produce a clean graph.+ from semantica.semantic_extract.methods import _parse_relation_result+ from semantica.semantic_extract import Entity as SEEntity++ known_ent = SEEntity(text="Apple", label="ORG", start_char=0, end_char=5)+ parsed = {+ "relations": [+ {+ "subject": "Apple",+ "predicate": "founded_by",+ "object": "Steve Jobs",+ "confidence": 0.95,+ }+ ]+ }+ relations = _parse_relation_result(+ parsed,+ [known_ent],+ "Apple was founded by Steve Jobs.",+ "openai",+ "gpt-4",+ )+ assert len(relations) == 1+ assert relations[0].object.metadata.get("synthetic") is True++ graph = GraphBuilder(resolve_conflicts=False).build(+ [known_ent, relations[0]],+ extract=False,+ )++ entity_ids = {e["id"] for e in graph["entities"]}+ assert "Steve Jobs" in entity_ids+ assert not [i for i in _issues(graph) if i.get("code") == "DANGLING_EDGE"]+++def test_reject_policy_emits_warning_when_all_rels_dropped(caplog):+ # When reject drops every relationship from a dict-style source, the+ # build() 'all relationships dropped' warning must still fire (the+ # input_relationships_count accounts for the dict source's list length+ # before processing, so it sees the original count > 0).+ import logging++ builder = GraphBuilder(+ resolve_conflicts=False,+ unknown_relation_endpoint="reject",+ )+ rel = _rel(_known(), "related_to", _synthetic("S"))++ with caplog.at_level(logging.WARNING, logger="graph_builder"):+ graph = builder.build(+ {+ "entities": [{"id": "Known Entity", "name": "Known Entity"}],+ "relationships": [rel],+ },+ extract=False,+ )++ assert graph["relationships"] == []+ assert any(+ "All relationships were dropped" in record.message+ for record in caplog.records+ )+++# ---------------------------------------------------------------------------+# Observability of the reject policy (Qodo finding: "reject silently drops")+# ---------------------------------------------------------------------------++def test_reject_policy_count_in_metadata():+ # graph["metadata"]["rejected_relationships"] must equal the number of+ # relationships dropped by the reject policy so callers can observe the+ # outcome without parsing logs.+ builder = GraphBuilder(+ resolve_conflicts=False,+ unknown_relation_endpoint="reject",+ )+ graph = builder.build(+ [+ _known("A"),+ _known("B"),+ _rel(_known("A"), "clean", _known("B")), # kept+ _rel(_known("A"), "dirty1", _synthetic("S1")), # rejected+ _rel(_synthetic("S2"), "dirty2", _known("B")), # rejected+ ],+ extract=False,+ )++ assert graph["metadata"]["rejected_relationships"] == 2+ assert len(graph["relationships"]) == 1+ assert graph["relationships"][0]["type"] == "clean"+++def test_include_policy_rejected_count_is_zero():+ # With the default include policy the rejected count must be 0.+ graph = GraphBuilder(resolve_conflicts=False).build(+ [_known(), _rel(_known(), "r", _synthetic("S"))],+ extract=False,+ )+ assert graph["metadata"]["rejected_relationships"] == 0+++def test_reject_policy_emits_warning_log_per_dropped_edge(caplog):+ # Each dropped edge must produce a WARNING-level log entry (not just INFO).+ # This makes the rejection visible to callers who configure standard+ # WARNING-level logging without enabling DEBUG.+ import logging++ builder = GraphBuilder(+ resolve_conflicts=False,+ unknown_relation_endpoint="reject",+ )++ with caplog.at_level(logging.WARNING, logger="semantica.graph_builder"):+ graph = builder.build(+ [+ _known(),+ _rel(_known(), "dirty1", _synthetic("S1")),+ _rel(_known(), "dirty2", _synthetic("S2")),+ ],+ extract=False,+ )++ assert graph["relationships"] == []+ drop_records = [+ r for r in caplog.records+ if "Dropping relationship" in r.message and r.levelno == logging.WARNING+ ]+ assert len(drop_records) == 2, (+ f"Expected 2 WARNING drop records, got {len(drop_records)}: {[r.message for r in caplog.records]}"+ )+++def test_rejected_count_resets_between_build_calls():+ # _rejected_relationships must be reset at the start of each build() call+ # so successive builds on the same instance report independent counts.+ builder = GraphBuilder(+ resolve_conflicts=False,+ unknown_relation_endpoint="reject",+ )++ g1 = builder.build(+ [_known(), _rel(_known(), "r", _synthetic("S"))],+ extract=False,+ )+ assert g1["metadata"]["rejected_relationships"] == 1++ # Second build has no synthetic endpoints — count must be 0, not accumulated.+ g2 = builder.build(+ [_known("A"), _known("B"), _rel(_known("A"), "clean", _known("B"))],+ extract=False,+ )+ assert g2["metadata"]["rejected_relationships"] == 0