Prevent dict key canonicalization

This commit is contained in:
xmarre 2026-03-16 17:06:09 +01:00
parent ce05e377a8
commit 6e3bd33665
2 changed files with 11 additions and 2 deletions

View File

@ -179,9 +179,9 @@ def _signature_to_hashable_impl(obj, depth=0, max_depth=_MAX_SIGNATURE_DEPTH, ac
ordered_items = []
for key, value in items:
key_result = _signature_to_hashable_impl(key, depth + 1, max_depth, active, memo, budget)
if key_result is _FAILED_SIGNATURE:
if type(key) not in _PRIMITIVE_SIGNATURE_TYPES:
return _FAILED_SIGNATURE
key_result = (key, _primitive_signature_sort_key(key))
value_result = _signature_to_hashable_impl(value, depth + 1, max_depth, active, memo, budget)
if value_result is _FAILED_SIGNATURE:
return _FAILED_SIGNATURE

View File

@ -282,6 +282,15 @@ def test_signature_to_hashable_fails_closed_for_ambiguous_dict_ordering(caching_
assert isinstance(sanitized, caching.Unhashable)
def test_signature_to_hashable_fails_closed_for_opaque_dict_key(caching_module):
"""Opaque dict keys should fail closed instead of being recursively canonicalized."""
caching, _ = caching_module
sanitized = caching._signature_to_hashable({_OpaqueValue(): 1})
assert isinstance(sanitized, caching.Unhashable)
def test_signature_to_hashable_fails_closed_on_dict_key_sort_collisions_even_with_distinct_values(caching_module, monkeypatch):
"""Different values must not mask dict key-sort collisions during canonicalization."""
caching, _ = caching_module