deadpool-executor 2026.7.1__tar.gz → 2026.11.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/PKG-INFO +21 -1
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/README.rst +20 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/__init__.py +1 -1
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/_pool.py +204 -27
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/pyproject.toml +1 -1
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/test_deadpool.py +60 -0
- deadpool_executor-2026.11.2/tests/test_idle_timeout.py +326 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/test_package_api.py +1 -1
- deadpool_executor-2026.11.2/tests/test_worker_accounting.py +168 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/.coveragerc +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/.pre-commit-config.yaml +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/LICENSE-AGPL +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/LICENSE-Apache +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/covstart.pth +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/__init__.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/_future.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/_protocol.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/_scheduler.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/_transport.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/_worker.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/client.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/config.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/errors.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/serializer.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/deadpool/remote/server.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/examples/callbacks.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/examples/entrypoint.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/examples/leftover.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/examples/priorities.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/img1.jpg +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/noxfile.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/__init__.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/conftest.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/__init__.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/README.txt +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/ca.pem +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/client-key.pem +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/client.pem +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/rogue-client-key.pem +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/rogue-client.pem +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/server-key.pem +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/server.pem +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/conftest.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/tasks.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_cancellation.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_client_api.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_fork_timeout.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_integration.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_protocol.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_public_end_to_end.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_scheduling_resilience.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_tcp.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_units.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_unix_lifecycle.py +0 -0
- {deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/test_oom.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: deadpool-executor
|
|
3
|
-
Version: 2026.
|
|
3
|
+
Version: 2026.11.2
|
|
4
4
|
Summary: A resilient process-pool executor and its optional remote interface.
|
|
5
5
|
Author-email: Caleb Hattingh <caleb.hattingh@gmail.com>
|
|
6
6
|
Requires-Python: >=3.10
|
|
@@ -324,6 +324,23 @@ pool when it is idle. This is another strategy alongside other
|
|
|
324
324
|
features like ``max_tasks_per_child`` and ``max_worker_memory_bytes``
|
|
325
325
|
to help deal with memory bloat in long-running pools.
|
|
326
326
|
|
|
327
|
+
By itself, ``min_workers`` stops a worker as soon as its task is done, if the
|
|
328
|
+
pool is above its minimum and there is nothing left to do. A burst then pays a
|
|
329
|
+
process start for every worker above the minimum, every time. To let workers
|
|
330
|
+
stay for a while instead, give the pool an ``idle_timeout``:
|
|
331
|
+
|
|
332
|
+
.. code-block:: python
|
|
333
|
+
|
|
334
|
+
with deadpool.Deadpool(min_workers=2, max_workers=10, idle_timeout=300) as exe:
|
|
335
|
+
...
|
|
336
|
+
|
|
337
|
+
While the pool has more than 2 workers, it stops the longest-idle worker once
|
|
338
|
+
that worker has been idle for 300 seconds. It waits for that worker to exit
|
|
339
|
+
before retiring another. Tasks go to the worker most recently made available,
|
|
340
|
+
so light traffic can reuse a warm process while the others age out. A worker
|
|
341
|
+
that has returned no result yet, which may still be starting, waits behind the
|
|
342
|
+
others. The timer reads the current ``min_workers`` at each check.
|
|
343
|
+
|
|
327
344
|
Statistics
|
|
328
345
|
~~~~~~~~~~
|
|
329
346
|
|
|
@@ -382,6 +399,9 @@ following keys:
|
|
|
382
399
|
in the inner workings of the executor, but on average it should not)
|
|
383
400
|
- ``worker_processes_idle``: The number of worker processes that are idle.
|
|
384
401
|
- ``worker_processes_busy``: The number of worker processes that are busy.
|
|
402
|
+
- ``worker_processes_stopped_idle`` and ``idle_sweep_errors`` are present when both
|
|
403
|
+
``min_workers`` and ``idle_timeout`` are supplied. They count idle retirements
|
|
404
|
+
started and failed timer checks, respectively.
|
|
385
405
|
|
|
386
406
|
|
|
387
407
|
Here is an example from the tests to explain what each of the
|
|
@@ -292,6 +292,23 @@ pool when it is idle. This is another strategy alongside other
|
|
|
292
292
|
features like ``max_tasks_per_child`` and ``max_worker_memory_bytes``
|
|
293
293
|
to help deal with memory bloat in long-running pools.
|
|
294
294
|
|
|
295
|
+
By itself, ``min_workers`` stops a worker as soon as its task is done, if the
|
|
296
|
+
pool is above its minimum and there is nothing left to do. A burst then pays a
|
|
297
|
+
process start for every worker above the minimum, every time. To let workers
|
|
298
|
+
stay for a while instead, give the pool an ``idle_timeout``:
|
|
299
|
+
|
|
300
|
+
.. code-block:: python
|
|
301
|
+
|
|
302
|
+
with deadpool.Deadpool(min_workers=2, max_workers=10, idle_timeout=300) as exe:
|
|
303
|
+
...
|
|
304
|
+
|
|
305
|
+
While the pool has more than 2 workers, it stops the longest-idle worker once
|
|
306
|
+
that worker has been idle for 300 seconds. It waits for that worker to exit
|
|
307
|
+
before retiring another. Tasks go to the worker most recently made available,
|
|
308
|
+
so light traffic can reuse a warm process while the others age out. A worker
|
|
309
|
+
that has returned no result yet, which may still be starting, waits behind the
|
|
310
|
+
others. The timer reads the current ``min_workers`` at each check.
|
|
311
|
+
|
|
295
312
|
Statistics
|
|
296
313
|
~~~~~~~~~~
|
|
297
314
|
|
|
@@ -350,6 +367,9 @@ following keys:
|
|
|
350
367
|
in the inner workings of the executor, but on average it should not)
|
|
351
368
|
- ``worker_processes_idle``: The number of worker processes that are idle.
|
|
352
369
|
- ``worker_processes_busy``: The number of worker processes that are busy.
|
|
370
|
+
- ``worker_processes_stopped_idle`` and ``idle_sweep_errors`` are present when both
|
|
371
|
+
``min_workers`` and ``idle_timeout`` are supplied. They count idle retirements
|
|
372
|
+
started and failed timer checks, respectively.
|
|
353
373
|
|
|
354
374
|
|
|
355
375
|
Here is an example from the tests to explain what each of the
|
|
@@ -29,6 +29,7 @@ import pickle
|
|
|
29
29
|
import signal
|
|
30
30
|
import sys
|
|
31
31
|
import threading
|
|
32
|
+
import time
|
|
32
33
|
import traceback
|
|
33
34
|
import typing
|
|
34
35
|
import weakref
|
|
@@ -36,6 +37,7 @@ import atexit
|
|
|
36
37
|
from concurrent.futures import CancelledError, Executor, InvalidStateError, as_completed
|
|
37
38
|
from dataclasses import dataclass, field
|
|
38
39
|
from multiprocessing.connection import Connection
|
|
40
|
+
from multiprocessing.reduction import ForkingPickler
|
|
39
41
|
from queue import Empty, PriorityQueue, Queue, SimpleQueue
|
|
40
42
|
from typing import Callable, Optional, Tuple
|
|
41
43
|
from collections.abc import Mapping
|
|
@@ -96,6 +98,9 @@ class Statistics:
|
|
|
96
98
|
self.tasks_failed = Stat(self._lock, 0)
|
|
97
99
|
self.worker_processes_created = Stat(self._lock, 0)
|
|
98
100
|
self.max_workers_busy_concurrently = Stat(self._lock, 0)
|
|
101
|
+
# Reported only by a pool with an ``idle_timeout``.
|
|
102
|
+
self.worker_processes_stopped_idle = Stat(self._lock, 0)
|
|
103
|
+
self.idle_sweep_errors = Stat(self._lock, 0)
|
|
99
104
|
|
|
100
105
|
def reset_counters(self):
|
|
101
106
|
self.tasks_received.set()
|
|
@@ -103,6 +108,8 @@ class Statistics:
|
|
|
103
108
|
self.tasks_failed.set()
|
|
104
109
|
self.worker_processes_created.set()
|
|
105
110
|
self.max_workers_busy_concurrently.set()
|
|
111
|
+
self.worker_processes_stopped_idle.set()
|
|
112
|
+
self.idle_sweep_errors.set()
|
|
106
113
|
|
|
107
114
|
def to_dict(self) -> dict[str, typing.Any]:
|
|
108
115
|
return {
|
|
@@ -121,6 +128,10 @@ class PrioritizedItem:
|
|
|
121
128
|
sequence: int = 0
|
|
122
129
|
|
|
123
130
|
|
|
131
|
+
class _JobSerializationError(Exception):
|
|
132
|
+
"""The job could not be serialized. No bytes were sent to the worker."""
|
|
133
|
+
|
|
134
|
+
|
|
124
135
|
@dataclass(init=False)
|
|
125
136
|
class WorkerProcess:
|
|
126
137
|
process: mp.Process
|
|
@@ -128,6 +139,8 @@ class WorkerProcess:
|
|
|
128
139
|
connection_send_msgs_to_process: Connection
|
|
129
140
|
# Stats
|
|
130
141
|
tasks_ran_counter: int
|
|
142
|
+
# It is known to have started. A task's exception counts as a result.
|
|
143
|
+
has_returned_result: bool
|
|
131
144
|
# Controls
|
|
132
145
|
# If the subprocess RSS memory is above this threshold,
|
|
133
146
|
# ask the system allocator to release unused memory back
|
|
@@ -169,6 +182,7 @@ class WorkerProcess:
|
|
|
169
182
|
self.connection_receive_msgs_from_process = conn_receiver
|
|
170
183
|
self.connection_send_msgs_to_process = conn_sender2
|
|
171
184
|
self.tasks_ran_counter = 0
|
|
185
|
+
self.has_returned_result = False
|
|
172
186
|
self.ok = True
|
|
173
187
|
|
|
174
188
|
def __hash__(self):
|
|
@@ -182,8 +196,12 @@ class WorkerProcess:
|
|
|
182
196
|
return psutil.Process(pid=self.pid).memory_info().rss
|
|
183
197
|
|
|
184
198
|
def submit_job(self, job):
|
|
199
|
+
try:
|
|
200
|
+
data = ForkingPickler.dumps(job)
|
|
201
|
+
except BaseException as exc:
|
|
202
|
+
raise _JobSerializationError from exc
|
|
185
203
|
self.tasks_ran_counter += 1
|
|
186
|
-
self.connection_send_msgs_to_process.
|
|
204
|
+
self.connection_send_msgs_to_process.send_bytes(data)
|
|
187
205
|
|
|
188
206
|
def shutdown(self, wait=True):
|
|
189
207
|
if not self.process.is_alive():
|
|
@@ -254,7 +272,9 @@ class WorkerProcess:
|
|
|
254
272
|
return self.connection_receive_msgs_from_process.poll(timeout=block_for)
|
|
255
273
|
|
|
256
274
|
def get_results(self):
|
|
257
|
-
|
|
275
|
+
result = self.connection_receive_msgs_from_process.recv()
|
|
276
|
+
self.has_returned_result = True
|
|
277
|
+
return result
|
|
258
278
|
|
|
259
279
|
|
|
260
280
|
class Future(concurrent.futures.Future):
|
|
@@ -302,6 +322,33 @@ class ProcessError(mp.ProcessError): ...
|
|
|
302
322
|
class PoolClosed(Exception): ...
|
|
303
323
|
|
|
304
324
|
|
|
325
|
+
class _IdleWorkers(Queue):
|
|
326
|
+
"""Take the newest idle worker for a task and the oldest for retirement.
|
|
327
|
+
|
|
328
|
+
A worker that has returned no result waits behind those that have, because
|
|
329
|
+
it may still be starting.
|
|
330
|
+
"""
|
|
331
|
+
|
|
332
|
+
def _put(self, worker):
|
|
333
|
+
item = (time.monotonic(), worker)
|
|
334
|
+
if worker.has_returned_result:
|
|
335
|
+
self.queue.append(item)
|
|
336
|
+
else:
|
|
337
|
+
self.queue.appendleft(item)
|
|
338
|
+
|
|
339
|
+
def _get(self):
|
|
340
|
+
return self.queue.pop()[1]
|
|
341
|
+
|
|
342
|
+
def take_expired(self, keep_idle: int, cutoff: float) -> Optional[WorkerProcess]:
|
|
343
|
+
with self.mutex:
|
|
344
|
+
if len(self.queue) > keep_idle:
|
|
345
|
+
oldest = min(self.queue, key=lambda item: item[0])
|
|
346
|
+
if oldest[0] <= cutoff:
|
|
347
|
+
self.queue.remove(oldest)
|
|
348
|
+
return oldest[1]
|
|
349
|
+
return None
|
|
350
|
+
|
|
351
|
+
|
|
305
352
|
class Deadpool(Executor):
|
|
306
353
|
def __init__(
|
|
307
354
|
self,
|
|
@@ -320,9 +367,18 @@ class Deadpool(Executor):
|
|
|
320
367
|
daemon=True,
|
|
321
368
|
malloc_trim_rss_memory_threshold_bytes: Optional[int] = None,
|
|
322
369
|
propagate_environ: Optional[Mapping] = None,
|
|
370
|
+
idle_timeout: Optional[float] = None,
|
|
323
371
|
) -> None:
|
|
324
372
|
"""The pool.
|
|
325
373
|
|
|
374
|
+
:param idle_timeout: Stop a worker that has been idle for this many
|
|
375
|
+
seconds while the pool has more workers than ``min_workers``, which
|
|
376
|
+
must then be between 1 and ``max_workers``. Tasks reuse the worker
|
|
377
|
+
most recently made available, and one that has returned no result
|
|
378
|
+
only if there is no other. The oldest idle worker retires first.
|
|
379
|
+
The timer reads the current minimum each time it checks. Omit either
|
|
380
|
+
option to keep the default checkout and retirement behavior.
|
|
381
|
+
|
|
326
382
|
:param propagate_environ: A mapping of environment variables to
|
|
327
383
|
propagate to the worker processes. This is useful for
|
|
328
384
|
setting up the environment in the worker processes. Subprocesses
|
|
@@ -364,6 +420,18 @@ class Deadpool(Executor):
|
|
|
364
420
|
else:
|
|
365
421
|
self.min_workers = min_workers
|
|
366
422
|
|
|
423
|
+
self.idle_timeout = idle_timeout
|
|
424
|
+
if idle_timeout is not None:
|
|
425
|
+
if not 0 < idle_timeout < float("inf"):
|
|
426
|
+
raise ValueError(
|
|
427
|
+
f"idle_timeout must be a finite number above 0, got {idle_timeout}"
|
|
428
|
+
)
|
|
429
|
+
if min_workers is not None and not 1 <= min_workers <= self.pool_size:
|
|
430
|
+
raise ValueError(
|
|
431
|
+
f"min_workers must be between 1 and {self.pool_size} "
|
|
432
|
+
f"with an idle_timeout, got {min_workers}"
|
|
433
|
+
)
|
|
434
|
+
|
|
367
435
|
self.max_tasks_per_child = max_tasks_per_child
|
|
368
436
|
self.max_worker_memory_bytes = max_worker_memory_bytes
|
|
369
437
|
self.submitted_jobs: PriorityQueue[PrioritizedItem] = PriorityQueue(
|
|
@@ -375,6 +443,11 @@ class Deadpool(Executor):
|
|
|
375
443
|
# Lock protecting busy_workers, existing_workers, and
|
|
376
444
|
# running_futs for thread-safety without the GIL.
|
|
377
445
|
self._workers_lock = threading.Lock()
|
|
446
|
+
# Held while a task counts the workers, starts one if needed and takes
|
|
447
|
+
# it, and while idle workers are cleared, so that nothing else takes the
|
|
448
|
+
# worker in between. Taken before ``_workers_lock`` when both are held.
|
|
449
|
+
self._checkout_lock = threading.Lock()
|
|
450
|
+
self._waiting_checkouts = 0 # Protected by _checkout_lock.
|
|
378
451
|
self.closed = False
|
|
379
452
|
self.shutdown_wait = shutdown_wait
|
|
380
453
|
self.shutdown_cancel_futures = shutdown_cancel_futures
|
|
@@ -386,7 +459,19 @@ class Deadpool(Executor):
|
|
|
386
459
|
self._submission_sequence = itertools.count()
|
|
387
460
|
|
|
388
461
|
# TODO: overcommit
|
|
389
|
-
self.
|
|
462
|
+
self._idle_timer: Optional[threading.Thread] = None
|
|
463
|
+
self.workers: SimpleQueue[WorkerProcess] | _IdleWorkers
|
|
464
|
+
if idle_timeout is not None and min_workers is not None:
|
|
465
|
+
self.workers = _IdleWorkers()
|
|
466
|
+
self._stop_timer = threading.Event()
|
|
467
|
+
self._idle_timer = threading.Thread(
|
|
468
|
+
target=self._run_idle_timer,
|
|
469
|
+
args=(self.workers,),
|
|
470
|
+
name="deadpool.idle",
|
|
471
|
+
daemon=True,
|
|
472
|
+
)
|
|
473
|
+
else:
|
|
474
|
+
self.workers = SimpleQueue()
|
|
390
475
|
for _ in range(self.pool_size):
|
|
391
476
|
self.add_worker_to_pool()
|
|
392
477
|
# When a worker is running a job, it will be removed from
|
|
@@ -397,12 +482,22 @@ class Deadpool(Executor):
|
|
|
397
482
|
self.busy_workers = set() # weakref.WeakSet()
|
|
398
483
|
|
|
399
484
|
# THE ONLY ACTIVE, PERSISTENT STATE IN DEADPOOL IS THIS THREAD
|
|
400
|
-
# BELOW
|
|
485
|
+
# BELOW, AND THE TIMER THREAD OF A POOL WITH AN IDLE TIMEOUT.
|
|
486
|
+
# PROTECT IT AT ALL COSTS.
|
|
401
487
|
self.runner_thread = threading.Thread(
|
|
402
488
|
target=self.runner, name="deadpool.runner", daemon=True
|
|
403
489
|
)
|
|
404
490
|
self.runner_thread.start()
|
|
405
491
|
|
|
492
|
+
if self._idle_timer is not None:
|
|
493
|
+
try:
|
|
494
|
+
self._idle_timer.start()
|
|
495
|
+
except Exception:
|
|
496
|
+
self._idle_timer = None # shutdown must only join a started timer
|
|
497
|
+
self.shutdown()
|
|
498
|
+
self.runner_thread.join()
|
|
499
|
+
raise
|
|
500
|
+
|
|
406
501
|
def get_statistics(self) -> dict[str, typing.Any]:
|
|
407
502
|
stats = self._statistics.to_dict()
|
|
408
503
|
|
|
@@ -412,9 +507,43 @@ class Deadpool(Executor):
|
|
|
412
507
|
stats["worker_processes_still_alive"] = len(self.existing_workers)
|
|
413
508
|
stats["worker_processes_busy"] = len(self.busy_workers)
|
|
414
509
|
stats["worker_processes_idle"] = self.workers.qsize()
|
|
510
|
+
if self._idle_timer is not None:
|
|
511
|
+
counters = self._statistics
|
|
512
|
+
stats["worker_processes_stopped_idle"] = (
|
|
513
|
+
counters.worker_processes_stopped_idle.value
|
|
514
|
+
)
|
|
515
|
+
stats["idle_sweep_errors"] = counters.idle_sweep_errors.value
|
|
415
516
|
|
|
416
517
|
return stats
|
|
417
518
|
|
|
519
|
+
def _run_idle_timer(self, workers: _IdleWorkers):
|
|
520
|
+
assert self.idle_timeout is not None
|
|
521
|
+
interval = max(0.05, min(self.idle_timeout / 4, 30.0))
|
|
522
|
+
while not self._stop_timer.wait(interval):
|
|
523
|
+
try:
|
|
524
|
+
# Serialize with checkout and count a returning worker only once.
|
|
525
|
+
with self._checkout_lock, self._workers_lock:
|
|
526
|
+
if self._stop_timer.is_set():
|
|
527
|
+
return
|
|
528
|
+
worker = workers.take_expired(
|
|
529
|
+
max(
|
|
530
|
+
self._waiting_checkouts,
|
|
531
|
+
self.min_workers - len(self.busy_workers),
|
|
532
|
+
),
|
|
533
|
+
time.monotonic() - self.idle_timeout,
|
|
534
|
+
)
|
|
535
|
+
if worker is not None:
|
|
536
|
+
self._statistics.worker_processes_stopped_idle.increment()
|
|
537
|
+
try:
|
|
538
|
+
worker.shutdown()
|
|
539
|
+
except Exception:
|
|
540
|
+
worker.process.kill()
|
|
541
|
+
worker.process.join()
|
|
542
|
+
raise
|
|
543
|
+
except Exception:
|
|
544
|
+
logger.exception("The idle timer failed; it will try again.")
|
|
545
|
+
self._statistics.idle_sweep_errors.increment()
|
|
546
|
+
|
|
418
547
|
def add_worker_to_pool(self):
|
|
419
548
|
if self.propagate_environ:
|
|
420
549
|
# By constructing here, late, we allow the user to make
|
|
@@ -456,8 +585,15 @@ class Deadpool(Executor):
|
|
|
456
585
|
this is to have new settings take effect, such as a new
|
|
457
586
|
environment variable that needs to be set in the workers.
|
|
458
587
|
"""
|
|
459
|
-
while
|
|
460
|
-
|
|
588
|
+
while True:
|
|
589
|
+
# Each is taken under the lock, so that a task never counts an idle
|
|
590
|
+
# worker that is taken here before the task can take it, and stopped
|
|
591
|
+
# outside it. A worker that is returned meanwhile is cleared too.
|
|
592
|
+
with self._checkout_lock:
|
|
593
|
+
try:
|
|
594
|
+
worker = self.workers.get_nowait()
|
|
595
|
+
except Empty:
|
|
596
|
+
break
|
|
461
597
|
worker.shutdown(wait=False)
|
|
462
598
|
|
|
463
599
|
def runner(self):
|
|
@@ -487,21 +623,44 @@ class Deadpool(Executor):
|
|
|
487
623
|
self.running_jobs.get()
|
|
488
624
|
continue
|
|
489
625
|
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
626
|
+
try:
|
|
627
|
+
threading.Thread(target=self.run_task, args=job, daemon=True).start()
|
|
628
|
+
except Exception as exc:
|
|
629
|
+
# No task thread exists to release the slot or complete the future.
|
|
630
|
+
self.running_jobs.get()
|
|
631
|
+
self.submitted_jobs.task_done()
|
|
632
|
+
self._statistics.tasks_failed.increment()
|
|
633
|
+
try:
|
|
634
|
+
fut.set_exception(exc)
|
|
635
|
+
except InvalidStateError:
|
|
636
|
+
pass # Cancelled during dispatch.
|
|
493
637
|
|
|
494
638
|
def get_process(self) -> WorkerProcess:
|
|
495
|
-
with self.
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
639
|
+
with self._checkout_lock:
|
|
640
|
+
with self._workers_lock:
|
|
641
|
+
bw = len(self.busy_workers)
|
|
642
|
+
mw = self.pool_size
|
|
643
|
+
qs = self.workers.qsize()
|
|
499
644
|
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
645
|
+
total_workers = bw + qs
|
|
646
|
+
if total_workers < mw and qs == 0:
|
|
647
|
+
self.add_worker_to_pool()
|
|
648
|
+
|
|
649
|
+
try:
|
|
650
|
+
wp = self.workers.get_nowait()
|
|
651
|
+
except Empty:
|
|
652
|
+
wp = None
|
|
653
|
+
self._waiting_checkouts += 1
|
|
654
|
+
|
|
655
|
+
if wp is None:
|
|
656
|
+
# A direct checkout can occupy capacity outside the submission limit.
|
|
657
|
+
# Reserve a returned worker against idle retirement while we wait.
|
|
658
|
+
try:
|
|
659
|
+
wp = self.workers.get()
|
|
660
|
+
finally:
|
|
661
|
+
with self._checkout_lock:
|
|
662
|
+
self._waiting_checkouts -= 1
|
|
503
663
|
|
|
504
|
-
wp = self.workers.get()
|
|
505
664
|
with self._workers_lock:
|
|
506
665
|
self.busy_workers.add(wp)
|
|
507
666
|
busy_count = len(self.busy_workers)
|
|
@@ -513,10 +672,13 @@ class Deadpool(Executor):
|
|
|
513
672
|
|
|
514
673
|
def done_with_process(self, wp: WorkerProcess):
|
|
515
674
|
# This worker is done with its job and is no longer busy.
|
|
675
|
+
# The two counts are read together. Read apart, another worker that is
|
|
676
|
+
# returned in between is counted as both busy and idle, and this one is
|
|
677
|
+
# stopped although the pool is at its minimum.
|
|
516
678
|
with self._workers_lock:
|
|
517
679
|
self.busy_workers.remove(wp)
|
|
518
680
|
count_workers_busy = len(self.busy_workers)
|
|
519
|
-
|
|
681
|
+
count_workers_idle = self.workers.qsize()
|
|
520
682
|
backlog_size = self.submitted_jobs.qsize()
|
|
521
683
|
|
|
522
684
|
# The `1` is for `wp` itself.
|
|
@@ -525,7 +687,11 @@ class Deadpool(Executor):
|
|
|
525
687
|
task_backlog_is_empty = backlog_size == 0
|
|
526
688
|
|
|
527
689
|
# if there_are_more_workers_than_min and (there_are_idle_workers or task_backlog_is_empty):
|
|
528
|
-
if
|
|
690
|
+
if (
|
|
691
|
+
there_are_more_workers_than_min
|
|
692
|
+
and task_backlog_is_empty
|
|
693
|
+
and self._idle_timer is None
|
|
694
|
+
):
|
|
529
695
|
# We have more workers than the minimum, and there is no backlog of
|
|
530
696
|
# tasks. This implies any tasks currently in play have already been picked
|
|
531
697
|
# up by workers in the pool, or the pool is idle. We can safely remove
|
|
@@ -561,6 +727,7 @@ class Deadpool(Executor):
|
|
|
561
727
|
|
|
562
728
|
def run_task(self, fn, args, kwargs, timeout, fut: Future):
|
|
563
729
|
try:
|
|
730
|
+
self._statistics.tasks_launched.increment()
|
|
564
731
|
retry_count = 10
|
|
565
732
|
while retry_count > 0:
|
|
566
733
|
retry_count -= 1
|
|
@@ -581,14 +748,15 @@ class Deadpool(Executor):
|
|
|
581
748
|
if after_submit is not None:
|
|
582
749
|
after_submit(worker.pid)
|
|
583
750
|
break
|
|
584
|
-
except
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
751
|
+
except _JobSerializationError as e:
|
|
752
|
+
self._statistics.tasks_failed.increment()
|
|
753
|
+
try:
|
|
754
|
+
assert e.__cause__ is not None
|
|
755
|
+
fut.set_exception(e.__cause__)
|
|
756
|
+
except InvalidStateError:
|
|
757
|
+
pass # Cancelled while serializing.
|
|
758
|
+
finally:
|
|
759
|
+
self.done_with_process(worker)
|
|
592
760
|
return
|
|
593
761
|
except BrokenPipeError:
|
|
594
762
|
# This likely comes from trying to send a job over a pipe
|
|
@@ -754,6 +922,8 @@ class Deadpool(Executor):
|
|
|
754
922
|
|
|
755
923
|
def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None:
|
|
756
924
|
if self.closed:
|
|
925
|
+
if wait and self._idle_timer is not None:
|
|
926
|
+
self._idle_timer.join()
|
|
757
927
|
return
|
|
758
928
|
|
|
759
929
|
logger.debug(f"shutdown: {wait=} {cancel_futures=}")
|
|
@@ -761,6 +931,10 @@ class Deadpool(Executor):
|
|
|
761
931
|
# No more new tasks can be submitted
|
|
762
932
|
self.closed = True
|
|
763
933
|
|
|
934
|
+
if self._idle_timer is not None:
|
|
935
|
+
with self._checkout_lock:
|
|
936
|
+
self._stop_timer.set()
|
|
937
|
+
|
|
764
938
|
if cancel_futures:
|
|
765
939
|
cancel_all_futures_on_queue(self.submitted_jobs)
|
|
766
940
|
|
|
@@ -823,6 +997,9 @@ class Deadpool(Executor):
|
|
|
823
997
|
for worker in remaining:
|
|
824
998
|
worker.shutdown()
|
|
825
999
|
|
|
1000
|
+
if wait and self._idle_timer is not None:
|
|
1001
|
+
self._idle_timer.join()
|
|
1002
|
+
|
|
826
1003
|
def __enter__(self):
|
|
827
1004
|
return self
|
|
828
1005
|
|
|
@@ -703,6 +703,66 @@ def test_max_memory(logging_initializer):
|
|
|
703
703
|
assert len(pids) >= 10
|
|
704
704
|
|
|
705
705
|
|
|
706
|
+
class UnpickleableArgument:
|
|
707
|
+
def __reduce__(self):
|
|
708
|
+
raise BrokenPipeError("raised by the reducer")
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
@pytest.mark.parametrize(
|
|
712
|
+
"argument, error",
|
|
713
|
+
[
|
|
714
|
+
(threading.Lock(), (TypeError, pickle.PicklingError)),
|
|
715
|
+
(UnpickleableArgument(), BrokenPipeError),
|
|
716
|
+
],
|
|
717
|
+
)
|
|
718
|
+
def test_unpickleable_argument_releases_worker(argument, error):
|
|
719
|
+
with deadpool.Deadpool(max_workers=1) as pool:
|
|
720
|
+
pid = pool.submit(os.getpid).result(timeout=5)
|
|
721
|
+
with pytest.raises(error):
|
|
722
|
+
pool.submit(str, argument).result(timeout=5)
|
|
723
|
+
assert pool.get_statistics()["tasks_failed"] == 1
|
|
724
|
+
assert pool.submit(os.getpid).result(timeout=5) == pid
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _cancel_during_argument_serialization():
|
|
728
|
+
serializing = threading.Event()
|
|
729
|
+
resume = threading.Event()
|
|
730
|
+
|
|
731
|
+
class BadArgument:
|
|
732
|
+
def __reduce__(self):
|
|
733
|
+
serializing.set()
|
|
734
|
+
assert resume.wait(5)
|
|
735
|
+
raise TypeError("cannot pickle argument")
|
|
736
|
+
|
|
737
|
+
with deadpool.Deadpool(max_workers=1) as pool:
|
|
738
|
+
pid = pool.submit(os.getpid).result(timeout=5)
|
|
739
|
+
future = pool.submit(str, BadArgument())
|
|
740
|
+
try:
|
|
741
|
+
assert serializing.wait(5)
|
|
742
|
+
assert future.cancel()
|
|
743
|
+
finally:
|
|
744
|
+
resume.set()
|
|
745
|
+
assert pool.submit(os.getpid).result(timeout=5) == pid
|
|
746
|
+
with pytest.raises(deadpool.CancelledError):
|
|
747
|
+
future.result()
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def test_cancel_during_argument_serialization_releases_worker():
|
|
751
|
+
# A stranded worker can block pool shutdown even after Future.result times out.
|
|
752
|
+
process = mp.get_context("spawn").Process(
|
|
753
|
+
target=_cancel_during_argument_serialization
|
|
754
|
+
)
|
|
755
|
+
process.start()
|
|
756
|
+
try:
|
|
757
|
+
process.join(timeout=15)
|
|
758
|
+
assert not process.is_alive(), "Cancellation or shutdown exceeded 15 seconds"
|
|
759
|
+
assert process.exitcode == 0
|
|
760
|
+
finally:
|
|
761
|
+
if process.is_alive():
|
|
762
|
+
process.kill()
|
|
763
|
+
process.join()
|
|
764
|
+
|
|
765
|
+
|
|
706
766
|
def test_can_pickle_nested_function():
|
|
707
767
|
# Verify that deadpool raises a ValueError
|
|
708
768
|
# if the function can't be pickled.
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Idle-worker behavior as seen by callers of Deadpool."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import multiprocessing
|
|
5
|
+
import os
|
|
6
|
+
import pickle
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
from multiprocessing.connection import Connection
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
from deadpool import Deadpool
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def wait_until(predicate, timeout=10):
|
|
17
|
+
deadline = time.monotonic() + timeout
|
|
18
|
+
while not predicate():
|
|
19
|
+
if time.monotonic() >= deadline:
|
|
20
|
+
raise AssertionError("Timed out waiting for " + repr(predicate))
|
|
21
|
+
time.sleep(0.01)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def wait_for_idle(pool, count):
|
|
25
|
+
wait_until(lambda: pool.get_statistics()["worker_processes_idle"] == count)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_timer_start_failure_cleans_up_pool(monkeypatch):
|
|
29
|
+
children = set(multiprocessing.active_children())
|
|
30
|
+
threads = set(threading.enumerate())
|
|
31
|
+
start = threading.Thread.start
|
|
32
|
+
|
|
33
|
+
def fail_timer(thread):
|
|
34
|
+
if thread.name == "deadpool.idle":
|
|
35
|
+
raise RuntimeError("timer could not start")
|
|
36
|
+
return start(thread)
|
|
37
|
+
|
|
38
|
+
monkeypatch.setattr(threading.Thread, "start", fail_timer)
|
|
39
|
+
with pytest.raises(RuntimeError, match="timer could not start"):
|
|
40
|
+
Deadpool(max_workers=2, min_workers=1, idle_timeout=1)
|
|
41
|
+
assert not set(multiprocessing.active_children()) - children
|
|
42
|
+
assert not any(
|
|
43
|
+
t.name == "deadpool.runner" for t in set(threading.enumerate()) - threads
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_pool_runs_next_task_after_dispatch_thread_fails(monkeypatch):
|
|
48
|
+
pool = Deadpool(max_workers=1, min_workers=1, idle_timeout=1)
|
|
49
|
+
|
|
50
|
+
def fail_start(thread):
|
|
51
|
+
raise RuntimeError("task thread could not start")
|
|
52
|
+
|
|
53
|
+
with monkeypatch.context() as patch:
|
|
54
|
+
patch.setattr(threading.Thread, "start", fail_start)
|
|
55
|
+
with pytest.raises(RuntimeError, match="task thread could not start"):
|
|
56
|
+
pool.submit(abs, -1).result(timeout=5)
|
|
57
|
+
assert pool.submit(abs, -2).result(timeout=5) == 2
|
|
58
|
+
pool.shutdown()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@pytest.mark.parametrize("bad", [0, -1, math.inf, math.nan])
|
|
62
|
+
def test_timeout_must_be_positive_and_finite(bad):
|
|
63
|
+
with pytest.raises(ValueError, match="idle_timeout"):
|
|
64
|
+
Deadpool(max_workers=2, min_workers=1, idle_timeout=bad)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@pytest.mark.parametrize("bad", [0, -1, 3])
|
|
68
|
+
def test_timeout_needs_a_valid_minimum(bad):
|
|
69
|
+
with pytest.raises(ValueError, match="min_workers"):
|
|
70
|
+
Deadpool(max_workers=2, min_workers=bad, idle_timeout=1)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@pytest.mark.parametrize("options", [{}, {"idle_timeout": 0.1}])
|
|
74
|
+
def test_pool_without_a_minimum_keeps_workers_and_rotates_tasks(options):
|
|
75
|
+
with Deadpool(max_workers=2, **options) as pool:
|
|
76
|
+
first = pool.submit(os.getpid).result(timeout=5)
|
|
77
|
+
wait_for_idle(pool, 2)
|
|
78
|
+
time.sleep(0.2)
|
|
79
|
+
assert pool.submit(os.getpid).result(timeout=5) != first
|
|
80
|
+
stats = pool.get_statistics()
|
|
81
|
+
assert "worker_processes_stopped_idle" not in stats
|
|
82
|
+
assert "idle_sweep_errors" not in stats
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_minimum_without_timeout_still_shrinks_on_return():
|
|
86
|
+
with Deadpool(max_workers=2, min_workers=1) as pool:
|
|
87
|
+
pool.submit(os.getpid).result(timeout=5)
|
|
88
|
+
wait_for_idle(pool, 1)
|
|
89
|
+
assert "worker_processes_stopped_idle" not in pool.get_statistics()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_warm_worker_is_reused_and_survives_idle_expiry():
|
|
93
|
+
with Deadpool(max_workers=3, min_workers=3, idle_timeout=0.3) as pool:
|
|
94
|
+
warm = pool.submit(os.getpid).result(timeout=5)
|
|
95
|
+
wait_for_idle(pool, 3)
|
|
96
|
+
assert pool.submit(os.getpid).result(timeout=5) == warm
|
|
97
|
+
wait_for_idle(pool, 3)
|
|
98
|
+
time.sleep(0.5) # All three are eligible by age, including the warm one.
|
|
99
|
+
assert pool.get_statistics()["worker_processes_stopped_idle"] == 0
|
|
100
|
+
pool.min_workers = 1
|
|
101
|
+
wait_for_idle(pool, 1)
|
|
102
|
+
assert pool.submit(os.getpid).result(timeout=5) == warm
|
|
103
|
+
assert pool.get_statistics()["worker_processes_stopped_idle"] == 2
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def hold_until(release):
|
|
107
|
+
wait_until(release.exists)
|
|
108
|
+
return os.getpid()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_returning_worker_remains_available_before_timeout():
|
|
112
|
+
with Deadpool(max_workers=2, min_workers=1, idle_timeout=60) as pool:
|
|
113
|
+
pool.submit(os.getpid).result(timeout=5)
|
|
114
|
+
wait_for_idle(pool, 2)
|
|
115
|
+
assert pool.get_statistics()["worker_processes_stopped_idle"] == 0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_busy_worker_counts_toward_the_minimum_and_pool_regrows(tmp_path):
|
|
119
|
+
with Deadpool(max_workers=3, min_workers=2, idle_timeout=0.4) as pool:
|
|
120
|
+
release = tmp_path / "release"
|
|
121
|
+
running = pool.submit(hold_until, release)
|
|
122
|
+
try:
|
|
123
|
+
wait_for_idle(pool, 1)
|
|
124
|
+
assert pool.get_statistics()["worker_processes_busy"] == 1
|
|
125
|
+
# A busy worker and one idle worker already satisfy the minimum.
|
|
126
|
+
time.sleep(0.55)
|
|
127
|
+
assert pool.get_statistics()["worker_processes_stopped_idle"] == 1
|
|
128
|
+
others = [pool.submit(hold_until, release) for _ in range(2)]
|
|
129
|
+
wait_until(lambda: pool.get_statistics()["worker_processes_busy"] == 3)
|
|
130
|
+
finally:
|
|
131
|
+
release.touch()
|
|
132
|
+
assert len({f.result(timeout=5) for f in [running, *others]}) == 3
|
|
133
|
+
wait_until(lambda: pool.get_statistics()["worker_processes_stopped_idle"] == 2)
|
|
134
|
+
wait_for_idle(pool, 2)
|
|
135
|
+
assert pool.get_statistics()["worker_processes_created"] == 4
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_idle_timer_leaves_a_worker_for_a_waiting_task(monkeypatch):
|
|
139
|
+
with Deadpool(max_workers=2, min_workers=2, idle_timeout=0.05) as pool:
|
|
140
|
+
first, second = pool.get_process(), pool.get_process()
|
|
141
|
+
waiting, resume = threading.Event(), threading.Event()
|
|
142
|
+
get = pool.workers.get
|
|
143
|
+
|
|
144
|
+
def delayed_get(block=True, timeout=None):
|
|
145
|
+
if block:
|
|
146
|
+
waiting.set()
|
|
147
|
+
assert resume.wait(5)
|
|
148
|
+
return get(block, timeout)
|
|
149
|
+
|
|
150
|
+
# Pause just the blocking checkout so the timer can run before it resumes.
|
|
151
|
+
monkeypatch.setattr(pool.workers, "get", delayed_get)
|
|
152
|
+
future = pool.submit(os.getpid)
|
|
153
|
+
try:
|
|
154
|
+
assert waiting.wait(5)
|
|
155
|
+
pool.done_with_process(first)
|
|
156
|
+
pool.min_workers = 1
|
|
157
|
+
time.sleep(0.3)
|
|
158
|
+
resume.set()
|
|
159
|
+
assert future.result(timeout=2) == first.pid
|
|
160
|
+
finally:
|
|
161
|
+
resume.set()
|
|
162
|
+
pool.done_with_process(second)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def hold_first_finalizer(started, release, another):
|
|
166
|
+
try:
|
|
167
|
+
started.touch(exist_ok=False)
|
|
168
|
+
except FileExistsError:
|
|
169
|
+
another.touch()
|
|
170
|
+
else:
|
|
171
|
+
wait_until(release.exists)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@pytest.mark.parametrize(
|
|
175
|
+
"wait, close_first", [(True, False), (False, False), (True, True)]
|
|
176
|
+
)
|
|
177
|
+
def test_shutdown_during_idle_retirement(tmp_path, wait, close_first):
|
|
178
|
+
started, release, another = (
|
|
179
|
+
tmp_path / n for n in ("started", "release", "another")
|
|
180
|
+
)
|
|
181
|
+
with Deadpool(
|
|
182
|
+
max_workers=3,
|
|
183
|
+
min_workers=1,
|
|
184
|
+
idle_timeout=0.2,
|
|
185
|
+
finalizer=hold_first_finalizer,
|
|
186
|
+
finalargs=(started, release, another),
|
|
187
|
+
) as pool:
|
|
188
|
+
try:
|
|
189
|
+
wait_until(started.exists)
|
|
190
|
+
assert pool.submit(os.getpid).result(timeout=5) > 0
|
|
191
|
+
time.sleep(0.3) # The first finalizer still holds up the next retirement.
|
|
192
|
+
assert pool.get_statistics()["worker_processes_stopped_idle"] == 1
|
|
193
|
+
if close_first:
|
|
194
|
+
pool.shutdown(wait=False)
|
|
195
|
+
shutdown = threading.Thread(target=pool.shutdown, kwargs={"wait": wait})
|
|
196
|
+
shutdown.start()
|
|
197
|
+
wait_until(another.exists)
|
|
198
|
+
shutdown.join(timeout=0.2 if wait else 5)
|
|
199
|
+
assert shutdown.is_alive() == wait
|
|
200
|
+
finally:
|
|
201
|
+
release.touch()
|
|
202
|
+
shutdown.join(timeout=5)
|
|
203
|
+
assert not shutdown.is_alive()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def test_retirement_recovers_from_a_failed_stop(monkeypatch):
|
|
207
|
+
# Fail a real shutdown message at the IPC boundary, once.
|
|
208
|
+
send = Connection.send
|
|
209
|
+
failed = False
|
|
210
|
+
|
|
211
|
+
def fail_once(conn, message):
|
|
212
|
+
nonlocal failed
|
|
213
|
+
if message is None and not failed:
|
|
214
|
+
failed = True
|
|
215
|
+
raise OSError("stop message failed")
|
|
216
|
+
return send(conn, message)
|
|
217
|
+
|
|
218
|
+
with Deadpool(max_workers=3, min_workers=1, idle_timeout=0.3) as pool:
|
|
219
|
+
monkeypatch.setattr(Connection, "send", fail_once)
|
|
220
|
+
wait_for_idle(pool, 1)
|
|
221
|
+
assert pool.get_statistics()["idle_sweep_errors"] == 1
|
|
222
|
+
assert pool.submit(os.getpid).result(timeout=5) > 0
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def start_when_released(gated, release):
|
|
226
|
+
if gated.exists():
|
|
227
|
+
wait_until(release.exists)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def test_task_does_not_wait_for_a_starting_worker_while_a_warm_one_is_idle(tmp_path):
|
|
231
|
+
gated, release, started = (tmp_path / n for n in ("gated", "release", "started"))
|
|
232
|
+
with Deadpool(
|
|
233
|
+
max_workers=2,
|
|
234
|
+
min_workers=2,
|
|
235
|
+
idle_timeout=60,
|
|
236
|
+
max_tasks_per_child=2,
|
|
237
|
+
initializer=start_when_released,
|
|
238
|
+
initargs=(gated, release),
|
|
239
|
+
) as pool:
|
|
240
|
+
try:
|
|
241
|
+
held = [pool.submit(hold_until, started) for _ in range(2)]
|
|
242
|
+
wait_until(lambda: pool.get_statistics()["worker_processes_busy"] == 2)
|
|
243
|
+
started.touch()
|
|
244
|
+
both = {f.result(timeout=5) for f in held}
|
|
245
|
+
wait_for_idle(pool, 2)
|
|
246
|
+
# Workers started from now on do not finish starting.
|
|
247
|
+
gated.touch()
|
|
248
|
+
retired = pool.submit(os.getpid).result(timeout=5)
|
|
249
|
+
wait_until(lambda: pool.get_statistics()["worker_processes_created"] == 3)
|
|
250
|
+
wait_for_idle(pool, 2)
|
|
251
|
+
warm = pool.submit(os.getpid).result(timeout=5)
|
|
252
|
+
assert {warm} == both - {retired}
|
|
253
|
+
finally:
|
|
254
|
+
release.touch()
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class FailsToPickleWhenReleased:
|
|
258
|
+
def __init__(self):
|
|
259
|
+
self.pickling = threading.Event()
|
|
260
|
+
self.release = threading.Event()
|
|
261
|
+
|
|
262
|
+
def __reduce__(self):
|
|
263
|
+
self.pickling.set()
|
|
264
|
+
assert self.release.wait(10)
|
|
265
|
+
raise pickle.PicklingError("not sent")
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def test_a_worker_whose_first_job_was_not_sent_waits_behind_a_warm_one(tmp_path):
|
|
269
|
+
gated, release, finish = (tmp_path / n for n in ("gated", "release", "finish"))
|
|
270
|
+
argument = FailsToPickleWhenReleased()
|
|
271
|
+
with Deadpool(
|
|
272
|
+
max_workers=2,
|
|
273
|
+
min_workers=2,
|
|
274
|
+
idle_timeout=60,
|
|
275
|
+
initializer=start_when_released,
|
|
276
|
+
initargs=(gated, release),
|
|
277
|
+
) as pool:
|
|
278
|
+
try:
|
|
279
|
+
warm = pool.submit(os.getpid).result(timeout=5)
|
|
280
|
+
wait_for_idle(pool, 2)
|
|
281
|
+
held = pool.submit(hold_until, finish)
|
|
282
|
+
wait_until(lambda: pool.get_statistics()["worker_processes_busy"] == 1)
|
|
283
|
+
# The other worker is replaced by one that does not finish starting.
|
|
284
|
+
gated.touch()
|
|
285
|
+
pool.clear_workers()
|
|
286
|
+
not_sent = pool.submit(str, argument)
|
|
287
|
+
assert argument.pickling.wait(5)
|
|
288
|
+
finish.touch()
|
|
289
|
+
assert held.result(timeout=5) == warm
|
|
290
|
+
wait_for_idle(pool, 1)
|
|
291
|
+
argument.release.set()
|
|
292
|
+
with pytest.raises(pickle.PicklingError, match="not sent"):
|
|
293
|
+
not_sent.result(timeout=5)
|
|
294
|
+
wait_for_idle(pool, 2)
|
|
295
|
+
assert pool.submit(os.getpid).result(timeout=5) == warm
|
|
296
|
+
finally:
|
|
297
|
+
argument.release.set()
|
|
298
|
+
finish.touch()
|
|
299
|
+
release.touch()
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def raise_pid():
|
|
303
|
+
raise ValueError(os.getpid())
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def test_a_worker_whose_first_task_raised_is_handed_out_first():
|
|
307
|
+
with Deadpool(max_workers=2, min_workers=2, idle_timeout=60) as pool:
|
|
308
|
+
wait_for_idle(pool, 2)
|
|
309
|
+
with pytest.raises(ValueError) as raised:
|
|
310
|
+
pool.submit(raise_pid).result(timeout=5)
|
|
311
|
+
wait_for_idle(pool, 2)
|
|
312
|
+
pid = pool.submit(os.getpid).result(timeout=5)
|
|
313
|
+
assert str(raised.value).split()[0] == str(pid)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def test_a_new_worker_waiting_behind_does_not_hide_an_expired_one():
|
|
317
|
+
with Deadpool(max_workers=3, min_workers=3, idle_timeout=2) as pool:
|
|
318
|
+
warm = pool.submit(os.getpid).result(timeout=5)
|
|
319
|
+
wait_for_idle(pool, 3)
|
|
320
|
+
time.sleep(2.2) # All three have expired.
|
|
321
|
+
pool.add_worker_to_pool()
|
|
322
|
+
pool.min_workers = 1
|
|
323
|
+
time.sleep(1.6) # Long enough for three checks; the new one is not yet due.
|
|
324
|
+
assert pool.get_statistics()["worker_processes_stopped_idle"] >= 2
|
|
325
|
+
wait_for_idle(pool, 1)
|
|
326
|
+
assert pool.submit(os.getpid).result(timeout=5) != warm
|
|
@@ -2,7 +2,7 @@ import deadpool
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
def test_package_preserves_local_api():
|
|
5
|
-
assert deadpool.__version__
|
|
5
|
+
assert isinstance(deadpool.__version__, str)
|
|
6
6
|
assert deadpool.Deadpool.__module__ == "deadpool._pool"
|
|
7
7
|
assert deadpool.PrioritizedItem is deadpool._pool.PrioritizedItem
|
|
8
8
|
assert callable(deadpool.trim_memory)
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Deterministic tests for races in how the pool counts its workers.
|
|
2
|
+
|
|
3
|
+
Each test forces the interleaving it is about, so none relies on timing to
|
|
4
|
+
trigger. The timeouts only bound how long a broken version can hang.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import threading
|
|
8
|
+
|
|
9
|
+
import deadpool
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _Hooked:
|
|
13
|
+
"""The idle queue, with a callback around its first ``qsize`` call."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, queue, before=None, after=None):
|
|
16
|
+
self._queue = queue
|
|
17
|
+
self._before, self._after = before, after
|
|
18
|
+
|
|
19
|
+
def __getattr__(self, name):
|
|
20
|
+
return getattr(self._queue, name)
|
|
21
|
+
|
|
22
|
+
def qsize(self):
|
|
23
|
+
before, self._before = self._before, None
|
|
24
|
+
after, self._after = self._after, None
|
|
25
|
+
if before is not None:
|
|
26
|
+
before()
|
|
27
|
+
size = self._queue.qsize()
|
|
28
|
+
if after is not None:
|
|
29
|
+
after()
|
|
30
|
+
return size
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _run(fn):
|
|
34
|
+
thread = threading.Thread(target=fn, daemon=True)
|
|
35
|
+
thread.start()
|
|
36
|
+
return thread
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_workers_returned_together_keep_the_minimum():
|
|
40
|
+
"""Two workers come back at once in a pool already at its minimum. Counting
|
|
41
|
+
the second one as both busy and idle would stop the first."""
|
|
42
|
+
with deadpool.Deadpool(max_workers=2, min_workers=2) as pool:
|
|
43
|
+
first, second = pool.get_process(), pool.get_process()
|
|
44
|
+
|
|
45
|
+
returning = []
|
|
46
|
+
|
|
47
|
+
def second_returns():
|
|
48
|
+
returning.append(_run(lambda: pool.done_with_process(second)))
|
|
49
|
+
# Finishes at once if it can; waits for the lock otherwise.
|
|
50
|
+
returning[0].join(timeout=0.5)
|
|
51
|
+
|
|
52
|
+
real_queue = pool.workers
|
|
53
|
+
pool.workers = _Hooked(real_queue, before=second_returns)
|
|
54
|
+
pool.done_with_process(first)
|
|
55
|
+
returning[0].join(timeout=10)
|
|
56
|
+
pool.workers = real_queue
|
|
57
|
+
assert not returning[0].is_alive()
|
|
58
|
+
stats = pool.get_statistics()
|
|
59
|
+
assert stats["worker_processes_busy"] == 0
|
|
60
|
+
assert stats["worker_processes_idle"] == 2
|
|
61
|
+
assert first.is_alive() and second.is_alive()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_a_started_worker_goes_to_the_task_it_was_started_for():
|
|
65
|
+
"""Two tasks find no idle worker in a pool with room for two more. Each gets
|
|
66
|
+
a worker; the second must not take the one started for the first."""
|
|
67
|
+
with deadpool.Deadpool(max_workers=3, min_workers=1) as pool:
|
|
68
|
+
held = [pool.get_process() for _ in range(3)]
|
|
69
|
+
for worker in held[1:]:
|
|
70
|
+
pool.done_with_process(worker) # above the minimum: stopped
|
|
71
|
+
assert pool.workers.qsize() == 0
|
|
72
|
+
|
|
73
|
+
got = []
|
|
74
|
+
started = threading.Event()
|
|
75
|
+
second_done = threading.Event()
|
|
76
|
+
real_add = pool.add_worker_to_pool
|
|
77
|
+
|
|
78
|
+
def add_then_let_the_second_task_run():
|
|
79
|
+
real_add()
|
|
80
|
+
if not started.is_set():
|
|
81
|
+
started.set()
|
|
82
|
+
# Broken: the second task takes this worker here. Fixed: it
|
|
83
|
+
# cannot get in until the first task has taken its worker.
|
|
84
|
+
second_done.wait(timeout=0.5)
|
|
85
|
+
|
|
86
|
+
pool.add_worker_to_pool = add_then_let_the_second_task_run
|
|
87
|
+
|
|
88
|
+
def second_task():
|
|
89
|
+
started.wait()
|
|
90
|
+
got.append(pool.get_process())
|
|
91
|
+
second_done.set()
|
|
92
|
+
|
|
93
|
+
second = _run(second_task)
|
|
94
|
+
first = _run(lambda: got.append(pool.get_process()))
|
|
95
|
+
first.join(timeout=10)
|
|
96
|
+
second.join(timeout=10)
|
|
97
|
+
stuck = first.is_alive() or second.is_alive()
|
|
98
|
+
pool.add_worker_to_pool = real_add
|
|
99
|
+
for worker in got:
|
|
100
|
+
pool.done_with_process(worker)
|
|
101
|
+
pool.done_with_process(held[0])
|
|
102
|
+
assert not stuck
|
|
103
|
+
assert len({id(w) for w in got}) == 2
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_clear_workers_does_not_block_if_the_last_worker_is_taken():
|
|
107
|
+
"""A task can take the last idle worker between ``empty()`` and ``get()``."""
|
|
108
|
+
|
|
109
|
+
class TakenAfterEmptyCheck:
|
|
110
|
+
def __init__(self, queue):
|
|
111
|
+
self._queue = queue
|
|
112
|
+
|
|
113
|
+
def __getattr__(self, name):
|
|
114
|
+
return getattr(self._queue, name)
|
|
115
|
+
|
|
116
|
+
def empty(self):
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
with deadpool.Deadpool(max_workers=1) as pool:
|
|
120
|
+
worker = pool.get_process()
|
|
121
|
+
real_queue = pool.workers
|
|
122
|
+
pool.workers = TakenAfterEmptyCheck(real_queue)
|
|
123
|
+
clearing = _run(pool.clear_workers)
|
|
124
|
+
clearing.join(timeout=2)
|
|
125
|
+
stuck = clearing.is_alive()
|
|
126
|
+
pool.workers = real_queue
|
|
127
|
+
pool.done_with_process(worker)
|
|
128
|
+
assert not stuck
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_clear_workers_between_the_count_and_the_take_does_not_strand_a_task():
|
|
132
|
+
"""``clear_workers`` takes the only idle worker just after a task counted it
|
|
133
|
+
and so decided not to start one. The task must not be left waiting."""
|
|
134
|
+
with deadpool.Deadpool(max_workers=1) as pool:
|
|
135
|
+
clearing = []
|
|
136
|
+
|
|
137
|
+
def clear_wins():
|
|
138
|
+
clearing.append(_run(pool.clear_workers))
|
|
139
|
+
# Finishes at once if it can; waits for the lock otherwise.
|
|
140
|
+
clearing[0].join(timeout=0.5)
|
|
141
|
+
|
|
142
|
+
real_queue = pool.workers
|
|
143
|
+
pool.workers = _Hooked(real_queue, after=clear_wins)
|
|
144
|
+
future = pool.submit(abs, -1)
|
|
145
|
+
try:
|
|
146
|
+
assert future.result(timeout=5) == 1
|
|
147
|
+
finally:
|
|
148
|
+
if not future.done():
|
|
149
|
+
pool.add_worker_to_pool() # let a stranded task finish
|
|
150
|
+
clearing[0].join(timeout=10)
|
|
151
|
+
pool.workers = real_queue
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_a_direct_caller_waits_for_a_worker_when_every_one_is_busy():
|
|
155
|
+
"""``submit`` never gets here: it runs at most ``max_workers`` tasks. A caller
|
|
156
|
+
of ``get_process`` beyond that waits for a worker to be returned, and does
|
|
157
|
+
not start one."""
|
|
158
|
+
with deadpool.Deadpool(max_workers=1) as pool:
|
|
159
|
+
held = pool.get_process()
|
|
160
|
+
got = []
|
|
161
|
+
waiting = _run(lambda: got.append(pool.get_process()))
|
|
162
|
+
waiting.join(timeout=0.5)
|
|
163
|
+
assert waiting.is_alive() and got == []
|
|
164
|
+
pool.done_with_process(held)
|
|
165
|
+
waiting.join(timeout=10)
|
|
166
|
+
assert got == [held]
|
|
167
|
+
assert pool.get_statistics()["worker_processes_created"] == 1
|
|
168
|
+
pool.done_with_process(held)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/client-key.pem
RENAMED
|
File without changes
|
|
File without changes
|
{deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/rogue-client-key.pem
RENAMED
|
File without changes
|
{deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/rogue-client.pem
RENAMED
|
File without changes
|
{deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/certs/server-key.pem
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_cancellation.py
RENAMED
|
File without changes
|
|
File without changes
|
{deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_fork_timeout.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_public_end_to_end.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{deadpool_executor-2026.7.1 → deadpool_executor-2026.11.2}/tests/remote/test_unix_lifecycle.py
RENAMED
|
File without changes
|
|
File without changes
|