Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(conflicts): resolve TypeError on unhashable values in voting/credibility strategies (#1208)

cxzg007d2902d3b0833
diff --git a/semantica/conflicts/conflict_resolver.py b/semantica/conflicts/conflict_resolver.py
index 48e26ea4..e1d85ea9 100644
--- a/semantica/conflicts/conflict_resolver.py
+++ b/semantica/conflicts/conflict_resolver.py
@@ -56,6 +56,7 @@ Author: Semantica Contributors
License: MIT
"""
+import json
from collections import Counter
from dataclasses import dataclass, field
from enum import Enum
@@ -67,6 +68,37 @@ from .conflict_detector import Conflict
from .source_tracker import SourceTracker
+def _hashable_key(value: Any) -> Any:
+ """Return a stable, hashable key for a conflicting value.
+
+ Conflicting values may be unhashable (e.g. ``dict`` or ``list``), which
+ breaks :class:`collections.Counter` and dict-key based aggregation used by
+ the voting and credibility-weighted strategies.
+
+ The ``"h"`` / ``"j"`` / ``"r"`` namespace tag is sufficient to prevent a
+ serialised unhashable structure from aliasing a hashable scalar: e.g. the
+ dict ``{"a": 1}`` gets key ``("j", '{"a": 1}')`` while the string
+ ``'{"a": 1}'`` gets key ``("h", '{"a": 1}')``, so they remain distinct.
+
+ Hashable values are wrapped only in the ``"h"`` tag without any type name,
+ which preserves Python's native equality semantics: values that compare
+ equal and share the same hash (e.g. ``1`` and ``1.0``, ``True`` and ``1``)
+ map to the same key and therefore aggregate together, exactly as they did
+ before this fix when ``Counter`` was used directly on hashable values.
+
+ Unhashable values are serialised to a stable JSON string under the ``"j"``
+ tag, falling back to ``repr()`` under the ``"r"`` tag when JSON fails.
+ """
+ try:
+ hash(value)
+ return ("h", value)
+ except TypeError:
+ try:
+ return ("j", json.dumps(value, sort_keys=True, default=str))
+ except (TypeError, ValueError):
+ return ("r", repr(value))
+
+
class ResolutionStrategy(str, Enum):
"""Conflict resolution strategy."""
@@ -361,9 +393,18 @@ class ConflictResolver:
resolution_notes="No conflicting values to resolve",
)
- # Count value occurrences
- value_counts = Counter(conflict.conflicting_values)
- most_common_value, count = value_counts.most_common(1)[0]
+ # Count value occurrences (using stable hashable keys so that
+ # unhashable values such as dict/list do not break Counter)
+ key_to_value: Dict[Any, Any] = {}
+ keys: List[Any] = []
+ for value in conflict.conflicting_values:
+ key = _hashable_key(value)
+ key_to_value.setdefault(key, value)
+ keys.append(key)
+
+ value_counts = Counter(keys)
+ most_common_key, count = value_counts.most_common(1)[0]
+ most_common_value = key_to_value[most_common_key]
# Calculate confidence based on vote ratio
total_votes = len(conflict.conflicting_values)
@@ -391,8 +432,10 @@ class ConflictResolver:
resolution_notes="Insufficient data for credibility-based resolution",
)
- # Weight values by source credibility
+ # Weight values by source credibility (keyed by stable hashable keys so
+ # that unhashable values such as dict/list can be used as map keys)
value_weights: Dict[Any, float] = {}
+ key_to_value: Dict[Any, Any] = {}
for i, value in enumerate(conflict.conflicting_values):
source = conflict.sources[i] if i < len(conflict.sources) else {}
@@ -402,9 +445,11 @@ class ConflictResolver:
weight = source_confidence * credibility
- if value not in value_weights:
- value_weights[value] = 0.0
- value_weights[value] += weight
+ key = _hashable_key(value)
+ key_to_value.setdefault(key, value)
+ if key not in value_weights:
+ value_weights[key] = 0.0
+ value_weights[key] += weight
# Get value with highest weight
if not value_weights:
@@ -414,10 +459,11 @@ class ConflictResolver:
resolution_notes="Could not calculate credibility weights",
)
- resolved_value = max(value_weights.items(), key=lambda x: x[1])[0]
+ resolved_key = max(value_weights.items(), key=lambda x: x[1])[0]
+ resolved_value = key_to_value[resolved_key]
total_weight = sum(value_weights.values())
confidence = (
- value_weights[resolved_value] / total_weight if total_weight > 0 else 0.0
+ value_weights[resolved_key] / total_weight if total_weight > 0 else 0.0
)
sources_used = [s.get("document", "unknown") for s in conflict.sources]
@@ -430,7 +476,7 @@ class ConflictResolver:
sources_used=sources_used,
resolution_notes=(
"Resolved by credibility-weighted voting "
- f"(weight: {value_weights[resolved_value]:.2f})"
+ f"(weight: {value_weights[resolved_key]:.2f})"
),
)
diff --git a/tests/conflicts/test_conflicts.py b/tests/conflicts/test_conflicts.py
index cf2e5e11..9427554a 100644
--- a/tests/conflicts/test_conflicts.py
+++ b/tests/conflicts/test_conflicts.py
@@ -1,3 +1,4 @@
+import json
import unittest
from datetime import datetime
from unittest.mock import MagicMock, patch
@@ -529,6 +530,154 @@ class TestConflictsModule(unittest.TestCase):
self.assertEqual(trends[0]["trend"], "insufficient_data")
self.assertEqual(trends[0]["conflict_count"], 1)
+ def test_resolve_by_voting_with_unhashable_values(self):
+ """Voting must handle unhashable values (dict/list) without crashing."""
+ resolver = ConflictResolver()
+
+ val_a = {"city": "New York", "zip": "10001"}
+ val_b = {"city": "Boston", "zip": "02101"}
+ conflict = Conflict(
+ conflict_id="c_unhashable_vote",
+ conflict_type=ConflictType.VALUE_CONFLICT,
+ entity_id="e1",
+ property_name="address",
+ conflicting_values=[val_a, val_a, val_b],
+ sources=[
+ {"document": "doc1", "confidence": 0.9},
+ {"document": "doc2", "confidence": 0.8},
+ {"document": "doc3", "confidence": 0.7},
+ ],
+ )
+
+ result = resolver.resolve_conflict(conflict, strategy="voting")
+ self.assertTrue(result.resolved)
+ # The majority value (val_a appears twice) must win and be returned
+ # as the original dict, not a stringified key.
+ self.assertEqual(result.resolved_value, val_a)
+ self.assertIsInstance(result.resolved_value, dict)
+
+ def test_resolve_by_credibility_with_unhashable_values(self):
+ """Credibility-weighted resolution must handle unhashable values."""
+ resolver = ConflictResolver()
+ resolver.source_tracker.set_source_credibility("doc_trusted", 1.0)
+ resolver.source_tracker.set_source_credibility("doc_flaky", 0.1)
+
+ val_a = ["tag1", "tag2"]
+ val_b = ["tag3"]
+ conflict = Conflict(
+ conflict_id="c_unhashable_cred",
+ conflict_type=ConflictType.VALUE_CONFLICT,
+ entity_id="e1",
+ property_name="tags",
+ conflicting_values=[val_a, val_a, val_b],
+ sources=[
+ {"document": "doc_flaky", "confidence": 0.9},
+ {"document": "doc_flaky", "confidence": 0.9},
+ {"document": "doc_trusted", "confidence": 0.9},
+ ],
+ )
+
+ result = resolver.resolve_conflict(conflict, strategy="credibility_weighted")
+ self.assertTrue(result.resolved)
+ # doc_trusted has far higher credibility, so val_b should win and be
+ # returned as the original list.
+ self.assertEqual(result.resolved_value, val_b)
+ self.assertIsInstance(result.resolved_value, list)
+
+ def test_voting_does_not_alias_struct_with_its_json_text(self):
+ """A dict and a string equal to its JSON text must not be merged.
+
+ Regression for PR #1208 review: type-tagged keys must keep a
+ serialized structure distinct from a scalar string that happens to
+ equal that serialization, so the majority string wins instead of the
+ single dict.
+ """
+ resolver = ConflictResolver()
+
+ struct = {"a": 1}
+ json_text = json.dumps(struct, sort_keys=True) # '{"a": 1}'
+ conflict = Conflict(
+ conflict_id="c_alias_vote",
+ conflict_type=ConflictType.VALUE_CONFLICT,
+ entity_id="e1",
+ property_name="payload",
+ conflicting_values=[struct, json_text, json_text],
+ sources=[
+ {"document": "doc1", "confidence": 0.9},
+ {"document": "doc2", "confidence": 0.8},
+ {"document": "doc3", "confidence": 0.7},
+ ],
+ )
+
+ result = resolver.resolve_conflict(conflict, strategy="voting")
+ self.assertTrue(result.resolved)
+ # The two identical json_text strings are the true majority; they must
+ # not be aliased with the dict.
+ self.assertEqual(result.resolved_value, json_text)
+ self.assertIsInstance(result.resolved_value, str)
+
+ def test_voting_aggregates_int_and_float_equal_values(self):
+ """1 and 1.0 must aggregate as the same voting value.
+
+ Python defines 1 == 1.0 and hash(1) == hash(1.0). The hashable-key
+ path must preserve this semantics so that a conflict containing both
+ int and float representations of the same number counts them together
+ rather than splitting them into separate buckets.
+ """
+ resolver = ConflictResolver()
+
+ conflict = Conflict(
+ conflict_id="c_int_float_vote",
+ conflict_type=ConflictType.VALUE_CONFLICT,
+ entity_id="e1",
+ property_name="score",
+ # 1 (int) and 1.0 (float) should merge → 3 votes vs 1 vote for 2
+ conflicting_values=[1, 1.0, 1, 2],
+ sources=[
+ {"document": "doc1", "confidence": 0.9},
+ {"document": "doc2", "confidence": 0.9},
+ {"document": "doc3", "confidence": 0.9},
+ {"document": "doc4", "confidence": 0.9},
+ ],
+ )
+
+ result = resolver.resolve_conflict(conflict, strategy="voting")
+ self.assertTrue(result.resolved)
+ # 1 and 1.0 are equal in Python; the merged bucket has 3 votes and wins
+ self.assertEqual(result.resolved_value, 1)
+ self.assertNotEqual(result.resolved_value, 2)
+
+ def test_voting_aggregates_bool_and_int_equal_values(self):
+ """True and 1 must aggregate as the same voting value.
+
+ Python defines True == 1 and hash(True) == hash(1). The hashable-key
+ path must preserve this semantics so that boolean True and integer 1
+ are treated as the same candidate rather than split across separate
+ buckets.
+ """
+ resolver = ConflictResolver()
+
+ conflict = Conflict(
+ conflict_id="c_bool_int_vote",
+ conflict_type=ConflictType.VALUE_CONFLICT,
+ entity_id="e1",
+ property_name="flag",
+ # True and 1 should merge → 3 votes vs 1 vote for False
+ conflicting_values=[True, 1, True, False],
+ sources=[
+ {"document": "doc1", "confidence": 0.9},
+ {"document": "doc2", "confidence": 0.9},
+ {"document": "doc3", "confidence": 0.9},
+ {"document": "doc4", "confidence": 0.9},
+ ],
+ )
+
+ result = resolver.resolve_conflict(conflict, strategy="voting")
+ self.assertTrue(result.resolved)
+ # True and 1 are equal in Python; the merged bucket has 3 votes and wins
+ self.assertTrue(result.resolved_value == 1) # True == 1 passes
+ self.assertNotEqual(result.resolved_value, False)
+
if __name__ == "__main__":
- unittest.main()
\ No newline at end of file
+ unittest.main()