Skip to content

Commit ef1be90

Browse files
committed
Fix a hash instability.
Apparently, accessing __annotations__ on a function changes func_annotations from a tuple to a dict. These things hash differently, and so if you called Entrypoint or NotCompiled on a function you could modify its hash.
1 parent 28278a8 commit ef1be90

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

typed_python/CompilerVisibleObjectVisitor.hpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -594,10 +594,10 @@ class CompilerVisibleObjectVisitor {
594594
}
595595

596596
instanceVisit(f->func_name);
597-
instanceVisit(f->func_code);
598-
visitDictOrTuple(f->func_annotations);
599-
visitTuple(f->func_defaults);
600-
visitDictOrTuple(f->func_kwdefaults);
597+
instanceVisit(PyFunction_GetCode((PyObject*)f));
598+
visitDictOrTuple(PyFunction_GetAnnotations((PyObject*)f));
599+
visitTuple(PyFunction_GetDefaults((PyObject*)f));
600+
visitDictOrTuple(PyFunction_GetKwDefaults((PyObject*)f));
601601

602602
hashVisit(ShaHash(1));
603603

typed_python/type_identity_test.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
UInt64, UInt32,
1919
ListOf, TupleOf, Tuple, NamedTuple, Dict, OneOf, Forward, identityHash,
2020
Entrypoint, Class, Member, Final, TypeFunction, SerializationContext,
21-
Function
21+
Function, NotCompiled
2222
)
2323

2424
import typed_python
@@ -94,6 +94,24 @@ class C:
9494
resetCompilerVisibleObjectHashCache()
9595

9696

97+
def test_identity_of_function_with_annotation():
98+
def f(x: int):
99+
pass
100+
101+
@Entrypoint
102+
def g(x: int):
103+
return f(x)
104+
105+
identityHash(f)
106+
identityHash(NotCompiled(f))
107+
108+
hashInstability = checkForHashInstability()
109+
110+
if hashInstability is not None:
111+
print(hashInstability)
112+
raise Exception("hash instability found")
113+
114+
97115
def test_class_and_held_class_in_group():
98116
class C(Class):
99117
pass

0 commit comments

Comments
 (0)