Skip to content

Commit 51351e7

Browse files
committed
gh-157841: Test concurrent functools.partial mutation
Race __setstate__() against repr(), a call through both tp_call and vectorcall, __reduce__() and a nested partial(), and assert that a reader never combines the positional arguments of one state with the keywords of another. Every state the test installs carries the same value twice, once reachable as a positional argument and once as a keyword, so a torn read fails as a mismatch instead of only as a crash. test_concurrent_setstate_writers passes without the fix; it is there to guard the ordering of the displaced-value decrefs, not to reproduce a failure.
1 parent 1479169 commit 51351e7

1 file changed

Lines changed: 125 additions & 1 deletion

File tree

‎Lib/test/test_free_threading/test_functools.py‎

Lines changed: 125 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import random
2+
import sys
23
import unittest
34

4-
from functools import lru_cache
5+
from functools import Placeholder, lru_cache, partial
56
from threading import Barrier, Thread
67

78
from test.support import threading_helper
@@ -71,5 +72,128 @@ def test_reentrant_cache_clear_bounded(self):
7172
self._test_reentrant_cache_clear(maxsize=128)
7273

7374

75+
class Callable:
76+
# Instances have no vectorcall slot, so partial() dispatches them through
77+
# tp_call (partial_call) instead of partial_vectorcall.
78+
def __call__(self, x, y=0, *extra, z=0):
79+
return (x, y, z)
80+
81+
82+
def target(x, y=0, *extra, z=0):
83+
return (x, y, z)
84+
85+
86+
@threading_helper.requires_working_threading()
87+
class TestPartial(unittest.TestCase):
88+
# gh-157841: __setstate__() publishes func, args, keywords and the
89+
# placeholder count as four independent stores with no lock, so a reader
90+
# can observe a mixture of two states. Every state written below carries
91+
# the same value twice -- once reachable as a positional argument, once as
92+
# a keyword -- so a torn read shows up as a mismatch and not only as a
93+
# crash.
94+
95+
@staticmethod
96+
def state(i):
97+
if i % 2:
98+
# one placeholder, so the caller's argument supplies x
99+
return (target, (Placeholder, i), {"z": i}, None)
100+
return (target, (i, i), {"z": i}, None)
101+
102+
def check_coherent(self, p):
103+
x, y, z = p(0)
104+
self.assertEqual(y, z, "torn read: mixed the state of two setstate()s")
105+
106+
def check_reduce_coherent(self, p):
107+
(_, (func,), (func2, args, keywords, dict_)) = p.__reduce__()
108+
self.assertIs(func, func2)
109+
self.assertEqual(args[-1], keywords["z"],
110+
"torn read: mixed the state of two setstate()s")
111+
112+
def check_flatten_coherent(self, p):
113+
# partial_new() reaches inside p to flatten it, so it reads func, args,
114+
# keywords and the placeholder count out of a live, mutable object.
115+
x, y, z = partial(p, 3)()
116+
self.assertEqual(y, z, "torn read: mixed the state of two setstate()s")
117+
118+
def _test_racing_setstate(self, p, state, readers):
119+
num_threads = 10
120+
ops_per_thread = 1000
121+
old_interval = sys.getswitchinterval()
122+
sys.setswitchinterval(1e-6)
123+
self.addCleanup(sys.setswitchinterval, old_interval)
124+
125+
b = Barrier(num_threads)
126+
errors = []
127+
128+
def thread_func(n):
129+
b.wait()
130+
for j in range(ops_per_thread):
131+
i = j * num_threads + n
132+
try:
133+
if i % 5 == 0:
134+
p.__setstate__(state(i))
135+
else:
136+
readers[i % len(readers)](p)
137+
except Exception as exc:
138+
errors.append(f"{type(exc).__name__}: {exc}")
139+
140+
threads = [Thread(target=thread_func, args=(n,))
141+
for n in range(num_threads)]
142+
with threading_helper.start_threads(threads):
143+
pass
144+
145+
if errors:
146+
self.fail(f"{len(errors)} failures, first: {errors[0]}")
147+
p.__setstate__(state(-1))
148+
self.check_coherent(p)
149+
self.check_reduce_coherent(p)
150+
self.check_flatten_coherent(p)
151+
152+
def test_concurrent_setstate_and_reads(self):
153+
readers = [self.check_coherent, self.check_reduce_coherent,
154+
self.check_flatten_coherent, repr]
155+
# The starting state is itself coherent, so a reader that runs before
156+
# the first __setstate__() is not a false failure.
157+
self._test_racing_setstate(partial(target, 0, 0, z=0), self.state,
158+
readers)
159+
160+
def test_concurrent_setstate_and_reads_no_vectorcall(self):
161+
wrapped = Callable()
162+
163+
def state(i):
164+
func, args, keywords, dict_ = self.state(i)
165+
return (wrapped, args, keywords, dict_)
166+
167+
readers = [lambda p: p(0), self.check_reduce_coherent,
168+
self.check_flatten_coherent, repr]
169+
self._test_racing_setstate(partial(wrapped, 0, 0, z=0), state, readers)
170+
171+
def test_concurrent_setstate_writers(self):
172+
# Concurrent writers must not drop a displaced value's reference twice.
173+
num_threads = 10
174+
ops_per_thread = 1000
175+
b = Barrier(num_threads)
176+
p = partial(target, 0, 0, z=0)
177+
errors = []
178+
179+
def thread_func(n):
180+
b.wait()
181+
for j in range(ops_per_thread):
182+
try:
183+
p.__setstate__(self.state(j * num_threads + n))
184+
except Exception as exc:
185+
errors.append(f"{type(exc).__name__}: {exc}")
186+
187+
threads = [Thread(target=thread_func, args=(n,))
188+
for n in range(num_threads)]
189+
with threading_helper.start_threads(threads):
190+
pass
191+
192+
if errors:
193+
self.fail(f"{len(errors)} failures, first: {errors[0]}")
194+
self.check_coherent(p)
195+
self.check_reduce_coherent(p)
196+
197+
74198
if __name__ == "__main__":
75199
unittest.main()

0 commit comments

Comments
 (0)