← Back to Pull requests

Add worker_stop_timeout: kill a worker that takes too long to stop #458

Merged
rstuart85 merged 3 files (1160 lines) on Dec 01, 2026 23:29 UTC
View on GitHub
rstuart85 rstuart85 commented on Nov 30, 2026 21:20 UTC
Author

Proposes worker_stop_timeout, off by default: a worker that is still alive that many seconds after the pool told it to stop is killed, with the processes it started. This is the stop deadline from the discussion on #452, as its own PR. Is this the shape you had in mind?

A worker whose finalizer is stuck never goes away. Since #454 it also holds up the idle timer, which stops no other worker until that one exits, and a shutdown(wait=True) that joins the timer.

Scope, following your notes on #452:

  • Every worker the pool stops while it is running: idle expiry, shrinking to min_workers, task count, memory, and clear_workers.

  • The deadline starts once the worker has been told to stop.

  • It can interrupt a finalizer. The docstring and the README say so, and say to choose a limit well above the longest a finalizer should take.

  • shutdown is separate: it puts no limit on the workers it stops itself, whose finalizers run to their end as now. One that was already stopping keeps its limit, so shutdown(wait=True) waits no longer than that for an idle worker that was being stopped.
  • How: the idle timer limits the stop it waits for. The stops that nothing waits for (recycling, shrinking, clear_workers) go to one daemon thread, which starts before the workers and sleeps until the earliest deadline. It holds only deadlines and process identities, so recycling does not hold on to file descriptors. The identity is taken when the worker starts, so a reused pid is neither searched for children nor signalled. A kill that fails, or that the process survives, is tried again after another timeout.

  • Shutdown: with the option on, a call that may retire a worker is counted, under the watcher's lock, from before the worker leaves the pool. The watcher ends when the pool is closed, no such call is running and no worker is still stopping. Once the pool is closed it looks every 0.1 s.

  • Startup: if the watcher cannot start, there are no workers yet and the constructor raises. If something later fails, the workers get the usual limit and the constructor raises without waiting for them. Without the option, startup failures are handled as before.

  • Long timeouts: each wait is at most an hour, and is repeated until the deadline. A failed wait counts neither as an exit nor as an expiry.
  • get_statistics() gains worker_stop_timeouts, only with the option. With the default, each worker also keeps a psutil.Process. 9745b6a skips the count above when the option is off, so a completed task and clear_workers no longer take its lock.

    Not covered: a worker killed while the interpreter is exiting, since the watching thread is a daemon.

    Tests (tests/test_worker_stop_timeout.py): a stalled finalizer for each of the five kinds of stop; a worker that closes its files, sentinel included, and stays; a finalizer that ends in time; very short and very long limits; a limit longer than one wait; a wait that fails; a stop message that is late, or fails; the default, also that neither a task nor clear_workers takes the count's lock; processes the worker started, also when they cannot be listed; both halves of shutdown; a retirement that overlaps shutdown, and a closed pool being let go; several batches; a failed signal; logging that raises or blocks; a worker that has exited, one whose state cannot be read, and a pid that is another process's; each of the pool's threads failing to start, with stop messages that work and that fail; refused values.

    On 9745b6a the full suite passes on Python 3.10 to 3.14 and on 3.14t with the GIL off (289 each, one at a time). Its new test, test_by_default_no_stop_is_counted, holds the count's lock while a task completes, its worker is given back and clear_workers runs. It times out on 11daffb. Three mutants each fail a test: the early return removed, inverted, or taken with the option on too.

    The other mutants were not repeated on 9745b6a. Of the 26 run on 11daffb, 25 fail a test and one (a failed start of the idle timer that waits for the workers) hangs the run. 21 of them were new for the second review; the other 5 repeat earlier ones. Not repeated on either commit: the rest of the earlier mutants, and the runs under load.

    Diff: 1160 lines (+1082 / -78) across 3 files Reviewer: cjrh Review duration: 1568m
    All Vouch review confidence checks passed
    Residual risk 0.12 = Change Risk (0.46) × (1 − Review Confidence (0.74)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.46 · 1160 lines diff across 3 files
    0.46
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.56 · 5 substantive comment(s)
    0.56
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    73%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    22 items
    cjrh cjrh commented on code on Nov 30, 2026 23:03 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -513,9 +554,67 @@ def get_statistics(self) -> dict[str, typing.Any]:
                     counters.worker_processes_stopped_idle.value
                 )
                 stats["idle_sweep_errors"] = counters.idle_sweep_errors.value
    +        if self.worker_stop_timeout is not None:
    +            stats["worker_stop_timeouts"] = self._statistics.worker_stop_timeouts.value
     
             return stats
     
    +    def _stop_worker(self, worker: WorkerProcess, wait: bool = False):
    +        """Tell a worker that has left the pool to stop."""
    +        if self.worker_stop_timeout is not None:
    +            self._limit_stop(worker, self.worker_stop_timeout)
    +        worker.shutdown(wait=wait)
    +
    +    def _limit_stop(self, worker: WorkerProcess, timeout: float):
    +        with self._stopping_lock:
    +            self._stopping.append((time.monotonic() + timeout, worker))
    +            if self._stop_watcher is not None:
    +                return
    +            watcher = threading.Thread(
    +                target=self._watch_stopping,
    +                args=(timeout,),
    +                name="deadpool.stop",
    +                daemon=True,
    +            )
    +            try:
    +                watcher.start()
    +            except Exception:
    +                logger.exception("Could not watch a stopping worker; will try again.")
    +            else:
    +                self._stop_watcher = watcher
    +
    +    def _watch_stopping(self, timeout: float):
    +        interval = max(0.05, min(timeout / 4, 1.0))
    +        while True:
    +            # Until one exits, so that it is let go of at once, or a limit is near.
    +            with self._stopping_lock:
    +                sentinels = [w.process.sentinel for _, w in self._stopping]
    +            exited = mp_connection.wait(sentinels, timeout=interval)
    +            with self._stopping_lock:
    +                now = time.monotonic()
    +                # Asking also reaps one that has exited, and dropping it frees its
    +                # file descriptors. One that something else has reaped can look
    +                # alive for good.
    +                alive = [
    +                    (t, w)
    +                    for t, w in self._stopping
    +                    if w.is_alive() and w.process.sentinel not in exited
    +                ]
    +                overdue = [w for t, w in alive if t <= now]
    +                # A kill can stay pending in the kernel: try again later.
    +                self._stopping = [
    +                    (now + timeout if t <= now else t, w) for t, w in alive
    +                ]
    +                if not alive:
    +                    self._stop_watcher = None
    +                    return
    +            for worker in overdue:
    +                logger.warning(
    +                    f"Worker {worker.pid} did not stop within {timeout} s; killing it."
    +                )
    +                self._statistics.worker_stop_timeouts.increment()
    +                worker.kill()

    One transient PermissionError from the worker kill ended the watcher. Its thread object stayed in _stop_watcher, so the next retirement appended a worker and returned. Both workers outlived their deadlines.

    Please handle signal failures per worker, leave that worker eligible for retry, and continue with the rest of the batch. Keep application logging off the path to sending those signals. If the watcher itself exits unexpectedly, clear its registration under the lock and ensure pending stops still have someone to enforce them. A recovery test can fail one signal attempt, then observe both workers exit and a subsequent job complete.

    cjrh cjrh commented on code on Nov 30, 2026 23:03 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -535,7 +634,7 @@ def _run_idle_timer(self, workers: _IdleWorkers):
                     if worker is not None:
                         self._statistics.worker_processes_stopped_idle.increment()
                         try:
    -                        worker.shutdown()
    +                        self._stop_worker(worker, wait=True)

    If the watcher fails to start on idle expiry, this thread enters an unbounded join. It then cannot reach the next retirement that would retry startup. With a 150 ms deadline, shutdown was still waiting after 650 ms and returned only when I released the finalizer. I also observed the idle timer and watcher both reading the same forkserver exit status, producing a spurious exit code of 255.

    This path already has a thread available to wait. I'd have it send the graceful stop, join for the time remaining, and escalate if the original worker is still alive. Keep this worker out of the asynchronous watch list. That gives idle retirement one owner for both the deadline and the join.

    cjrh cjrh commented on code on Nov 30, 2026 23:04 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -223,6 +228,17 @@ def shutdown(self, wait=True):
         def is_alive(self):
             return self.process.is_alive()
     
    +    def kill(self):
    +        """Kill the process and those it started, without waiting for them."""
    +        started = []
    +        with contextlib.suppress(psutil.Error):
    +            # Listed first: they stop being its children once it is gone.
    +            started = psutil.Process(self.pid).children(recursive=True)

    A worker can exit after the overdue list is built and before this PID lookup. If the PID has been reused, the descendants found here belong to another process. This finding comes from inspecting the code.

    Please capture the worker's process identity at startup and use it for descendant discovery and for signalling the worker itself. The same identity can settle an ambiguous exit notification: on fork/spawn, closing the worker's end of the sentinel pipe during cleanup can wake the watcher while the worker is still alive. Confirm exit before dropping its deadline.

    cjrh cjrh commented on code on Nov 30, 2026 23:04 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -513,9 +554,67 @@ def get_statistics(self) -> dict[str, typing.Any]:
                     counters.worker_processes_stopped_idle.value
                 )
                 stats["idle_sweep_errors"] = counters.idle_sweep_errors.value
    +        if self.worker_stop_timeout is not None:
    +            stats["worker_stop_timeouts"] = self._statistics.worker_stop_timeouts.value
     
             return stats
     
    +    def _stop_worker(self, worker: WorkerProcess, wait: bool = False):
    +        """Tell a worker that has left the pool to stop."""
    +        if self.worker_stop_timeout is not None:
    +            self._limit_stop(worker, self.worker_stop_timeout)

    The deadline starts before the stop message is sent. When I delayed the sender, the watcher killed a healthy worker before it received the message, so even its trivial finalizer never ran. The 50 ms polling floor produces the opposite error: a 25 ms finalizer completed under a 5 ms limit in three runs, each reporting zero timeouts.

    I'd send the stop request, record its monotonic deadline at handoff, and pass that absolute deadline to whichever path owns the wait. The asynchronous watcher can wait for an exit or the earliest outstanding deadline. This also removes the polling-floor and quarter-timeout tuning constants.

    cjrh cjrh commented on code on Nov 30, 2026 23:04 UTC
    Code Review
    tests/test_worker_stop_timeout.py:1
    @@ -0,0 +1,268 @@
    +"""How long a worker may take to stop: ``Deadpool(worker_stop_timeout=...)``."""
    +
    +import contextlib
    +import math
    +import os
    +import subprocess
    +import sys
    +import threading
    +import time
    +
    +import psutil
    +import pytest
    +
    +from deadpool import Deadpool
    +from deadpool._pool import WorkerProcess
    +
    +
    +def wait_until(predicate, timeout=10):
    +    deadline = time.monotonic() + timeout
    +    while not predicate():
    +        if time.monotonic() >= deadline:
    +            raise AssertionError("Timed out waiting for " + repr(predicate))
    +        time.sleep(0.01)
    +
    +
    +def stall_while(marker):
    +    """A finalizer that does not end while the marker file exists."""
    +    while marker.exists():
    +        time.sleep(0.02)
    +
    +
    +def finish_slowly(seconds, done):
    +    time.sleep(seconds)
    +    done.touch()
    +
    +
    +def start_helper():
    +    """Start a process from the worker; its pid and the worker's."""
    +    helper = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
    +    return helper.pid, os.getpid()
    +
    +
    +def gone(pid):
    +    try:
    +        return psutil.Process(pid).status() == psutil.STATUS_ZOMBIE
    +    except psutil.NoSuchProcess:
    +        return True
    +
    +
    +def timeouts(pool):
    +    return pool.get_statistics()["worker_stop_timeouts"]
    +
    +
    +@pytest.fixture
    +def marker(tmp_path):
    +    path = tmp_path / "stalled"
    +    path.touch()
    +    yield path
    +    path.unlink(missing_ok=True)
    +
    +
    +@contextlib.contextmanager
    +def stalling_pool(marker, **options):
    +    """A pool whose workers do not finish stopping until the block ends."""
    +    with Deadpool(
    +        **{"max_workers": 1, **options}, finalizer=stall_while, finalargs=(marker,)
    +    ) as pool:
    +        try:
    +            yield pool
    +        finally:
    +            marker.unlink(missing_ok=True)
    +
    +
    +def watching():
    +    return "deadpool.stop" in {t.name for t in threading.enumerate()}
    +
    +
    +@pytest.mark.parametrize("bad", [0, -1, math.inf, math.nan])
    +def test_timeout_must_be_positive_and_finite(bad):
    +    with pytest.raises(ValueError, match="worker_stop_timeout"):
    +        Deadpool(max_workers=1, worker_stop_timeout=bad)
    +
    +
    +@pytest.mark.parametrize(
    +    "options, stop",
    +    [
    +        pytest.param({"max_tasks_per_child": 1}, None, id="task count"),
    +        pytest.param({"max_worker_memory_bytes": 1}, None, id="memory"),
    +        pytest.param({"min_workers": 1, "max_workers": 2}, None, id="shrink"),
    +        pytest.param(
    +            {"min_workers": 1, "max_workers": 2, "idle_timeout": 0.2}, None, id="idle"
    +        ),
    +        pytest.param({}, Deadpool.clear_workers, id="clear_workers"),
    +    ],
    +)
    +def test_worker_that_does_not_stop_in_time_is_killed(marker, options, stop):
    +    with stalling_pool(marker, **options, worker_stop_timeout=0.5) as pool:
    +        before = list(pool.existing_workers)
    +        pool.submit(os.getpid).result(timeout=5)
    +        if stop:
    +            # A result can arrive before its worker is back in the pool.
    +            wait_until(lambda: pool.get_statistics()["worker_processes_idle"] == 1)
    +            stop(pool)
    +        wait_until(lambda: timeouts(pool) == 1)
    +        wait_until(lambda: any(gone(w.pid) for w in before))
    +
    +
    +def test_worker_that_stops_in_time_is_left_to_finish(tmp_path):
    +    done = tmp_path / "done"
    +    with Deadpool(
    +        max_workers=1,
    +        max_tasks_per_child=1,
    +        finalizer=finish_slowly,
    +        finalargs=(2.5, done),  # Long enough for two checks.
    +        worker_stop_timeout=8,
    +    ) as pool:
    +        pool.submit(os.getpid).result(timeout=5)
    +        wait_until(done.exists)
    +        assert timeouts(pool) == 0
    +
    +
    +def test_by_default_a_stalled_worker_is_left_alone(marker):
    +    wait_until(lambda: not watching())  # Those of earlier tests.
    +    with stalling_pool(marker, max_tasks_per_child=1) as pool:
    +        stalled = pool.submit(os.getpid).result(timeout=5)
    +        time.sleep(1.5)
    +        assert not gone(stalled)
    +        assert "worker_stop_timeouts" not in pool.get_statistics()
    +        assert not watching()
    +
    +
    +def test_processes_the_worker_started_are_killed_too(marker):
    +    with stalling_pool(marker, max_tasks_per_child=1, worker_stop_timeout=0.5) as pool:
    +        helper, worker = pool.submit(start_helper).result(timeout=5)
    +        wait_until(lambda: gone(worker))
    +        wait_until(lambda: gone(helper))
    +
    +
    +def test_shutdown_lets_the_workers_it_stops_finish(tmp_path):
    +    done = tmp_path / "done"
    +    with Deadpool(
    +        max_workers=1,
    +        finalizer=finish_slowly,
    +        finalargs=(1.0, done),
    +        worker_stop_timeout=0.2,
    +    ):
    +        pass
    +    assert done.exists()
    +
    +
    +def test_shutdown_waits_no_longer_than_the_timeout_for_an_idle_worker(marker):
    +    with stalling_pool(
    +        marker,
    +        max_workers=2,
    +        min_workers=1,
    +        idle_timeout=0.2,
    +        worker_stop_timeout=1.5,
    +    ) as pool:
    +        wait_until(lambda: pool.get_statistics()["worker_processes_stopped_idle"] == 1)
    +        # Only the worker that is already stopping is stalled.
    +        time.sleep(0.3)
    +        stalled = [w for w in pool.existing_workers if w not in idle_workers(pool)]
    +        assert len(stalled) == 1
    +        keep = idle_workers(pool)[0]
    +        closing = threading.Thread(target=pool.shutdown)
    +        closing.start()
    +        wait_until(lambda: timeouts(pool) == 1)
    +        marker.unlink()
    +        closing.join(timeout=10)
    +        assert not closing.is_alive()
    +        assert gone(stalled[0].pid) and gone(keep.pid)
    +
    +
    +def idle_workers(pool):
    +    return [worker for _, worker in list(pool.workers.queue)]

    Please rework these tests around the public API. Reading pool.workers.queue couples this test to the tuple layout. Checking for a thread named deadpool.stop in the restart and multi-worker tests also ties the suite to one implementation, and can pick up threads from earlier pools.

    For the idle/shutdown case, have the first finalizer record its PID and wait on a marker, and let subsequent finalizers return. Once that first marker appears, call shutdown(wait=True) with a bounded test wait and assert it returns and the recorded PID is gone. That also avoids the fixed sleep and exercises the distinction between an already-retiring worker and one stopped by shutdown.

    For recycling or clearing, get PIDs from submit(os.getpid) or finalizer markers, retire two batches, and verify that the retired processes disappear and a later submission succeeds. Keep narrow fault injection for errors such as a failed signal that are hard to induce portably. Assert recovery through worker lifetime, futures, shutdown, and the public statistics.

    cjrh cjrh requested changes on Nov 30, 2026 23:04 UTC
    Changes Requested Reviewer

    I'd go ahead with the parent-side retirement timeout. Starting from the pool's stop request covers a stalled initializer, finalizer, or atexit handler on a worker that is already retiring. The documented behavior for workers stopped by explicit shutdown makes sense to keep.

    I'm requesting changes because the pool can lose deadline enforcement after a single transient failure. The simplification I'd make first is to let the idle timer finish the stop it already waits for. That leaves the watcher responsible only for asynchronous retirements and keeps recycling asynchronous. Both paths can use the same stop-request and identity-checked kill operations.

    I'd keep the parameterized coverage of all five retirement paths and make the tests assert what a caller can observe. The existing descendant test is a good model: a submitted job returns PIDs, and the test checks what happened to those processes.

    I reviewed 9509a7d. All 252 tests passed on CPython 3.14, and all 45 stop-timeout and idle-worker tests passed on free-threaded 3.14. The inline comments include the cases I found outside that coverage.

    harness=Codex,model=GPT-6,reasoning=unspecified

    rstuart85 rstuart85 commented on code on Dec 01, 2026 01:21 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -513,9 +554,67 @@ def get_statistics(self) -> dict[str, typing.Any]:
                     counters.worker_processes_stopped_idle.value
                 )
                 stats["idle_sweep_errors"] = counters.idle_sweep_errors.value
    +        if self.worker_stop_timeout is not None:
    +            stats["worker_stop_timeouts"] = self._statistics.worker_stop_timeouts.value
     
             return stats
     
    +    def _stop_worker(self, worker: WorkerProcess, wait: bool = False):
    +        """Tell a worker that has left the pool to stop."""
    +        if self.worker_stop_timeout is not None:
    +            self._limit_stop(worker, self.worker_stop_timeout)
    +        worker.shutdown(wait=wait)
    +
    +    def _limit_stop(self, worker: WorkerProcess, timeout: float):
    +        with self._stopping_lock:
    +            self._stopping.append((time.monotonic() + timeout, worker))
    +            if self._stop_watcher is not None:
    +                return
    +            watcher = threading.Thread(
    +                target=self._watch_stopping,
    +                args=(timeout,),
    +                name="deadpool.stop",
    +                daemon=True,
    +            )
    +            try:
    +                watcher.start()
    +            except Exception:
    +                logger.exception("Could not watch a stopping worker; will try again.")
    +            else:
    +                self._stop_watcher = watcher
    +
    +    def _watch_stopping(self, timeout: float):
    +        interval = max(0.05, min(timeout / 4, 1.0))
    +        while True:
    +            # Until one exits, so that it is let go of at once, or a limit is near.
    +            with self._stopping_lock:
    +                sentinels = [w.process.sentinel for _, w in self._stopping]
    +            exited = mp_connection.wait(sentinels, timeout=interval)
    +            with self._stopping_lock:
    +                now = time.monotonic()
    +                # Asking also reaps one that has exited, and dropping it frees its
    +                # file descriptors. One that something else has reaped can look
    +                # alive for good.
    +                alive = [
    +                    (t, w)
    +                    for t, w in self._stopping
    +                    if w.is_alive() and w.process.sentinel not in exited
    +                ]
    +                overdue = [w for t, w in alive if t <= now]
    +                # A kill can stay pending in the kernel: try again later.
    +                self._stopping = [
    +                    (now + timeout if t <= now else t, w) for t, w in alive
    +                ]
    +                if not alive:
    +                    self._stop_watcher = None
    +                    return
    +            for worker in overdue:
    +                logger.warning(
    +                    f"Worker {worker.pid} did not stop within {timeout} s; killing it."
    +                )
    +                self._statistics.worker_stop_timeouts.increment()
    +                worker.kill()

    Each worker is put back with a new deadline before anything is signalled, and each kill is on its own, so one failure delays that worker and no other. The kill path does not log. There is no registration to clear: the watcher runs for as long as the pool has the option. test_one_failed_signal_does_not_free_any_worker, ..._an_idle_worker and test_logging_does_not_keep_a_worker_alive (a handler that raises, and one that blocks).

    rstuart85 rstuart85 commented on code on Dec 01, 2026 01:21 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -535,7 +634,7 @@ def _run_idle_timer(self, workers: _IdleWorkers):
                     if worker is not None:
                         self._statistics.worker_processes_stopped_idle.increment()
                         try:
    -                        worker.shutdown()
    +                        self._stop_worker(worker, wait=True)

    The idle timer sends the stop, waits out the limit, kills the worker if it is still alive, and tries again if that fails. It never touches the watch list.

    rstuart85 rstuart85 commented on code on Dec 01, 2026 01:21 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -223,6 +228,17 @@ def shutdown(self, wait=True):
         def is_alive(self):
             return self.process.is_alive()
     
    +    def kill(self):
    +        """Kill the process and those it started, without waiting for them."""
    +        started = []
    +        with contextlib.suppress(psutil.Error):
    +            # Listed first: they stop being its children once it is gone.
    +            started = psutil.Process(self.pid).children(recursive=True)

    Each worker keeps the psutil.Process made when it started, and that is what is checked and killed, so a reused pid is neither searched for children nor signalled. Exit is confirmed with it too: a worker that closes its end of the sentinel and stays alive is still killed (test_a_worker_that_closes_its_files_keeps_its_limit, for spawn and forkserver). The watcher does not read exit statuses, so it cannot take one from multiprocessing.

    rstuart85 rstuart85 commented on code on Dec 01, 2026 01:21 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -513,9 +554,67 @@ def get_statistics(self) -> dict[str, typing.Any]:
                     counters.worker_processes_stopped_idle.value
                 )
                 stats["idle_sweep_errors"] = counters.idle_sweep_errors.value
    +        if self.worker_stop_timeout is not None:
    +            stats["worker_stop_timeouts"] = self._statistics.worker_stop_timeouts.value
     
             return stats
     
    +    def _stop_worker(self, worker: WorkerProcess, wait: bool = False):
    +        """Tell a worker that has left the pool to stop."""
    +        if self.worker_stop_timeout is not None:
    +            self._limit_stop(worker, self.worker_stop_timeout)

    The deadline is taken after the message is sent, and the watcher sleeps until the earliest one, with no floor. It holds only identities and deadlines, so no descriptors are kept for workers that have exited.

    rstuart85 rstuart85 commented on code on Dec 01, 2026 01:21 UTC
    Code Review
    tests/test_worker_stop_timeout.py:1
    @@ -0,0 +1,268 @@
    +"""How long a worker may take to stop: ``Deadpool(worker_stop_timeout=...)``."""
    +
    +import contextlib
    +import math
    +import os
    +import subprocess
    +import sys
    +import threading
    +import time
    +
    +import psutil
    +import pytest
    +
    +from deadpool import Deadpool
    +from deadpool._pool import WorkerProcess
    +
    +
    +def wait_until(predicate, timeout=10):
    +    deadline = time.monotonic() + timeout
    +    while not predicate():
    +        if time.monotonic() >= deadline:
    +            raise AssertionError("Timed out waiting for " + repr(predicate))
    +        time.sleep(0.01)
    +
    +
    +def stall_while(marker):
    +    """A finalizer that does not end while the marker file exists."""
    +    while marker.exists():
    +        time.sleep(0.02)
    +
    +
    +def finish_slowly(seconds, done):
    +    time.sleep(seconds)
    +    done.touch()
    +
    +
    +def start_helper():
    +    """Start a process from the worker; its pid and the worker's."""
    +    helper = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
    +    return helper.pid, os.getpid()
    +
    +
    +def gone(pid):
    +    try:
    +        return psutil.Process(pid).status() == psutil.STATUS_ZOMBIE
    +    except psutil.NoSuchProcess:
    +        return True
    +
    +
    +def timeouts(pool):
    +    return pool.get_statistics()["worker_stop_timeouts"]
    +
    +
    +@pytest.fixture
    +def marker(tmp_path):
    +    path = tmp_path / "stalled"
    +    path.touch()
    +    yield path
    +    path.unlink(missing_ok=True)
    +
    +
    +@contextlib.contextmanager
    +def stalling_pool(marker, **options):
    +    """A pool whose workers do not finish stopping until the block ends."""
    +    with Deadpool(
    +        **{"max_workers": 1, **options}, finalizer=stall_while, finalargs=(marker,)
    +    ) as pool:
    +        try:
    +            yield pool
    +        finally:
    +            marker.unlink(missing_ok=True)
    +
    +
    +def watching():
    +    return "deadpool.stop" in {t.name for t in threading.enumerate()}
    +
    +
    +@pytest.mark.parametrize("bad", [0, -1, math.inf, math.nan])
    +def test_timeout_must_be_positive_and_finite(bad):
    +    with pytest.raises(ValueError, match="worker_stop_timeout"):
    +        Deadpool(max_workers=1, worker_stop_timeout=bad)
    +
    +
    +@pytest.mark.parametrize(
    +    "options, stop",
    +    [
    +        pytest.param({"max_tasks_per_child": 1}, None, id="task count"),
    +        pytest.param({"max_worker_memory_bytes": 1}, None, id="memory"),
    +        pytest.param({"min_workers": 1, "max_workers": 2}, None, id="shrink"),
    +        pytest.param(
    +            {"min_workers": 1, "max_workers": 2, "idle_timeout": 0.2}, None, id="idle"
    +        ),
    +        pytest.param({}, Deadpool.clear_workers, id="clear_workers"),
    +    ],
    +)
    +def test_worker_that_does_not_stop_in_time_is_killed(marker, options, stop):
    +    with stalling_pool(marker, **options, worker_stop_timeout=0.5) as pool:
    +        before = list(pool.existing_workers)
    +        pool.submit(os.getpid).result(timeout=5)
    +        if stop:
    +            # A result can arrive before its worker is back in the pool.
    +            wait_until(lambda: pool.get_statistics()["worker_processes_idle"] == 1)
    +            stop(pool)
    +        wait_until(lambda: timeouts(pool) == 1)
    +        wait_until(lambda: any(gone(w.pid) for w in before))
    +
    +
    +def test_worker_that_stops_in_time_is_left_to_finish(tmp_path):
    +    done = tmp_path / "done"
    +    with Deadpool(
    +        max_workers=1,
    +        max_tasks_per_child=1,
    +        finalizer=finish_slowly,
    +        finalargs=(2.5, done),  # Long enough for two checks.
    +        worker_stop_timeout=8,
    +    ) as pool:
    +        pool.submit(os.getpid).result(timeout=5)
    +        wait_until(done.exists)
    +        assert timeouts(pool) == 0
    +
    +
    +def test_by_default_a_stalled_worker_is_left_alone(marker):
    +    wait_until(lambda: not watching())  # Those of earlier tests.
    +    with stalling_pool(marker, max_tasks_per_child=1) as pool:
    +        stalled = pool.submit(os.getpid).result(timeout=5)
    +        time.sleep(1.5)
    +        assert not gone(stalled)
    +        assert "worker_stop_timeouts" not in pool.get_statistics()
    +        assert not watching()
    +
    +
    +def test_processes_the_worker_started_are_killed_too(marker):
    +    with stalling_pool(marker, max_tasks_per_child=1, worker_stop_timeout=0.5) as pool:
    +        helper, worker = pool.submit(start_helper).result(timeout=5)
    +        wait_until(lambda: gone(worker))
    +        wait_until(lambda: gone(helper))
    +
    +
    +def test_shutdown_lets_the_workers_it_stops_finish(tmp_path):
    +    done = tmp_path / "done"
    +    with Deadpool(
    +        max_workers=1,
    +        finalizer=finish_slowly,
    +        finalargs=(1.0, done),
    +        worker_stop_timeout=0.2,
    +    ):
    +        pass
    +    assert done.exists()
    +
    +
    +def test_shutdown_waits_no_longer_than_the_timeout_for_an_idle_worker(marker):
    +    with stalling_pool(
    +        marker,
    +        max_workers=2,
    +        min_workers=1,
    +        idle_timeout=0.2,
    +        worker_stop_timeout=1.5,
    +    ) as pool:
    +        wait_until(lambda: pool.get_statistics()["worker_processes_stopped_idle"] == 1)
    +        # Only the worker that is already stopping is stalled.
    +        time.sleep(0.3)
    +        stalled = [w for w in pool.existing_workers if w not in idle_workers(pool)]
    +        assert len(stalled) == 1
    +        keep = idle_workers(pool)[0]
    +        closing = threading.Thread(target=pool.shutdown)
    +        closing.start()
    +        wait_until(lambda: timeouts(pool) == 1)
    +        marker.unlink()
    +        closing.join(timeout=10)
    +        assert not closing.is_alive()
    +        assert gone(stalled[0].pid) and gone(keep.pid)
    +
    +
    +def idle_workers(pool):
    +    return [worker for _, worker in list(pool.workers.queue)]

    Rewritten on finalizer markers, PIDs, futures, shutdown and the statistics, with the idle/shutdown case as you describe. Fault injection is left for a failed signal, a message that is sent late or fails, a listing that is refused, a reused pid, a logging handler and a thread that cannot start.

    rstuart85 rstuart85 commented on Dec 01, 2026 01:21 UTC
    Author

    I reproduced the four you ran (one failed signal, a delayed sender, the 25 ms finalizer under 5 ms, and a watcher that cannot start) on 9509a7d, and all five are addressed in 0b62c6d and 134f2e0. As you suggested, the idle timer now limits the stop it waits for, and the watcher has only the stops nothing waits for. Both use the same identity-checked kill.

    One choice to check: the watcher now starts with the pool instead of on the first stop, so there is no restart to get wrong. If it cannot start, the constructor raises, as it does for the idle timer. And nothing is logged when a worker is killed; worker_stop_timeouts counts it.

    cjrh cjrh commented on code on Dec 01, 2026 14:11 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -513,9 +603,67 @@ def get_statistics(self) -> dict[str, typing.Any]:
                     counters.worker_processes_stopped_idle.value
                 )
                 stats["idle_sweep_errors"] = counters.idle_sweep_errors.value
    +        if self.worker_stop_timeout is not None:
    +            stats["worker_stop_timeouts"] = self._statistics.worker_stop_timeouts.value
     
             return stats
     
    +    def _stop_worker(self, worker: WorkerProcess):
    +        """Tell a worker that has left the pool to stop, without waiting."""
    +        try:
    +            worker.shutdown(wait=False)
    +        finally:
    +            if self.worker_stop_timeout is not None:
    +                # It has until then from when it was told, not from before.
    +                with self._stopping_changed:
    +                    deadline = time.monotonic() + self.worker_stop_timeout
    +                    self._stopping.append((deadline, worker.identity))

    A concurrent shutdown can leave this deadline with no watcher. I paused clear_workers() after it had sent the stop request and the worker had entered its finalizer, but before this append. shutdown() saw an empty retirement queue, set _no_more_stops, and the watcher exited. When I resumed clear_workers(), the worker stayed alive past three timeout periods with worker_stop_timeouts == 0. The documented guarantee covers this worker because it was already stopping. Could the handoff from the idle queue to the watcher share a lock with shutdown’s decision that there can be no further retirements? The lock only needs to cover that handoff and can be released before waiting for a worker to exit.

    cjrh cjrh commented on code on Dec 01, 2026 14:11 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -482,21 +564,29 @@ def __init__(
             self.busy_workers = set()  #  weakref.WeakSet()
     
             # THE ONLY ACTIVE, PERSISTENT STATE IN DEADPOOL IS THIS THREAD
    -        # BELOW, AND THE TIMER THREAD OF A POOL WITH AN IDLE TIMEOUT.
    +        # BELOW, THE TIMER THREAD OF A POOL WITH AN IDLE TIMEOUT AND THE
    +        # WATCHER THREAD OF A POOL WITH A WORKER STOP TIMEOUT.
             # PROTECT IT AT ALL COSTS.
             self.runner_thread = threading.Thread(
                 target=self.runner, name="deadpool.runner", daemon=True
             )
             self.runner_thread.start()
     
    -        if self._idle_timer is not None:
    -            try:
    +        try:
    +            if worker_stop_timeout is not None:
    +                threading.Thread(
    +                    target=self._watch_stopping,
    +                    args=(worker_stop_timeout,),
    +                    name="deadpool.stop",
    +                    daemon=True,
    +                ).start()
    +            if self._idle_timer is not None:
                     self._idle_timer.start()
    -            except Exception:
    -                self._idle_timer = None  # shutdown must only join a started timer
    -                self.shutdown()
    -                self.runner_thread.join()
    -                raise
    +        except Exception:
    +            self._idle_timer = None  # shutdown must only join a started timer
    +            self.shutdown()

    A failed watcher start can hang the constructor. Workers have already started by this point. When I made the watcher fail to start, this call waited in a worker finalizer even with a 120 ms stop timeout. The constructor raised the original error only after I released the finalizer. The caller has no pool handle to recover with. I’d either start the watcher before creating workers and clean it up if later startup fails, or forcibly terminate and reap the workers during constructor rollback.

    cjrh cjrh commented on code on Dec 01, 2026 14:11 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -223,6 +269,17 @@ def shutdown(self, wait=True):
         def is_alive(self):
             return self.process.is_alive()
     
    +    def wait_until_exited(self, timeout: float) -> bool:
    +        """Whether the process exits within the timeout."""
    +        deadline = time.monotonic() + timeout
    +        # It may close its end of the sentinel while it still has work to do.
    +        mp_connection.wait([self.process.sentinel], timeout)

    A valid long timeout can cause an immediate SIGKILL. On Linux, a 30-day worker_stop_timeout overflowed the underlying poll() timeout. The idle timer’s exception handler immediately killed a worker whose finalizer needed only 250 ms. The asynchronous path has a related failure: 1e12 seconds passes validation but raises OverflowError in Condition.wait(), ending the shared watcher. I’d cap each individual wait to a supported duration and recalculate the remaining time against the monotonic deadline. A wait error should never count as evidence that the deadline expired.

    cjrh cjrh commented on code on Dec 01, 2026 14:11 UTC
    Code Review
    deadpool/_pool.py:1
    @@ -1000,6 +1148,12 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None:
             if wait and self._idle_timer is not None:
                 self._idle_timer.join()
     
    +        # The watcher ends with the last worker that is stopping.
    +        with self._stopping_changed:
    +            self._stopping = deque(s for s in self._stopping if not s[1].has_exited())

    A worker finishing just after this check can keep the closed pool alive until its original deadline. I allowed a retiring worker to exit normally just after shutdown checked it, dropped the pool reference, and confirmed the worker was gone while the watcher and pool were still alive. Nothing wakes the watcher on that exit. Repeated short-lived pools with a long timeout can accumulate one thread per closed pool. During shutdown, could the watcher recheck outstanding workers at a bounded interval? Normal recycling can keep sleeping until the earliest deadline.

    cjrh cjrh commented on code on Dec 01, 2026 14:11 UTC
    Code Review
    tests/test_worker_stop_timeout.py:1
    @@ -0,0 +1,499 @@
    +"""How long a worker may take to stop: ``Deadpool(worker_stop_timeout=...)``."""
    +
    +import logging
    +import math
    +import os
    +import signal
    +import subprocess
    +import sys
    +import threading
    +import time
    +
    +import psutil
    +import pytest
    +
    +from deadpool import Deadpool
    +from deadpool._pool import WorkerProcess
    +
    +
    +def wait_until(predicate, timeout=15):
    +    deadline = time.monotonic() + timeout
    +    while not predicate():
    +        if time.monotonic() >= deadline:
    +            raise AssertionError("Timed out waiting for " + repr(predicate))
    +        time.sleep(0.01)
    +
    +
    +def gone(pid):
    +    try:
    +        return psutil.Process(pid).status() == psutil.STATUS_ZOMBIE
    +    except psutil.NoSuchProcess:
    +        return True
    +
    +
    +class Stalls:
    +    """A finalizer that notes its worker's pid, and does not end until released."""
    +
    +    def __init__(self, folder):
    +        self.folder = folder
    +        self.released = folder / "released"
    +
    +    def __call__(self):
    +        (self.folder / f"{os.getpid()}.pid").touch()
    +        while not self.released.exists():
    +            time.sleep(0.02)
    +
    +    def pids(self):
    +        return [int(path.stem) for path in self.folder.glob("*.pid")]
    +
    +    def release(self):
    +        self.released.touch()
    +
    +
    +class StallsFirst(Stalls):
    +    """Only the first worker to stop stalls."""
    +
    +    def __call__(self):
    +        if not self.pids():
    +            super().__call__()
    +
    +
    +class StallsWithoutFiles(Stalls):
    +    """Closes every file the worker has, among them its end of the sentinel."""
    +
    +    def __call__(self):
    +        os.closerange(3, 1024)
    +        super().__call__()
    +
    +
    +class Takes:
    +    """A finalizer that takes some time."""
    +
    +    def __init__(self, seconds, done):
    +        self.seconds = seconds
    +        self.done = done
    +
    +    def __call__(self):
    +        time.sleep(self.seconds)
    +        self.done.touch()
    +
    +
    +@pytest.fixture
    +def make_pool():
    +    """A pool that is shut down after the test, its stalled finalizers released."""
    +    made = []
    +
    +    def make(finalizer=None, **options):
    +        pool = Deadpool(**{"max_workers": 1, **options}, finalizer=finalizer)
    +        made.append((pool, finalizer))
    +        return pool
    +
    +    yield make
    +    for pool, finalizer in made:
    +        if isinstance(finalizer, Stalls):
    +            finalizer.release()
    +        pool.shutdown()
    +
    +
    +@pytest.fixture
    +def stalls(tmp_path):
    +    return Stalls(tmp_path)
    +
    +
    +def start_helper():
    +    """Start a process from the worker; its pid and the worker's."""
    +    helper = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
    +    return helper.pid, os.getpid()
    +
    +
    +def run(pool, fn=os.getpid):
    +    return pool.submit(fn).result(timeout=15)
    +
    +
    +def timeouts(pool):
    +    return pool.get_statistics()["worker_stop_timeouts"]
    +
    +
    +def wait_for_idle(pool, count):
    +    # A result can arrive before its worker is back in the pool.
    +    wait_until(lambda: pool.get_statistics()["worker_processes_idle"] == count)
    +
    +
    +@pytest.mark.parametrize("bad", [0, -1, math.inf, math.nan])
    +def test_timeout_must_be_positive_and_finite(bad):
    +    with pytest.raises(ValueError, match="worker_stop_timeout"):
    +        Deadpool(max_workers=1, worker_stop_timeout=bad)
    +
    +
    +# Every way the pool retires a worker that is running.
    +RETIREMENTS = [
    +    pytest.param({"max_tasks_per_child": 1}, id="task count"),
    +    pytest.param({"max_worker_memory_bytes": 1}, id="memory"),
    +    pytest.param({"min_workers": 1, "max_workers": 2}, id="shrink"),
    +    pytest.param({"min_workers": 1, "max_workers": 2, "idle_timeout": 0.2}, id="idle"),
    +    pytest.param({}, id="clear_workers"),
    +]
    +
    +
    +def retire(pool, options):
    +    run(pool)
    +    if not options:
    +        wait_for_idle(pool, 1)
    +        pool.clear_workers()
    +
    +
    +@pytest.mark.parametrize("options", RETIREMENTS)
    +def test_a_worker_that_does_not_stop_in_time_is_killed(make_pool, stalls, options):
    +    pool = make_pool(stalls, **options, worker_stop_timeout=0.5)
    +    retire(pool, options)
    +    wait_until(stalls.pids)
    +    (stalled,) = stalls.pids()
    +    wait_until(lambda: gone(stalled))
    +    assert timeouts(pool) == 1
    +    run(pool)
    +
    +
    +@pytest.mark.parametrize("options", [RETIREMENTS[0], RETIREMENTS[3]])
    +@pytest.mark.parametrize("context", ["spawn", "forkserver"])
    +def test_a_worker_that_closes_its_files_keeps_its_limit(
    +    make_pool, tmp_path, context, options
    +):
    +    stalls = StallsWithoutFiles(tmp_path)
    +    pool = make_pool(stalls, **options, worker_stop_timeout=1, mp_context=context)
    +    retire(pool, options)
    +    wait_until(stalls.pids)
    +    (stalled,) = stalls.pids()
    +    wait_until(lambda: gone(stalled))
    +    assert timeouts(pool) == 1
    +
    +
    +@pytest.mark.parametrize("options", [RETIREMENTS[0], RETIREMENTS[3]])
    +def test_a_worker_that_stops_in_time_is_left_to_finish(make_pool, tmp_path, options):
    +    done = tmp_path / "done"
    +    pool = make_pool(Takes(1, done), **options, worker_stop_timeout=10)
    +    retire(pool, options)
    +    wait_until(done.exists)
    +    assert timeouts(pool) == 0
    +
    +
    +def test_the_limit_is_kept_to_when_it_is_short(make_pool, tmp_path):
    +    """Any one worker can finish first on a busy machine, but not all of them."""
    +    pool = make_pool(
    +        Takes(0.01, tmp_path / "done"), max_tasks_per_child=1, worker_stop_timeout=0.002
    +    )
    +    for _ in range(10):
    +        run(pool)
    +    wait_until(lambda: timeouts(pool) > 0)
    +
    +
    +def test_the_limit_starts_when_the_worker_has_been_told(
    +    make_pool, tmp_path, monkeypatch
    +):
    +    tell = WorkerProcess.shutdown
    +
    +    def tell_late(worker, wait=True):
    +        time.sleep(3)
    +        tell(worker, wait)
    +
    +    monkeypatch.setattr(WorkerProcess, "shutdown", tell_late)
    +    done = tmp_path / "done"
    +    pool = make_pool(Takes(0, done), max_tasks_per_child=1, worker_stop_timeout=2)
    +    run(pool)
    +    wait_until(done.exists)
    +    assert timeouts(pool) == 0
    +
    +
    +def test_a_worker_whose_stop_message_fails_keeps_its_limit(
    +    make_pool, stalls, monkeypatch
    +):
    +    def fail(worker, wait=True):
    +        raise OSError("the message could not be sent")
    +
    +    pool = make_pool(stalls, worker_stop_timeout=0.5)
    +    worker = run(pool)
    +    wait_for_idle(pool, 1)
    +    with monkeypatch.context() as patch:
    +        patch.setattr(WorkerProcess, "shutdown", fail)
    +        with pytest.raises(OSError):
    +            pool.clear_workers()
    +    wait_until(lambda: gone(worker))
    +    assert run(pool) != worker
    +
    +
    +def test_by_default_a_stalled_worker_is_left_alone(make_pool, stalls):
    +    pool = make_pool(stalls, max_tasks_per_child=1)
    +    stalled = run(pool)
    +    time.sleep(1.5)
    +    assert not gone(stalled)
    +    assert "worker_stop_timeouts" not in pool.get_statistics()
    +
    +
    +def test_processes_the_worker_started_are_killed_too(make_pool, stalls):
    +    pool = make_pool(stalls, max_tasks_per_child=1, worker_stop_timeout=0.5)
    +    helper, worker = run(pool, start_helper)
    +    wait_until(lambda: gone(worker))
    +    wait_until(lambda: gone(helper))
    +
    +
    +def test_an_idle_worker_takes_the_processes_it_started_along(make_pool, stalls):
    +    pool = make_pool(
    +        stalls,
    +        max_workers=2,
    +        min_workers=1,
    +        idle_timeout=0.5,
    +        worker_stop_timeout=0.5,
    +    )
    +    helpers = [pool.submit(start_helper) for _ in range(2)]
    +    helpers = dict(reversed(f.result(timeout=15)) for f in helpers)
    +    wait_until(stalls.pids)
    +    (stalled,) = stalls.pids()
    +    wait_until(lambda: gone(stalled))
    +    if stalled in helpers:  # Both tasks can have gone to one worker.
    +        wait_until(lambda: gone(helpers[stalled]))
    +
    +
    +def test_shutdown_lets_the_workers_it_stops_finish(make_pool, tmp_path):
    +    done = tmp_path / "done"
    +    pool = make_pool(Takes(1, done), worker_stop_timeout=0.2)
    +    run(pool)
    +    pool.shutdown()
    +    assert done.exists()
    +    assert timeouts(pool) == 0
    +
    +
    +def test_shutdown_waits_no_longer_than_the_limit_for_an_idle_worker(
    +    make_pool, tmp_path
    +):
    +    stalls = StallsFirst(tmp_path)
    +    pool = make_pool(
    +        stalls,
    +        max_workers=2,
    +        min_workers=1,
    +        idle_timeout=0.2,
    +        worker_stop_timeout=1.5,
    +    )
    +    wait_until(stalls.pids)
    +    (stalled,) = stalls.pids()
    +    closing = threading.Thread(target=pool.shutdown)
    +    closing.start()
    +    closing.join(timeout=15)
    +    assert not closing.is_alive()
    +    assert gone(stalled)
    +    assert timeouts(pool) == 1
    +
    +
    +@pytest.mark.parametrize("wait", [True, False])
    +def test_a_worker_that_was_stopping_keeps_its_limit_after_shutdown(
    +    make_pool, tmp_path, wait
    +):
    +    stalls = StallsFirst(tmp_path)
    +    pool = make_pool(stalls, max_tasks_per_child=1, worker_stop_timeout=1.5)
    +    stalled = run(pool)
    +    wait_until(stalls.pids)
    +    pool.shutdown(wait=wait)
    +    wait_until(lambda: gone(stalled))
    +    assert timeouts(pool) == 1
    +
    +
    +def test_each_batch_of_workers_has_its_limit(make_pool, stalls):
    +    pool = make_pool(stalls, max_workers=3, worker_stop_timeout=0.5)
    +    wait_for_idle(pool, 3)
    +
    +    def clear_until_gone(total):
    +        pool.clear_workers()
    +        wait_until(lambda: len(stalls.pids()) == total)
    +        wait_until(lambda: all(gone(pid) for pid in stalls.pids()))
    +        assert run(pool) not in stalls.pids()
    +        wait_for_idle(pool, 1)
    +
    +    clear_until_gone(3)
    +    clear_until_gone(4)  # The task above started one worker.
    +    assert timeouts(pool) == 4
    +
    +
    +def test_shutdown_leaves_no_thread_behind(make_pool):
    +    before = set(threading.enumerate())
    +    pool = make_pool(max_tasks_per_child=1, worker_stop_timeout=60)
    +    for _ in range(3):
    +        run(pool)
    +    pool.shutdown()
    +    wait_until(lambda: not set(threading.enumerate()) - before)
    +
    +
    +def fail_once(monkeypatch):
    +    """The first process to be killed is not; those after it are."""
    +    failed = []
    +    kill = os.kill
    +
    +    def kill_or_fail(pid, sig):
    +        if sig == signal.SIGKILL and not failed:
    +            failed.append(pid)
    +            raise PermissionError("not now")
    +        return kill(pid, sig)
    +
    +    monkeypatch.setattr(os, "kill", kill_or_fail)
    +    return failed
    +
    +
    +def test_one_failed_signal_does_not_free_any_worker(make_pool, stalls, monkeypatch):
    +    failed = fail_once(monkeypatch)
    +    pool = make_pool(stalls, max_workers=2, worker_stop_timeout=0.5)
    +    wait_for_idle(pool, 2)
    +    pool.clear_workers()
    +    wait_until(lambda: len(stalls.pids()) == 2)
    +    workers = stalls.pids()
    +    wait_until(lambda: all(gone(pid) for pid in workers))
    +    assert failed and failed[0] in workers
    +    assert timeouts(pool) == 2
    +    assert run(pool) not in workers
    +
    +
    +def test_one_failed_signal_does_not_free_an_idle_worker(make_pool, stalls, monkeypatch):
    +    failed = fail_once(monkeypatch)
    +    pool = make_pool(
    +        stalls,
    +        max_workers=2,
    +        min_workers=1,
    +        idle_timeout=0.2,
    +        worker_stop_timeout=0.5,
    +    )
    +    wait_until(stalls.pids)
    +    stalled = stalls.pids()[0]
    +    wait_until(lambda: gone(stalled))
    +    assert failed == [stalled]
    +    assert timeouts(pool) >= 1
    +    assert run(pool) != stalled
    +
    +
    +@pytest.mark.parametrize("blocked", [False, True])
    +def test_logging_does_not_keep_a_worker_alive(make_pool, stalls, blocked):
    +    release = threading.Event()
    +
    +    class Handler(logging.Handler):
    +        def handle(self, record):
    +            release.wait() if blocked else 1 / 0
    +
    +    logger, handler = logging.getLogger("deadpool"), Handler(logging.INFO)
    +    logger.addHandler(handler)
    +    try:
    +        pool = make_pool(stalls, max_tasks_per_child=1, worker_stop_timeout=0.5)
    +        workers = [run(pool), run(pool)]
    +        wait_until(lambda: all(gone(pid) for pid in workers))
    +        assert run(pool) not in workers
    +    finally:
    +        release.set()
    +        logger.removeHandler(handler)
    +
    +
    +def test_a_worker_is_killed_when_what_it_started_cannot_be(
    +    make_pool, stalls, monkeypatch
    +):
    +    def refuse(process, recursive=False):
    +        raise psutil.AccessDenied()
    +
    +    monkeypatch.setattr(psutil.Process, "children", refuse)
    +    pool = make_pool(stalls, max_tasks_per_child=1, worker_stop_timeout=0.5)
    +    worker = run(pool)
    +    wait_until(lambda: gone(worker))
    +    assert timeouts(pool) == 1
    +
    +
    +@pytest.mark.parametrize(
    +    "error, killed",
    +    [
    +        pytest.param(psutil.AccessDenied(), True, id="cannot be read"),
    +        pytest.param(psutil.NoSuchProcess(0), False, id="just exited"),
    +    ],
    +)
    +def test_a_worker_whose_state_is_not_known(
    +    make_pool, stalls, monkeypatch, error, killed
    +):
    +    def fail(process):
    +        raise error
    +
    +    pool = make_pool(stalls, max_tasks_per_child=1, worker_stop_timeout=0.5)
    +    with monkeypatch.context() as patch:
    +        patch.setattr(psutil.Process, "status", fail)
    +        worker = run(pool)
    +        wait_until(stalls.pids)
    +        time.sleep(1)
    +    assert gone(worker) is killed
    +    assert timeouts(pool) == killed
    +
    +
    +def test_a_worker_that_was_gone_before_it_was_known(make_pool, stalls, monkeypatch):
    +    def fail(process, pid=None):
    +        raise psutil.NoSuchProcess(pid)
    +
    +    before = set(threading.enumerate())
    +    with monkeypatch.context() as patch:
    +        patch.setattr(psutil.Process, "__init__", fail)
    +        pool = make_pool(stalls, worker_stop_timeout=0.5)
    +    wait_for_idle(pool, 1)
    +    pool.clear_workers()  # Nothing is known of this one, so it has no limit.
    +    worker = run(pool)
    +    time.sleep(1)
    +    wait_for_idle(pool, 1)
    +    pool.clear_workers()
    +    wait_until(lambda: gone(worker))
    +    assert timeouts(pool) == 1
    +    stalls.release()
    +    pool.shutdown()
    +    wait_until(lambda: not set(threading.enumerate()) - before)
    +
    +
    +def test_a_worker_that_has_stopped_is_not_signalled(make_pool, monkeypatch):
    +    signalled = []
    +    kill = os.kill
    +
    +    def record(pid, sig):
    +        if sig == signal.SIGKILL:
    +            signalled.append(pid)
    +        return kill(pid, sig)
    +
    +    monkeypatch.setattr(os, "kill", record)
    +    pool = make_pool(max_tasks_per_child=1, worker_stop_timeout=1)
    +    workers = [run(pool) for _ in range(3)]
    +    wait_until(lambda: all(gone(pid) for pid in workers))
    +    time.sleep(1.5)  # Their limits pass.
    +    assert signalled == []
    +    assert timeouts(pool) == 0
    +
    +
    +def test_a_process_that_has_the_pid_of_a_worker_is_not_signalled(
    +    make_pool, stalls, monkeypatch
    +):
    +    pool = make_pool(stalls, max_tasks_per_child=1, worker_stop_timeout=1)
    +    worker = run(pool)
    +    wait_until(stalls.pids)
    +    # psutil says so when the pid belongs to a process that started later.
    +    running = psutil.Process.is_running
    +    monkeypatch.setattr(
    +        psutil.Process, "is_running", lambda p: p.pid != worker and running(p)
    +    )
    +    time.sleep(2)
    +    assert not gone(worker)
    +    assert timeouts(pool) == 0
    +
    +
    +def test_a_pool_that_cannot_keep_to_the_limit_is_not_made(monkeypatch):
    +    start = threading.Thread.start
    +    started = []
    +
    +    def refuse_second(thread):
    +        started.append(thread)
    +        if len(started) == 2:
    +            raise RuntimeError("thread could not start")
    +        return start(thread)
    +
    +    def children():
    +        return {p.pid for p in psutil.Process().children(recursive=True)}
    +
    +    before = children()
    +    monkeypatch.setattr(threading.Thread, "start", refuse_second)
    +    with pytest.raises(RuntimeError, match="could not start"):
    +        Deadpool(max_workers=1, worker_stop_timeout=1)
    +    assert len(started) == 2
    +    assert not started[0].is_alive()
    +    # The process that starts the others can stay.
    +    wait_until(lambda: len([p for p in children() - before if not gone(p)]) <= 2)

    This test assumes the watcher is exactly the second thread started, yet it allows two extra child processes to remain. It can therefore pass with the pool’s sole worker leaked. I’d keep the targeted startup fault injection and assert the behavior visible to the caller: construction raises promptly even with a blocking finalizer, and any worker PID recorded by the initializer exits.

    cjrh cjrh commented on code on Dec 01, 2026 14:11 UTC
    Code Review
    tests/test_worker_stop_timeout.py:1
    @@ -0,0 +1,499 @@
    +"""How long a worker may take to stop: ``Deadpool(worker_stop_timeout=...)``."""
    +
    +import logging
    +import math
    +import os
    +import signal
    +import subprocess
    +import sys
    +import threading
    +import time
    +
    +import psutil
    +import pytest
    +
    +from deadpool import Deadpool
    +from deadpool._pool import WorkerProcess
    +
    +
    +def wait_until(predicate, timeout=15):
    +    deadline = time.monotonic() + timeout
    +    while not predicate():
    +        if time.monotonic() >= deadline:
    +            raise AssertionError("Timed out waiting for " + repr(predicate))
    +        time.sleep(0.01)
    +
    +
    +def gone(pid):
    +    try:
    +        return psutil.Process(pid).status() == psutil.STATUS_ZOMBIE
    +    except psutil.NoSuchProcess:
    +        return True
    +
    +
    +class Stalls:
    +    """A finalizer that notes its worker's pid, and does not end until released."""
    +
    +    def __init__(self, folder):
    +        self.folder = folder
    +        self.released = folder / "released"
    +
    +    def __call__(self):
    +        (self.folder / f"{os.getpid()}.pid").touch()
    +        while not self.released.exists():
    +            time.sleep(0.02)
    +
    +    def pids(self):
    +        return [int(path.stem) for path in self.folder.glob("*.pid")]
    +
    +    def release(self):
    +        self.released.touch()
    +
    +
    +class StallsFirst(Stalls):
    +    """Only the first worker to stop stalls."""
    +
    +    def __call__(self):
    +        if not self.pids():
    +            super().__call__()
    +
    +
    +class StallsWithoutFiles(Stalls):
    +    """Closes every file the worker has, among them its end of the sentinel."""
    +
    +    def __call__(self):
    +        os.closerange(3, 1024)
    +        super().__call__()
    +
    +
    +class Takes:
    +    """A finalizer that takes some time."""
    +
    +    def __init__(self, seconds, done):
    +        self.seconds = seconds
    +        self.done = done
    +
    +    def __call__(self):
    +        time.sleep(self.seconds)
    +        self.done.touch()
    +
    +
    +@pytest.fixture
    +def make_pool():
    +    """A pool that is shut down after the test, its stalled finalizers released."""
    +    made = []
    +
    +    def make(finalizer=None, **options):
    +        pool = Deadpool(**{"max_workers": 1, **options}, finalizer=finalizer)
    +        made.append((pool, finalizer))
    +        return pool
    +
    +    yield make
    +    for pool, finalizer in made:
    +        if isinstance(finalizer, Stalls):
    +            finalizer.release()
    +        pool.shutdown()
    +
    +
    +@pytest.fixture
    +def stalls(tmp_path):
    +    return Stalls(tmp_path)
    +
    +
    +def start_helper():
    +    """Start a process from the worker; its pid and the worker's."""
    +    helper = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
    +    return helper.pid, os.getpid()
    +
    +
    +def run(pool, fn=os.getpid):
    +    return pool.submit(fn).result(timeout=15)
    +
    +
    +def timeouts(pool):
    +    return pool.get_statistics()["worker_stop_timeouts"]
    +
    +
    +def wait_for_idle(pool, count):
    +    # A result can arrive before its worker is back in the pool.
    +    wait_until(lambda: pool.get_statistics()["worker_processes_idle"] == count)
    +
    +
    +@pytest.mark.parametrize("bad", [0, -1, math.inf, math.nan])
    +def test_timeout_must_be_positive_and_finite(bad):
    +    with pytest.raises(ValueError, match="worker_stop_timeout"):
    +        Deadpool(max_workers=1, worker_stop_timeout=bad)
    +
    +
    +# Every way the pool retires a worker that is running.
    +RETIREMENTS = [
    +    pytest.param({"max_tasks_per_child": 1}, id="task count"),
    +    pytest.param({"max_worker_memory_bytes": 1}, id="memory"),
    +    pytest.param({"min_workers": 1, "max_workers": 2}, id="shrink"),
    +    pytest.param({"min_workers": 1, "max_workers": 2, "idle_timeout": 0.2}, id="idle"),
    +    pytest.param({}, id="clear_workers"),
    +]
    +
    +
    +def retire(pool, options):
    +    run(pool)
    +    if not options:
    +        wait_for_idle(pool, 1)
    +        pool.clear_workers()
    +
    +
    +@pytest.mark.parametrize("options", RETIREMENTS)
    +def test_a_worker_that_does_not_stop_in_time_is_killed(make_pool, stalls, options):
    +    pool = make_pool(stalls, **options, worker_stop_timeout=0.5)
    +    retire(pool, options)
    +    wait_until(stalls.pids)
    +    (stalled,) = stalls.pids()
    +    wait_until(lambda: gone(stalled))
    +    assert timeouts(pool) == 1
    +    run(pool)
    +
    +
    +@pytest.mark.parametrize("options", [RETIREMENTS[0], RETIREMENTS[3]])
    +@pytest.mark.parametrize("context", ["spawn", "forkserver"])
    +def test_a_worker_that_closes_its_files_keeps_its_limit(
    +    make_pool, tmp_path, context, options
    +):
    +    stalls = StallsWithoutFiles(tmp_path)
    +    pool = make_pool(stalls, **options, worker_stop_timeout=1, mp_context=context)
    +    retire(pool, options)
    +    wait_until(stalls.pids)
    +    (stalled,) = stalls.pids()
    +    wait_until(lambda: gone(stalled))
    +    assert timeouts(pool) == 1
    +
    +
    +@pytest.mark.parametrize("options", [RETIREMENTS[0], RETIREMENTS[3]])
    +def test_a_worker_that_stops_in_time_is_left_to_finish(make_pool, tmp_path, options):
    +    done = tmp_path / "done"
    +    pool = make_pool(Takes(1, done), **options, worker_stop_timeout=10)
    +    retire(pool, options)
    +    wait_until(done.exists)
    +    assert timeouts(pool) == 0
    +
    +
    +def test_the_limit_is_kept_to_when_it_is_short(make_pool, tmp_path):
    +    """Any one worker can finish first on a busy machine, but not all of them."""
    +    pool = make_pool(
    +        Takes(0.01, tmp_path / "done"), max_tasks_per_child=1, worker_stop_timeout=0.002
    +    )
    +    for _ in range(10):
    +        run(pool)
    +    wait_until(lambda: timeouts(pool) > 0)
    +
    +
    +def test_the_limit_starts_when_the_worker_has_been_told(
    +    make_pool, tmp_path, monkeypatch
    +):
    +    tell = WorkerProcess.shutdown
    +
    +    def tell_late(worker, wait=True):
    +        time.sleep(3)
    +        tell(worker, wait)
    +
    +    monkeypatch.setattr(WorkerProcess, "shutdown", tell_late)
    +    done = tmp_path / "done"
    +    pool = make_pool(Takes(0, done), max_tasks_per_child=1, worker_stop_timeout=2)
    +    run(pool)
    +    wait_until(done.exists)
    +    assert timeouts(pool) == 0
    +
    +
    +def test_a_worker_whose_stop_message_fails_keeps_its_limit(
    +    make_pool, stalls, monkeypatch
    +):
    +    def fail(worker, wait=True):
    +        raise OSError("the message could not be sent")
    +
    +    pool = make_pool(stalls, worker_stop_timeout=0.5)
    +    worker = run(pool)
    +    wait_for_idle(pool, 1)
    +    with monkeypatch.context() as patch:
    +        patch.setattr(WorkerProcess, "shutdown", fail)
    +        with pytest.raises(OSError):
    +            pool.clear_workers()
    +    wait_until(lambda: gone(worker))
    +    assert run(pool) != worker
    +
    +
    +def test_by_default_a_stalled_worker_is_left_alone(make_pool, stalls):
    +    pool = make_pool(stalls, max_tasks_per_child=1)
    +    stalled = run(pool)
    +    time.sleep(1.5)
    +    assert not gone(stalled)
    +    assert "worker_stop_timeouts" not in pool.get_statistics()
    +
    +
    +def test_processes_the_worker_started_are_killed_too(make_pool, stalls):
    +    pool = make_pool(stalls, max_tasks_per_child=1, worker_stop_timeout=0.5)
    +    helper, worker = run(pool, start_helper)
    +    wait_until(lambda: gone(worker))
    +    wait_until(lambda: gone(helper))
    +
    +
    +def test_an_idle_worker_takes_the_processes_it_started_along(make_pool, stalls):
    +    pool = make_pool(
    +        stalls,
    +        max_workers=2,
    +        min_workers=1,
    +        idle_timeout=0.5,
    +        worker_stop_timeout=0.5,
    +    )
    +    helpers = [pool.submit(start_helper) for _ in range(2)]
    +    helpers = dict(reversed(f.result(timeout=15)) for f in helpers)
    +    wait_until(stalls.pids)
    +    (stalled,) = stalls.pids()
    +    wait_until(lambda: gone(stalled))
    +    if stalled in helpers:  # Both tasks can have gone to one worker.

    If both jobs ran on one worker and the other worker retired, the test passes without checking that a helper exited. Could each worker start a helper in its initializer, or could the two submitted tasks synchronize so they occupy different workers? Then the assertion about the retired worker’s helper can be unconditional.

    cjrh cjrh requested changes on Dec 01, 2026 14:11 UTC
    Changes Requested Reviewer

    I’d keep the single watcher started at construction when worker_stop_timeout is enabled. The idle timer now owns the worker it waits for, one failed signal no longer disables timeouts for other workers, and the deadline starts after the stop request. Most of the rewritten tests now exercise the public API through futures, finalizer markers, PIDs, and statistics.

    I reproduced four remaining issues at 134f2e0. The most important is that a worker already in its finalizer can lose its timeout entirely when clear_workers() overlaps shutdown(). The inline comments cover all four, suggested fixes, and two test changes.

    The full suite passed on Python 3.14 (269 tests). The focused idle and worker-stop suites passed with the GIL disabled (62 tests). The four findings came from separate local checks.

    harness=Codex,model=GPT-6,reasoning=unspecified

    cjrh cjrh approved these changes on Dec 01, 2026 21:40 UTC
    Approved Reviewer

    Thanks for working through these. I reran the four failure cases from my last review, and all four fixes held. In particular, a worker already stopping keeps its deadline when clear_workers() overlaps shutdown(). I’m happy to merge this.

    One optional follow-up: when worker_stop_timeout=None, every completed task still enters _may_retire(), takes the condition lock twice, and updates _retiring. Only the stop watcher reads that count. An early bypass in _may_retire() when the timeout is disabled would keep that bookkeeping off the default path.

    rstuart85 rstuart85 commented on Dec 01, 2026 23:02 UTC
    Author

    Added your optional follow-up in 9745b6a: with worker_stop_timeout=None the retirement count is skipped, so a completed task and clear_workers no longer take its lock. One new test, which times out on 11daffb.

    Reviewers
    Assignees
    rstuart85 rstuart85
    Labels
    risk: low confidence: 73.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 45.9% (MEDIUM) · Higher = larger blast radius
    45.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 73.9% · Lower = rushed or shallow review
    73.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 12% · Safe to merge
    12%
    Repository