Add worker_stop_timeout: kill a worker that takes too long to stop #458
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.
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.
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.
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.
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.
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
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
cjrh
rstuart85
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:
min_workers, task count, memory, andclear_workers.shutdownis 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, soshutdown(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.get_statistics()gainsworker_stop_timeouts, only with the option. With the default, each worker also keeps apsutil.Process.9745b6askips the count above when the option is off, so a completed task andclear_workersno 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 norclear_workerstakes the count's lock; processes the worker started, also when they cannot be listed; both halves ofshutdown; a retirement that overlapsshutdown, 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
9745b6athe 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 andclear_workersruns. It times out on11daffb. 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 on11daffb, 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.