uncle-lv
(Uncle Lv)
2026 年11 月 16 日 14:40
1
opened 01:54AM - 14 Nov 26 UTC
closed 09:06PM - 15 Nov 26 UTC
`Cache.memoize()` gives the same cache key to unequal integer arguments `-1` and… `-2`. After caching the first call, the second call returns the first argument's result without running the function. This also happens with `typed=True`; both arguments have the same type.
Reproduced on current master `3b0d5d13cacf1c32f3d043719234265e0945b6d5`, on Linux with CPython 3.10.12 and 3.14.9:
```python
from cacheout import Cache
for typed in (False, True):
calls = []
@Cache().memoize(typed=typed)
def echo(value):
calls.append(value)
return value
print(typed, echo.cache_key(-1) == echo.cache_key(-2))
print(echo(-1), echo(-2), calls)
print(echo.uncached(-2))
```
Output:
```text
False True
-1 -1 [-1]
-2
True True
-1 -1 [-1]
-2
```
Expected: the memoized second call returns `-2`, just as the uncached function does, and both distinct arguments are evaluated. A focused async-function reproduction gives the same wrong second result.
The key builder reduces each hashable argument to `hash(value)` before constructing the final string digest. On both tested runtimes, `hash(-1) == hash(-2) == -2`, so the distinct values are already lost before MD5 is applied. This does not require a custom `__hash__` implementation or an MD5 collision.
[PR #44](https://github.com/dgilland/cacheout/pull/44) fixed collisions between different argument partitions by preserving the boundaries between hashes. This is different: a single unequal argument pair has the same Python hash, even with those boundaries preserved.
No patch or assignment request is included. The public string-valued `cache_key` helper makes repair compatibility worth considering; no particular redesign is proposed here. The checks above are focused reproductions, not a full test-suite run or a production incident.
AI assistance was used for this investigation, reproduction and report.
我在处理这个issue时,发现CPython中,hash(-1)和hash(-2)的结果都是-2。
Python 3.13.14 (main, Jun 11 2026, 01:07:38) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
Ctrl click to launch VS Code Native REPL (https://aka.ms/python-native-repl)
>>> hash(-1)
-2
>>> hash(-2)
-2
我推测应该是因为C语言里一般使用返回值-1代表异常情况,但是CPython中hash方法 对简单数字是直接返回其值的。但又由于-1返回值代表异常情况,所以-1的哈希值被改写为了-2,-2的哈希值仍是-2。
没有任何文档说明这一行为。
虽然哈希允许发生碰撞,但是CPython实现中这个-1和-2直接碰撞,还是有点难绷 。
忍不住分享给大家。
1 个赞
uncle-lv
(Uncle Lv)
2026 年11 月 16 日 17:18
2
我使用AI进一步扫描了CPython的issue列表,实际上已经有官方成员做出过回应 了。
原因的确是根据惯例,C语言中,-1需要用于表示异常情况,所以对所有返回-1的hash值进行了替换。
也并非没有任何文档说明这一行为。官方文档的Hashing of numeric types 章节中,有说明这一行为。
CPython相关issue:
Python官方文档:
Stack Overflow相关问答:
1 个赞