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(explorer): type the dedup wire shape with a validated DuplicatePair model (#1635)
Nilay Mallik415dfc621f8d
diff --git a/semantica/explorer/routes/enrich.py b/semantica/explorer/routes/enrich.pyindex 491971a3..0b61bee3 100644--- a/semantica/explorer/routes/enrich.py+++ b/semantica/explorer/routes/enrich.py@@ -3,10 +3,12 @@ Enrichment and reasoning routes."""import asyncio+import loggingimport refrom typing import Dict, List, Optional, Tuplefrom fastapi import APIRouter, Depends, HTTPException+from pydantic import ValidationErrorfrom ..dependencies import get_sessionfrom ..schemas import (@@ -24,6 +26,7 @@ from ..schemas import (from ..session import GraphSessionrouter = APIRouter(tags=["Enrichment"])+logger = logging.getLogger(__name__)_FACT_RE = re.compile(r"^(?P<predicate>[A-Za-z_][\w:-]*)\((?P<args>.*)\)$")# SECURITY: Cap the candidate pool loaded by link prediction to prevent a@@ -52,27 +55,6 @@ def _safe_dict(obj) -> dict:return {"value": str(obj)}-def _dedup_pair(item: dict) -> dict:- """Map a duplicate pair to the shape the Entity Resolution tab parses.-- ``DuplicateDetector`` yields ``DuplicateCandidate`` fields (``entity1`` /- ``entity2`` / ``similarity_score``), but ``EntityResolutionTab.tsx`` reads- ``entity_a`` / ``entity_b`` / ``similarity|score``. Emit both so the UI- resolves ids/scores while any client on the old keys keeps working- (see issue #1585).- """- pair = dict(item)- if "entity_a" not in pair and "entity1" in pair:- pair["entity_a"] = pair["entity1"]- if "entity_b" not in pair and "entity2" in pair:- pair["entity_b"] = pair["entity2"]- if "similarity" not in pair and "similarity_score" in pair:- pair["similarity"] = pair["similarity_score"]- if "score" not in pair and "confidence" in pair:- pair["score"] = pair["confidence"]- return pair--def _parse_fact(fact: str) -> Optional[Tuple[str, List[str]]]:match = _FACT_RE.match((fact or "").strip())if not match:@@ -329,9 +311,24 @@ async def detect_duplicates(]duplicates = await asyncio.to_thread(detector.detect_duplicates, entities, threshold=body.threshold)duplicate_list = duplicates if isinstance(duplicates, list) else getattr(duplicates, "duplicates", [])- return DedupResponse(duplicates=[_dedup_pair(_safe_dict(item)) for item in duplicate_list], total_flagged=len(duplicate_list))+ # DuplicatePair normalizes the candidate keys to the shape the Entity+ # Resolution tab parses and validates that it is actually present.+ return DedupResponse(+ duplicates=[_safe_dict(item) for item in duplicate_list],+ total_flagged=len(duplicate_list),+ )except ImportError:raise HTTPException(status_code=503, detail="Deduplication module not available.")+ except ValidationError as exc:+ # A pair that carries neither the canonical nor the legacy spelling is+ # a server-side contract break (issue #1592), not a bad request. Fail+ # loudly here instead of shipping rows the UI renders as 0% with empty+ # ids, which is how #1585 went unnoticed.+ logger.exception("Dedup response violated the DuplicatePair contract")+ raise HTTPException(+ status_code=500,+ detail=f"Dedup response violated the DuplicatePair contract: {exc}",+ ) from excexcept Exception as exc:raise HTTPException(status_code=422, detail=f"Dedup scan failed: {exc}")diff --git a/semantica/explorer/schemas.py b/semantica/explorer/schemas.pyindex 30aa257f..2f7beec7 100644--- a/semantica/explorer/schemas.py+++ b/semantica/explorer/schemas.py@@ -3,9 +3,9 @@ Shared Pydantic schemas for the Semantica Knowledge Explorer API."""from datetime import datetime, timezone-from typing import Any, Dict, List, Literal, Optional, Tuple+from typing import Any, Dict, List, Literal, Optional, Tuple, Union-from pydantic import BaseModel, Field, field_validator+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validatorclass NodeResponse(BaseModel):@@ -220,8 +220,88 @@ class DedupRequest(BaseModel):threshold: float = Field(default=0.8, ge=0.0, le=1.0)+class DuplicatePair(BaseModel):+ """One flagged duplicate pair, in the shape the Entity Resolution tab reads.++ ``DuplicateDetector`` emits ``DuplicateCandidate`` fields (``entity1`` /+ ``entity2`` / ``similarity_score`` / ``confidence``), while+ ``EntityResolutionTab.tsx::parseDuplicates`` reads ``entity_a`` /+ ``entity_b`` / ``similarity``-or-``score``. Issue #1585 shipped because+ those key sets were disjoint and ``DedupResponse.duplicates`` was an+ untyped ``List[Dict[str, Any]]``, so nothing failed at the API boundary+ and the UI rendered empty ids with a 0% score bar.++ Both spellings travel on the wire: the canonical keys the UI parses are+ required, and their legacy twins are mirrored so clients written against+ the pre-#1586 shape keep resolving. A producer that emits neither+ spelling now fails validation loudly instead of silently degrading.++ Detector extras such as ``reasons`` and ``metadata`` pass through+ untouched via ``extra="allow"``.+ """++ model_config = ConfigDict(extra="allow")++ entity_a: Union[str, Dict[str, Any]]+ entity_b: Union[str, Dict[str, Any]]+ similarity: float+ score: float++ # Legacy DuplicateCandidate spellings, mirrored from the canonical keys+ # above so pre-#1586 consumers keep working.+ entity1: Optional[Union[str, Dict[str, Any]]] = None+ entity2: Optional[Union[str, Dict[str, Any]]] = None+ similarity_score: Optional[float] = None+ confidence: Optional[float] = None++ @model_validator(mode="before")+ @classmethod+ def _mirror_pair_aliases(cls, data: Any) -> Any:+ """Fill each canonical key from its legacy twin, and vice versa.++ Runs before field validation so a payload carrying either spelling+ satisfies the required canonical fields. A payload carrying neither+ leaves them unset and fails validation, which is the point.+ """+ if not isinstance(data, dict):+ return data++ pair = dict(data)++ def _coalesce(*keys: str) -> Any:+ for key in keys:+ value = pair.get(key)+ if value is not None:+ return value+ return None++ entity_a = _coalesce("entity_a", "entity1")+ entity_b = _coalesce("entity_b", "entity2")+ # ``similarity`` is the key the UI reads first and ``score`` its+ # fallback, so cross-fill between the two families: a producer that+ # emits only one of them still renders a real score bar. When both+ # are present each keeps its own value.+ similarity = _coalesce("similarity", "similarity_score", "score", "confidence")+ score = _coalesce("score", "confidence", "similarity", "similarity_score")++ for key, value in (+ ("entity_a", entity_a),+ ("entity1", entity_a),+ ("entity_b", entity_b),+ ("entity2", entity_b),+ ("similarity", similarity),+ ("similarity_score", similarity),+ ("score", score),+ ("confidence", score),+ ):+ if pair.get(key) is None and value is not None:+ pair[key] = value++ return pair++class DedupResponse(BaseModel):- duplicates: List[Dict[str, Any]] = Field(default_factory=list)+ duplicates: List[DuplicatePair] = Field(default_factory=list)total_flagged: int = 0diff --git a/tests/explorer/test_enrich_dedup_wire_shape.py b/tests/explorer/test_enrich_dedup_wire_shape.pyindex bd4e5b6c..a8c6833d 100644--- a/tests/explorer/test_enrich_dedup_wire_shape.py+++ b/tests/explorer/test_enrich_dedup_wire_shape.py@@ -1,4 +1,4 @@-"""Regression tests for issue #1585.+"""Regression tests for issues #1585 and #1592.``POST /api/enrich/dedup`` serialized ``DuplicateCandidate`` fields verbatim(``entity1``/``entity2``/``similarity_score``), but the Entity Resolution tab@@ -7,8 +7,14 @@every flagged pair rendered with empty ids and a 0% score bar, and mergePOSTed empty ids.-Each test below fails while the backend omits the frontend-facing keys and-passes once the route maps candidates to the agreed pair shape.+#1585 fixed the mapping; #1592 moves the contract into the schema. The+``DedupResponse.duplicates`` list is now typed as ``DuplicatePair`` instead of+``List[Dict[str, Any]]``, so a producer that drifts off both the canonical and+the legacy spelling fails validation at the API boundary rather than shipping+rows the UI renders as 0%.++The route tests below fail while the backend omits the frontend-facing keys;+the schema tests fail while the wire shape is an untyped dict."""import pytest@@ -18,9 +24,11 @@ import pytestpytest.importorskip("fastapi")from fastapi.testclient import TestClient # noqa: E402+from pydantic import ValidationError # noqa: E402from semantica.context.context_graph import ContextGraph # noqa: E402from semantica.explorer.app import create_app # noqa: E402+from semantica.explorer.schemas import DedupResponse, DuplicatePair # noqa: E402from semantica.explorer.session import GraphSession # noqa: E402@@ -107,3 +115,164 @@ def test_dedup_merge_round_trip():assert merge.status_code == 200, merge.textassert merge.json()["removed_ids"] == [duplicate_id]+++def test_dedup_route_preserves_detector_extras():+ """``reasons``/``metadata`` must survive the typed boundary (#1592).++ ``DuplicatePair`` sets ``extra="allow"`` precisely so that constraining+ the wire shape does not silently drop detector diagnostics.+ """+ with _client_with_duplicates() as client:+ response = client.post("/api/enrich/dedup", json={"threshold": 0.5})++ assert response.status_code == 200, response.text+ assert response.json()["duplicates"], "expected at least one flagged pair"+ for item in response.json()["duplicates"]:+ assert "reasons" in item, f"reasons dropped from {item}"+ assert "metadata" in item, f"metadata dropped from {item}"+++def test_dedup_route_rejects_drifted_pair_shape(monkeypatch):+ """A pair on neither spelling must fail loudly, not render as 0% (#1592).++ Before the typed response this returned 200 with unusable rows, which is+ exactly how #1585 reached users. The route now surfaces a contract error.+ """++ class _DriftedDetector:+ """Stands in for a future refactor that renames the pair fields."""++ def __init__(self, *args, **kwargs):+ pass++ def detect_duplicates(self, entities, **kwargs):+ return [{"left": "acme_inc", "right": "acme_corp", "sim": 0.95}]++ monkeypatch.setattr("semantica.deduplication.DuplicateDetector", _DriftedDetector)++ with _client_with_duplicates() as client:+ response = client.post("/api/enrich/dedup", json={"threshold": 0.5})++ assert response.status_code == 500, response.text+ assert "DuplicatePair" in response.json()["detail"]+++def test_duplicate_pair_accepts_detector_keys():+ """Legacy DuplicateCandidate keys in, both spellings out.++ ``DuplicateCandidate`` always carries both ``similarity_score`` and+ ``confidence`` as distinct values. The mirroring must map each to its own+ canonical twin without collapsing them.+ """+ pair = DuplicatePair.model_validate(+ {+ "entity1": {"id": "acme_inc", "text": "Acme Corporation"},+ "entity2": {"id": "acme_corp", "text": "Acme Corp"},+ "similarity_score": 0.91,+ "confidence": 0.87,+ }+ )+ dumped = pair.model_dump()++ assert dumped["entity_a"] == {"id": "acme_inc", "text": "Acme Corporation"}+ assert dumped["entity_b"] == {"id": "acme_corp", "text": "Acme Corp"}+ # Legacy keys stay on the wire for pre-#1586 clients.+ assert dumped["entity1"] == dumped["entity_a"]+ assert dumped["entity2"] == dumped["entity_b"]+ # similarity ← similarity_score, score ← confidence; they must stay distinct.+ assert dumped["similarity"] == 0.91+ assert dumped["similarity_score"] == 0.91+ assert dumped["score"] == 0.87+ assert dumped["confidence"] == 0.87+ assert dumped["similarity"] != dumped["score"]+++def test_duplicate_pair_accepts_canonical_keys_and_backfills_legacy():+ """Canonical keys in, legacy twins mirrored out."""+ pair = DuplicatePair.model_validate(+ {"entity_a": "acme_inc", "entity_b": "acme_corp", "similarity": 0.8}+ )+ dumped = pair.model_dump()++ assert dumped["entity1"] == "acme_inc"+ assert dumped["entity2"] == "acme_corp"+ assert dumped["similarity_score"] == 0.8+ # No confidence was supplied, so `score` falls back to the similarity+ # rather than leaving the UI with a 0% bar.+ assert dumped["score"] == 0.8+++def test_duplicate_pair_keeps_similarity_and_confidence_distinct():+ """Cross-filling must not collapse two genuinely different scores."""+ pair = DuplicatePair.model_validate(+ {+ "entity1": "a",+ "entity2": "b",+ "similarity_score": 0.95,+ "confidence": 0.60,+ }+ )++ assert pair.similarity == 0.95+ assert pair.score == 0.60+++def test_duplicate_pair_rejects_drifted_keys():+ """The core #1592 guarantee: unknown-only pair keys fail validation."""+ with pytest.raises(ValidationError) as excinfo:+ DuplicatePair.model_validate(+ {"left": "acme_inc", "right": "acme_corp", "sim": 0.95}+ )++ missing = {error["loc"][0] for error in excinfo.value.errors()}+ assert {"entity_a", "entity_b", "similarity"} <= missing+++def test_dedup_response_validates_nested_pairs():+ """``DedupResponse`` must reject a drifted pair, not accept any dict."""+ with pytest.raises(ValidationError):+ DedupResponse(duplicates=[{"left": "a", "right": "b"}], total_flagged=1)++ ok = DedupResponse(+ duplicates=[{"entity1": "a", "entity2": "b", "similarity_score": 0.9}],+ total_flagged=1,+ )+ assert ok.duplicates[0].entity_a == "a"+++def test_duplicate_pair_fills_score_from_similarity():+ """``score`` is required but falls back to ``similarity`` when absent.++ A producer that only emits ``similarity`` (no ``confidence`` / ``score``)+ must still yield a non-zero score bar in the UI. Both required float+ fields and every legacy twin must be populated from the single source.+ """+ pair = DuplicatePair.model_validate(+ {+ "entity_a": "a",+ "entity_b": "b",+ "similarity": 0.9,+ }+ )+ dumped = pair.model_dump()++ assert dumped["similarity"] == 0.9+ assert dumped["score"] == 0.9+ # Legacy twins must also be backfilled so pre-#1586 clients keep resolving.+ assert dumped["similarity_score"] == 0.9+ assert dumped["confidence"] == 0.9+++def test_duplicate_pair_rejects_missing_score_family():+ """A pair with valid entity fields but no score family must fail validation.++ Entities without any of similarity / similarity_score / score / confidence+ cannot produce a usable score bar, so they must not silently pass through+ as a 0% row — the validator must surface a ``ValidationError`` instead.+ """+ with pytest.raises(ValidationError) as excinfo:+ DuplicatePair.model_validate({"entity_a": "a", "entity_b": "b"})++ missing = {error["loc"][0] for error in excinfo.value.errors()}+ assert {"similarity", "score"} <= missing