Debian Codegraph @

Lib/test/test_concurrent_futures/test_process_pool.py

raw
1 import os
2 import sys
3 import threading
4 import time
5 import unittest
6 from concurrent import futures
7 from concurrent.futures.process import BrokenProcessPool
8
9 from test import support
10 from test.support import hashlib_helper
11
12 from .executor import ExecutorTest, mul
13 from .util import (
14 ProcessPoolForkMixin, ProcessPoolForkserverMixin, ProcessPoolSpawnMixin,
15 create_executor_tests, setup_module)
16
17
18 class EventfulGCObj():
19 def __init__(self, mgr):
20 self.event = mgr.Event()
21
22 def __del__(self):
23 self.event.set()
24
25
26 class ProcessPoolExecutorTest(ExecutorTest):
27
28 @unittest.skipUnless(sys.platform=='win32', 'Windows-only process limit')
29 def test_max_workers_too_large(self):
30 with self.assertRaisesRegex(ValueError,
31 "max_workers must be <= 61"):
32 futures.ProcessPoolExecutor(max_workers=62)
33
34 def test_killed_child(self):
35 # When a child process is abruptly terminated, the whole pool gets
36 # "broken".
37 futures = [self.executor.submit(time.sleep, 3)]
38 # Get one of the processes, and terminate (kill) it
39 p = next(iter(self.executor._processes.values()))
40 p.terminate()
41 for fut in futures:
42 self.assertRaises(BrokenProcessPool, fut.result)
43 # Submitting other jobs fails as well.
44 self.assertRaises(BrokenProcessPool, self.executor.submit, pow, 2, 8)
45
46 def test_map_chunksize(self):
47 def bad_map():
48 list(self.executor.map(pow, range(40), range(40), chunksize=-1))
49
50 ref = list(map(pow, range(40), range(40)))
51 self.assertEqual(
52 list(self.executor.map(pow, range(40), range(40), chunksize=6)),
53 ref)
54 self.assertEqual(
55 list(self.executor.map(pow, range(40), range(40), chunksize=50)),
56 ref)
57 self.assertEqual(
58 list(self.executor.map(pow, range(40), range(40), chunksize=40)),
59 ref)
60 self.assertRaises(ValueError, bad_map)
61
62 @classmethod
63 def _test_traceback(cls):
64 raise RuntimeError(123) # some comment
65
66 def test_traceback(self):
67 # We want ensure that the traceback from the child process is
68 # contained in the traceback raised in the main process.
69 future = self.executor.submit(self._test_traceback)
70 with self.assertRaises(Exception) as cm:
71 future.result()
72
73 exc = cm.exception
74 self.assertIs(type(exc), RuntimeError)
75 self.assertEqual(exc.args, (123,))
76 cause = exc.__cause__
77 self.assertIs(type(cause), futures.process._RemoteTraceback)
78 self.assertIn('raise RuntimeError(123) # some comment', cause.tb)
79
80 with support.captured_stderr() as f1:
81 try:
82 raise exc
83 except RuntimeError:
84 sys.excepthook(*sys.exc_info())
85 self.assertIn('raise RuntimeError(123) # some comment',
86 f1.getvalue())
87
88 @hashlib_helper.requires_hashdigest('md5')
89 def test_ressources_gced_in_workers(self):
90 # Ensure that argument for a job are correctly gc-ed after the job
91 # is finished
92 mgr = self.get_context().Manager()
93 obj = EventfulGCObj(mgr)
94 future = self.executor.submit(id, obj)
95 future.result()
96
97 self.assertTrue(obj.event.wait(timeout=1))
98
99 # explicitly destroy the object to ensure that EventfulGCObj.__del__()
100 # is called while manager is still running.
101 support.gc_collect()
102 obj = None
103 support.gc_collect()
104
105 mgr.shutdown()
106 mgr.join()
107
108 def test_saturation(self):
109 executor = self.executor
110 mp_context = self.get_context()
111 sem = mp_context.Semaphore(0)
112 job_count = 15 * executor._max_workers
113 for _ in range(job_count):
114 executor.submit(sem.acquire)
115 self.assertEqual(len(executor._processes), executor._max_workers)
116 for _ in range(job_count):
117 sem.release()
118
119 @support.requires_gil_enabled("gh-117344: test is flaky without the GIL")
120 def test_idle_process_reuse_one(self):
121 executor = self.executor
122 assert executor._max_workers >= 4
123 if self.get_context().get_start_method(allow_none=False) == "fork":
124 raise unittest.SkipTest("Incompatible with the fork start method.")
125 executor.submit(mul, 21, 2).result()
126 executor.submit(mul, 6, 7).result()
127 executor.submit(mul, 3, 14).result()
128 self.assertEqual(len(executor._processes), 1)
129
130 def test_idle_process_reuse_multiple(self):
131 executor = self.executor
132 assert executor._max_workers <= 5
133 if self.get_context().get_start_method(allow_none=False) == "fork":
134 raise unittest.SkipTest("Incompatible with the fork start method.")
135 executor.submit(mul, 12, 7).result()
136 executor.submit(mul, 33, 25)
137 executor.submit(mul, 25, 26).result()
138 executor.submit(mul, 18, 29)
139 executor.submit(mul, 1, 2).result()
140 executor.submit(mul, 0, 9)
141 self.assertLessEqual(len(executor._processes), 3)
142 executor.shutdown()
143
144 def test_max_tasks_per_child(self):
145 context = self.get_context()
146 if context.get_start_method(allow_none=False) == "fork":
147 with self.assertRaises(ValueError):
148 self.executor_type(1, mp_context=context, max_tasks_per_child=3)
149 return
150 # not using self.executor as we need to control construction.
151 # arguably this could go in another class w/o that mixin.
152 executor = self.executor_type(
153 1, mp_context=context, max_tasks_per_child=3)
154 f1 = executor.submit(os.getpid)
155 original_pid = f1.result()
156 # The worker pid remains the same as the worker could be reused
157 f2 = executor.submit(os.getpid)
158 self.assertEqual(f2.result(), original_pid)
159 self.assertEqual(len(executor._processes), 1)
160 f3 = executor.submit(os.getpid)
161 self.assertEqual(f3.result(), original_pid)
162
163 # A new worker is spawned, with a statistically different pid,
164 # while the previous was reaped.
165 f4 = executor.submit(os.getpid)
166 new_pid = f4.result()
167 self.assertNotEqual(original_pid, new_pid)
168 self.assertEqual(len(executor._processes), 1)
169
170 executor.shutdown()
171
172 def test_max_tasks_per_child_defaults_to_spawn_context(self):
173 # not using self.executor as we need to control construction.
174 # arguably this could go in another class w/o that mixin.
175 executor = self.executor_type(1, max_tasks_per_child=3)
176 self.assertEqual(executor._mp_context.get_start_method(), "spawn")
177
178 def test_max_tasks_early_shutdown(self):
179 context = self.get_context()
180 if context.get_start_method(allow_none=False) == "fork":
181 raise unittest.SkipTest("Incompatible with the fork start method.")
182 # not using self.executor as we need to control construction.
183 # arguably this could go in another class w/o that mixin.
184 executor = self.executor_type(
185 3, mp_context=context, max_tasks_per_child=1)
186 futures = []
187 for i in range(6):
188 futures.append(executor.submit(mul, i, i))
189 executor.shutdown()
190 for i, future in enumerate(futures):
191 self.assertEqual(future.result(), mul(i, i))
192
193 def test_python_finalization_error(self):
194 # gh-109047: Catch RuntimeError on thread creation
195 # during Python finalization.
196
197 context = self.get_context()
198
199 # gh-109047: Mock the threading.start_joinable_thread() function to inject
200 # RuntimeError: simulate the error raised during Python finalization.
201 # Block the second creation: create _ExecutorManagerThread, but block
202 # QueueFeederThread.
203 orig_start_new_thread = threading._start_joinable_thread
204 nthread = 0
205 def mock_start_new_thread(func, *args, **kwargs):
206 nonlocal nthread
207 if nthread >= 1:
208 raise RuntimeError("can't create new thread at "
209 "interpreter shutdown")
210 nthread += 1
211 return orig_start_new_thread(func, *args, **kwargs)
212
213 with support.swap_attr(threading, '_start_joinable_thread',
214 mock_start_new_thread):
215 executor = self.executor_type(max_workers=2, mp_context=context)
216 with executor:
217 with self.assertRaises(BrokenProcessPool):
218 list(executor.map(mul, [(2, 3)] * 10))
219 executor.shutdown()
220
221
222 create_executor_tests(globals(), ProcessPoolExecutorTest,
223 executor_mixins=(ProcessPoolForkMixin,
224 ProcessPoolForkserverMixin,
225 ProcessPoolSpawnMixin))
226
227
228 def setUpModule():
229 setup_module()
230
231
232 if __name__ == "__main__":
233 unittest.main()