From d46908afe02b8d6a569e3a4f013d8280a82352e8 Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Sun, 15 Nov 2026 00:17:37 -0500 Subject: [PATCH 1/6] Fix ThreadPool.shrink() accounting of pending shutdowns shrink() subtracted the shutdowns that earlier calls had queued from the amount it was asked for, before it removed the threads that had already exited. So a call made before an earlier call's threads were reaped was mostly ignored: four shrink(20) calls in a row retired 20 of 90 threads, and 40 when made a second apart. The idle property already leaves those threads out, so a caller that sizes the amount from it had them subtracted twice. The threads above the minimum were also counted with those already shutting down: shrink(40), then shrink(80), on 50 threads with a minimum of 10 retired all 50, and left 30 requests queued. The pending shutdowns also had to match the requests in the queue exactly, and could not: a put() interrupted while it waited for room in the queue left one with no request, reaping dropped one for each thread that had exited, whatever the reason, and two calls at once could ask the same threads. The pool now keeps the retirement requests that are due, under a lock. shrink() reserves up to the amount asked, among the threads above the minimum that earlier calls have not asked to retire. It does so inside the try block that takes back the requests it has not queued, so an interrupt anywhere leaves nothing due without a request, and never touches another call's. A request only wakes a worker: a worker that takes one retires if it is still due and the pool keeps its minimum without it, and otherwise goes on serving. So a request that an interrupted call took back, or one that outlived a thread that exited for another reason, changes nothing. idle reads the threads and the retirements due under the same lock. A worker counts the threads that still serve by their ready flag, since before Python 3.13 is_alive() can fail when two threads call it at once for a thread that is exiting. stop() is unchanged. Assisted-By: Anthropic Claude Opus 5.5 Assisted-By: OpenAI Codex Signed-off-by: Adam Harwell --- cheroot/test/test_server.py | 580 +++++++++++++++++++++- cheroot/workers/threadpool.py | 115 ++++- cheroot/workers/threadpool.pyi | 12 + docs/changelog-fragments.d/859.bugfix.rst | 8 + docs/conf.py | 1 + 5 files changed, 690 insertions(+), 26 deletions(-) create mode 100644 docs/changelog-fragments.d/859.bugfix.rst diff --git a/cheroot/test/test_server.py b/cheroot/test/test_server.py index 11c47231fa..8109662fac 100644 --- a/cheroot/test/test_server.py +++ b/cheroot/test/test_server.py @@ -1,5 +1,8 @@ """Tests for the HTTP server.""" +from __future__ import annotations + +import contextlib import gc import os import pathlib @@ -9,7 +12,9 @@ import sys import tempfile import threading +import time import types +import typing as _t import urllib.parse # noqa: WPS301 import uuid from http import HTTPStatus @@ -27,7 +32,7 @@ EPHEMERAL_PORT, SUCCESSFUL_SUBPROCESS_EXIT, ) -from ..workers.threadpool import ThreadPool +from ..workers.threadpool import ThreadPool, WorkerThread IS_SLOW_ENV = IS_MACOS or IS_WINDOWS @@ -46,6 +51,18 @@ ) +def _wait_until( + *, + compute_condition: _t.Callable[[], bool], + timeout: float = 10, +) -> bool: + """Wait until the condition is true or the timeout expires.""" + deadline = time.monotonic() + timeout + while not compute_condition() and time.monotonic() < deadline: + time.sleep(0.05) + return compute_condition() + + @pytest.fixture(params=('abstract', 'file')) def unix_sock_file(request): """Check that bound UNIX socket address is stored in server.""" @@ -84,6 +101,19 @@ def unix_file_sock(): os.unlink(tmp_sock_fname) +def _make_server( + server_class: type[HTTPServer] = HTTPServer, + *, + minthreads: int = 10, +) -> HTTPServer: + """Make a server on an ephemeral port, without starting it.""" + return server_class( + bind_addr=(ANY_INTERFACE_IPV4, EPHEMERAL_PORT), + gateway=Gateway, + minthreads=minthreads, + ) + + def test_prepare_makes_server_ready(): """Check that prepare() makes the server ready, and stop() clears it.""" httpserver = HTTPServer( @@ -584,6 +614,554 @@ def test_threadpool_multistart_validation(monkeypatch): tp.start() +def _prepared_pool( + request: pytest.FixtureRequest, + *, + minthreads: int, +) -> ThreadPool: + """Prepare a server with a set number of threads, and return its pool.""" + httpserver = _make_server(minthreads=minthreads) + httpserver.prepare() + request.addfinalizer(httpserver.stop) + return httpserver.requests + + +def _count_live_threads(pool: ThreadPool) -> int: + """Count the pool's threads that have not exited yet.""" + return sum(thread.is_alive() for thread in pool._threads) + + +def _wait_for_thread_count(pool: ThreadPool, count: int) -> bool: + """Wait for the pool to have the expected number of live workers.""" + return _wait_until( + compute_condition=lambda: _count_live_threads(pool) == count, + ) + + +def _wait_for_empty_queue(pool: ThreadPool) -> bool: + """Wait for the workers to take every request in the queue.""" + return _wait_until(compute_condition=lambda: pool.qsize == 0) + + +@pytest.fixture +def single_thread_pool(request: pytest.FixtureRequest) -> ThreadPool: + """Return the pool of a prepared server with a minimum of one thread.""" + return _prepared_pool(request, minthreads=1) + + +def test_threadpool_shrink_calls_are_additive( + single_thread_pool: ThreadPool, +) -> None: + """Test two close-together shrink() calls retire the total requested.""" + pool = single_thread_pool + pool.grow(20) + pool.shrink(10) + pool.shrink(10) + assert pool.idle == 1 + assert _wait_for_thread_count(pool, pool.min) + + +def test_threadpool_shrink_keeps_minimum( + request: pytest.FixtureRequest, +) -> None: + """Test that shrink() keeps the minimum number of threads.""" + pool = _prepared_pool(request, minthreads=10) + pool.grow(40) + pool.shrink(40) + pool.shrink(80) + assert pool.idle == 10 + assert _wait_for_thread_count(pool, 10) + assert pool.qsize == 0 + + +def _read_idle_while_retiring(pool: ThreadPool) -> list[int]: + """Return the idle counts that differ from 1 while threads retire.""" + wrong = [] + pool.grow(20) + pool.shrink(20) + deadline = time.monotonic() + 10 + while len(pool._serving()) > 1 and time.monotonic() < deadline: + idle = pool.idle + if idle != 1: + wrong.append(idle) + return wrong + + +def test_threadpool_idle_is_exact_while_threads_retire( + single_thread_pool: ThreadPool, +) -> None: + """A thread taking its shutdown never shows as idle and due at once.""" + pool = single_thread_pool + with contextlib.ExitStack() as cleanup: + cleanup.callback(sys.setswitchinterval, sys.getswitchinterval()) + # Switch threads often, as a PyPy run may + sys.setswitchinterval(1e-6) + wrong = [_read_idle_while_retiring(pool) for _ in range(10)] + assert not any(wrong) + + +def test_threadpool_workers_do_not_check_other_threads( + single_thread_pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A worker that takes a retirement request does not call is_alive().""" + pool = single_thread_pool + callers = [] + original_is_alive = WorkerThread.is_alive + + def _recorded_is_alive(thread: WorkerThread) -> bool: + if isinstance(threading.current_thread(), WorkerThread): + callers.append(threading.current_thread()) + return original_is_alive(thread) + + monkeypatch.setattr(WorkerThread, 'is_alive', _recorded_is_alive) + pool.grow(3) + pool.shrink(3) + # Once they have exited, the workers have handled their requests + assert _wait_for_thread_count(pool, pool.min) + assert not pool._retirements_due + assert not callers + + +class _LockInterruptedOnRelease: + """The pool's lock, interrupted once as it is released.""" + + def __init__(self, pool: ThreadPool) -> None: + self._lock = pool._lock + self._interrupted = False + + def __enter__(self) -> None: + self._lock.acquire() + + def __exit__(self, *_exc: object) -> None: + self._lock.release() + if not self._interrupted: + self._interrupted = True + raise KeyboardInterrupt + + +def test_threadpool_shrink_interrupted_after_its_reservation( + single_thread_pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A shrink() interrupted before it queues gives its shutdown back.""" + pool = single_thread_pool + pool.grow(3) + with monkeypatch.context() as patch: + # Right after it reserved the shutdowns + patch.setattr(pool, '_lock', _LockInterruptedOnRelease(pool)) + with pytest.raises(KeyboardInterrupt): + pool.shrink(5) + # No retirement is due, so every thread counts as idle + assert pool.idle == 4 + pool.shrink(5) + assert _wait_for_thread_count(pool, pool.min) + + +@pytest.mark.parametrize('queued_before_error', (0, 1)) +def test_threadpool_interrupted_shrink_releases_unused_reservations( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, + queued_before_error: int, +) -> None: + """An interrupted shrink keeps only successfully queued retirements.""" + queued: list[object] = [] + # Workers wait until the counts are checked + with _paused_workers(monkeypatch): + pool = _prepared_pool(request, minthreads=1) + pool.grow(2) + original_put = pool._queue.put + + def _interrupted_put(obj: object) -> None: + if len(queued) == queued_before_error: + # Such as a KeyboardInterrupt while waiting for room + raise RuntimeError('interrupted') + original_put(obj) + queued.append(obj) + + with monkeypatch.context() as patch: + patch.setattr(pool._queue, 'put', _interrupted_put) + with pytest.raises(RuntimeError, match='interrupted'): + pool.shrink(2) + assert len(pool._retirements_due) == queued_before_error + assert pool.idle == 3 - queued_before_error + + pool.shrink(3) + assert _wait_for_thread_count(pool, pool.min) + assert pool.qsize == 0 + + +def _join_thread(thread: threading.Thread) -> None: + """Join a started test thread and fail if it does not finish.""" + if thread.ident is None: + return + thread.join(10) + assert not thread.is_alive() + + +def _release_events(*events: threading.Event) -> None: + """Unblock test workers during cleanup, including assertion failures.""" + for event in events: + event.set() + + +def _run_overlapping_shrinks( + first: threading.Thread, + second: threading.Thread, + first_enqueue: threading.Event, + second_progress: threading.Event, + release_enqueue: threading.Event, +) -> None: + """Hold the first enqueue until the second call has made its decision.""" + with contextlib.ExitStack() as cleanup: + cleanup.callback(_join_thread, first) + cleanup.callback(_join_thread, second) + cleanup.callback(_release_events, release_enqueue) + first.start() + assert first_enqueue.wait(10) + second.start() + # The second call either tries to enqueue another request or returns. + assert second_progress.wait(10) + + +def test_threadpool_unrelated_exit_keeps_pending_shutdown( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An unrelated worker exit must not consume a queued retirement.""" + release_exit = threading.Event() + release_workers = threading.Event() + original_process = WorkerThread._process_connections_until_interrupted + failed_worker = None + + def _controlled_process(worker: WorkerThread) -> None: + assert release_exit.wait(10) + if worker is failed_worker: + return + assert release_workers.wait(10) + original_process(worker) + + with contextlib.ExitStack() as cleanup, monkeypatch.context() as patch: + cleanup.callback(_release_events, release_exit, release_workers) + patch.setattr( + WorkerThread, + '_process_connections_until_interrupted', + _controlled_process, + ) + pool = _prepared_pool(request, minthreads=2) + pool.grow(2) + failed_worker = pool._threads[0] + pool.shrink(1) + release_exit.set() + _join_thread(failed_worker) + + # Three workers remain, with one retirement already queued. + pool.shrink(1) + assert pool.qsize == 1 + + assert _wait_for_thread_count(pool, 2) + + +def _shrink_and_notify( + pool: ThreadPool, + finished: threading.Event, + errors: list[BaseException], +) -> None: + """Capture a shrink failure and signal that the caller has finished.""" + try: + pool.shrink(2) + except BaseException as error: + errors.append(error) + finally: + finished.set() + + +@pytest.mark.parametrize('queue_size', (0, 1)) +def test_threadpool_concurrent_shrink_keeps_minimum( + single_thread_pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, + queue_size: int, +) -> None: + """Concurrent calls must not spend the same retirement budget twice.""" + pool = single_thread_pool + pool.grow(2) + first_enqueue = threading.Event() + second_progress = threading.Event() + release_enqueue = threading.Event() + errors: list[BaseException] = [] + queued: list[object] = [] + original_put = pool._queue.put + + def _held_put(obj: object) -> None: + entered = ( + first_enqueue + if threading.current_thread() is first + else second_progress + ) + entered.set() + assert release_enqueue.wait(10) + original_put(obj) + queued.append(obj) + + first = threading.Thread( + target=_shrink_and_notify, + args=(pool, first_enqueue, errors), + ) + second = threading.Thread( + target=_shrink_and_notify, + args=(pool, second_progress, errors), + ) + with monkeypatch.context() as patch: + patch.setattr(pool._queue, 'maxsize', queue_size) + patch.setattr(pool._queue, 'put', _held_put) + _run_overlapping_shrinks( + first, + second, + first_enqueue, + second_progress, + release_enqueue, + ) + + assert not errors + assert len(queued) == 2 + + assert _wait_for_thread_count(pool, pool.min) + assert pool.qsize == 0 + + +@contextlib.contextmanager +def _paused_workers( + monkeypatch: pytest.MonkeyPatch, +) -> _t.Iterator[threading.Event]: + """Hold workers before they consume requests, and always release them.""" + release = threading.Event() + original_process = WorkerThread._process_connections_until_interrupted + + def _paused_process(worker: WorkerThread) -> None: + assert release.wait(10) + original_process(worker) + + with contextlib.ExitStack() as cleanup, monkeypatch.context() as patch: + cleanup.callback(release.set) + patch.setattr( + WorkerThread, + '_process_connections_until_interrupted', + _paused_process, + ) + yield release + + +@pytest.mark.parametrize('worker_claimed', (False, True)) +def test_threadpool_interrupt_after_enqueue_keeps_minimum( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, + *, + worker_claimed: bool, +) -> None: + """Retrying after an interrupted successful enqueue must keep the minimum.""" + with _paused_workers(monkeypatch) as release: + pool = _prepared_pool(request, minthreads=1) + pool.grow(1) + original_put = pool._queue.put + + def _put_then_interrupt(obj: object) -> None: + original_put(obj) + if worker_claimed: + release.set() + assert _wait_for_thread_count(pool, 1) + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(pool._queue, 'put', _put_then_interrupt) + with pytest.raises(KeyboardInterrupt): + pool.shrink(1) + pool.shrink(1) + + assert _wait_for_thread_count(pool, 1) + assert pool.qsize == 0 + + +def test_threadpool_reap_before_enqueue_returns_keeps_idle_count( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Reaping before the enqueue returns must not leave a phantom shutdown.""" + pool = _prepared_pool(request, minthreads=1) + pool.grow(2) + original_put = pool._queue.put + + def _put_then_reap(obj: object) -> None: + original_put(obj) + assert _wait_for_thread_count(pool, 2) + reaper = threading.Thread(target=pool.shrink, args=(0,)) + reaper.start() + _join_thread(reaper) + + with monkeypatch.context() as patch: + patch.setattr(pool._queue, 'put', _put_then_reap) + pool.shrink(1) + assert pool.idle == 2 + + pool.shrink(1) + assert _wait_for_thread_count(pool, 1) + + +def test_threadpool_unneeded_shrink_request_keeps_threads( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A retirement request that its call canceled must not end a thread.""" + # Workers wait until the interrupted call has canceled its request + with _paused_workers(monkeypatch): + pool = _prepared_pool(request, minthreads=1) + pool.grow(2) + original_put = pool._queue.put + + def _put_then_interrupt(obj: object) -> None: + original_put(obj) + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(pool._queue, 'put', _put_then_interrupt) + with pytest.raises(KeyboardInterrupt): + pool.shrink(2) + # It gave its shutdowns back, but its first request is queued + assert not pool._retirements_due + assert pool.qsize == 1 + assert _wait_for_empty_queue(pool) + assert _count_live_threads(pool) == 3 + assert pool.idle == 3 + + +def _interrupt_a_shrink_while_another_is_due( + pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Interrupt a call once another has reserved a shutdown.""" + original_put = pool._queue.put + second_queuing = threading.Event() + first_done = threading.Event() + second = threading.Thread(target=pool.shrink, args=(1,)) + + def _controlled_put(obj: object) -> None: + if threading.current_thread() is second: + second_queuing.set() + assert first_done.wait(10) + original_put(obj) + if threading.current_thread() is second: + return + # A worker takes the request and exits + assert _wait_for_thread_count(pool, 2) + second.start() + assert second_queuing.wait(10) + # Interrupted after its request got into the queue + raise KeyboardInterrupt + + with contextlib.ExitStack() as cleanup, monkeypatch.context() as patch: + cleanup.callback(_join_thread, second) + cleanup.callback(first_done.set) + patch.setattr(pool._queue, 'put', _controlled_put) + with pytest.raises(KeyboardInterrupt): + pool.shrink(amount=1) + + +def test_threadpool_interrupted_shrink_keeps_other_calls_shutdowns( + single_thread_pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An interrupted call gives back only shutdowns of its own requests.""" + pool = single_thread_pool + pool.grow(2) + _interrupt_a_shrink_while_another_is_due(pool, monkeypatch) + # One thread retired for each call + assert _wait_for_thread_count(pool, 1) + assert not pool._retirements_due + + +def test_threadpool_shrink_keeps_minimum_after_an_unrelated_exit( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A retirement due when another thread exits must keep the minimum.""" + release_exit = threading.Event() + release_workers = threading.Event() + original_process = WorkerThread._process_connections_until_interrupted + failed_worker = None + + def _controlled_process(worker: WorkerThread) -> None: + assert release_exit.wait(10) + if worker is failed_worker: + return + assert release_workers.wait(10) + original_process(worker) + + with contextlib.ExitStack() as cleanup, monkeypatch.context() as patch: + cleanup.callback(_release_events, release_exit, release_workers) + patch.setattr( + WorkerThread, + '_process_connections_until_interrupted', + _controlled_process, + ) + pool = _prepared_pool(request, minthreads=2) + pool.grow(1) + failed_worker = pool._threads[0] + # Retire every idle thread above the minimum: one + pool.shrink(pool.idle) + release_exit.set() + _join_thread(failed_worker) + release_workers.set() + assert _wait_for_empty_queue(pool) + # The request found the minimum left, and dropped its shutdown + assert _wait_until(compute_condition=lambda: not pool._retirements_due) + assert _count_live_threads(pool) == 2 + assert pool.idle == 2 + + +@contextlib.contextmanager +def _hold_retiring_workers( + monkeypatch: pytest.MonkeyPatch, +) -> _t.Iterator[queue.Queue[WorkerThread]]: + """Hold workers after their processing loop has consumed a retirement.""" + release = threading.Event() + at_exit: queue.Queue[WorkerThread] = queue.Queue() + original_process = WorkerThread._process_connections_until_interrupted + + def _held_exit(worker: WorkerThread) -> None: + original_process(worker) + at_exit.put(worker) + assert release.wait(10) + + with contextlib.ExitStack() as cleanup, monkeypatch.context() as patch: + cleanup.callback(release.set) + patch.setattr( + WorkerThread, + '_process_connections_until_interrupted', + _held_exit, + ) + yield at_exit + + +def test_threadpool_shrink_skips_threads_shutting_down( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A thread that is shutting down is neither idle nor asked again.""" + with _hold_retiring_workers(monkeypatch) as at_exit: + pool = _prepared_pool(request, minthreads=1) + pool.grow(2) + pool.shrink(1) + assert _wait_until(compute_condition=lambda: at_exit.qsize() == 1) + # The retiring thread is still alive, but it no longer serves + assert _count_live_threads(pool) == 3 + assert pool.idle == 2 + pool.shrink(5) + assert _wait_until(compute_condition=lambda: at_exit.qsize() == 2) + assert _wait_for_empty_queue(pool) + assert not pool._retirements_due + assert pool.idle == 1 + assert _wait_for_thread_count(pool, 1) + + def test_overload_results_in_suitable_http_error(request): """A server that can't keep up with requests returns a 503 HTTP error.""" localhost = '127.0.0.1' diff --git a/cheroot/workers/threadpool.py b/cheroot/workers/threadpool.py index c827a567aa..1aeaebd76b 100644 --- a/cheroot/workers/threadpool.py +++ b/cheroot/workers/threadpool.py @@ -5,8 +5,6 @@ joinable """ -import collections -import contextlib import logging import queue import socket @@ -35,6 +33,10 @@ def __radd__(self, other): _SHUTDOWNREQUEST = object() +class _RetirementRequest: + """A ticket that shrink() queues, for any one thread to take and retire.""" + + class WorkerThread(threading.Thread): """Thread which continuously polls a Queue for Connection objects. @@ -55,6 +57,9 @@ class WorkerThread(threading.Thread): """A simple flag for the calling server to know when this thread has begun polling the Queue.""" + _retiring = False + """Whether this thread took a retirement request, and is exiting.""" + def __init__(self, server): """Initialize WorkerThread instance. @@ -152,6 +157,15 @@ def run(self): finally: self.ready = False + def _get_request(self): + """Get a connection, or a shutdown request if this thread exits.""" + while True: + conn = self.server.requests.get() + if not isinstance(conn, _RetirementRequest): + return conn + if self.server.requests._decide_retirement(self, conn): + return _SHUTDOWNREQUEST + def _process_connections_until_interrupted(self): """Process incoming HTTP connections in an infinite loop. @@ -162,7 +176,7 @@ def _process_connections_until_interrupted(self): server instance """ while True: - conn = self.server.requests.get() + conn = self._get_request() if conn is _SHUTDOWNREQUEST: return @@ -287,7 +301,10 @@ def __init__( # pylint: disable=too-many-positional-arguments self._queue = queue.Queue(maxsize=accepted_queue_size) self._queue_put_timeout = accepted_queue_timeout self.get = self._queue.get - self._pending_shutdowns = collections.deque() + # Guards _retirements_due and _threads against concurrent access + # from `idle`, `shrink()`, and a worker claiming its own retirement. + self._lock = threading.Lock() + self._retirements_due = set() def start(self): """Start the pool of threads. @@ -301,8 +318,11 @@ def start(self): @property def idle(self): """Number of worker threads which are idle. Read-only.""" - idles = len([t for t in self._threads if t.conn is None]) - return max(idles - len(self._pending_shutdowns), 0) + # The threads and the retirements due change together as a worker + # takes a retirement request + with self._lock: + idles = len([t for t in self._serving() if t.conn is None]) + return max(idles - len(self._retirements_due), 0) def put(self, obj): """Put request into queue. @@ -317,8 +337,13 @@ def _clear_dead_threads(self): # Remove any dead threads from our list for t in [t for t in self._threads if not t.is_alive()]: self._threads.remove(t) - with contextlib.suppress(IndexError): - self._pending_shutdowns.popleft() + + def _serving(self): + """Return the threads that run and that are not shutting down.""" + # A thread clears `ready` as it exits. Workers call this, and before + # Python 3.13, is_alive() can fail when two threads call it, or + # join(), at once for a thread that is exiting. + return [t for t in self._threads if t.ready and not t._retiring] def grow(self, amount): """Spawn new worker threads (not above self.max).""" @@ -338,26 +363,66 @@ def _spawn_worker(self): return worker def shrink(self, amount): - """Kill off worker threads (not below self.min).""" - # Grow/shrink the pool if necessary. - # Remove any dead threads from our list - amount -= len(self._pending_shutdowns) - self._clear_dead_threads() - if amount <= 0: - return + """Kill off worker threads (not below self.min). - # calculate the number of threads above the minimum - n_extra = max(len(self._threads) - self.min, 0) + Threads that earlier calls asked to retire count as gone. + """ + retirement_requests = [] + n_queued = 0 + try: + with self._lock: + # Remove any dead threads from our list + self._clear_dead_threads() + + # calculate the number of threads it's safe to remove, + # taking into account the minimum and any retirement + # requests still pending from previous calls + n_removable = max( + len(self._serving()) + - len(self._retirements_due) + - self.min, + 0, + ) - # don't remove more than amount - n_to_remove = min(amount, n_extra) + # don't remove more than amount + retirement_requests = [ + _RetirementRequest() + for _ in range(min(amount, n_removable)) + ] + # Add these retirement requests to _retirements_due before + # they're queued, so a concurrent shrink() call knows about + # them and budgets for them accordingly. + self._retirements_due.update(retirement_requests) + + # put a request on the queue for each retirement + for request in retirement_requests: + self._queue.put(request) + n_queued += 1 + finally: + # If shrink() was interrupted, remove the ones we added to + # _retirements_due that never made it onto the queue, or that got + # in as put() was interrupted: a thread that takes one skips it. + with self._lock: + self._retirements_due.difference_update( + retirement_requests[n_queued:], + ) - # put shutdown requests on the queue equal to the number of threads - # to remove. As each request is processed by a worker, that worker - # will terminate and be culled from the list. - for _ in range(n_to_remove): - self._pending_shutdowns.append(None) - self._queue.put(_SHUTDOWNREQUEST) + def _decide_retirement(self, worker, request): + """Decide whether a worker that took a retirement request retires. + + The request stops being due whatever the answer, and the worker is + marked as retiring when it is yes. + """ + with self._lock: + # Its shrink() call may have taken it back + if request not in self._retirements_due: + return False + self._retirements_due.remove(request) + # Another thread may have exited since shrink() was called + if len(self._serving()) <= self.min: + return False + worker._retiring = True + return True def stop(self, timeout=5): """Terminate all worker threads. diff --git a/cheroot/workers/threadpool.pyi b/cheroot/workers/threadpool.pyi index e9c837dd55..801a74d6b8 100644 --- a/cheroot/workers/threadpool.pyi +++ b/cheroot/workers/threadpool.pyi @@ -9,10 +9,13 @@ class TrueyZero: trueyzero: TrueyZero +class _RetirementRequest: ... + class WorkerThread(threading.Thread): conn: _t.Any server: _t.Any ready: bool + _retiring: bool requests_seen: int bytes_read: int bytes_written: int @@ -21,12 +24,15 @@ class WorkerThread(threading.Thread): stats: _t.Any def __init__(self, server): ... def run(self) -> None: ... + def _get_request(self) -> _t.Any: ... class ThreadPool: server: _t.Any min: _t.Any max: _t.Any get: _t.Any + _lock: threading.Lock + _retirements_due: set[_RetirementRequest] def __init__( self, server, @@ -41,6 +47,12 @@ class ThreadPool: def put(self, obj) -> None: ... def grow(self, amount) -> None: ... def shrink(self, amount) -> None: ... + def _serving(self) -> list[WorkerThread]: ... + def _decide_retirement( + self, + worker: WorkerThread, + request: _RetirementRequest, + ) -> bool: ... def stop(self, timeout: int = ...) -> None: ... @property def qsize(self) -> int: ... diff --git a/docs/changelog-fragments.d/859.bugfix.rst b/docs/changelog-fragments.d/859.bugfix.rst new file mode 100644 index 0000000000..7d7b1ced82 --- /dev/null +++ b/docs/changelog-fragments.d/859.bugfix.rst @@ -0,0 +1,8 @@ +Fixed :py:meth:`ThreadPool.shrink() ` +accounting for pending shutdowns. Repeated calls now request up to ``amount`` +additional thread retirements while preserving the pool's minimum size, +including when calls overlap, a call is interrupted, or a thread exits for +another reason. Previously, pending shutdowns could suppress a later call, or +let the pool drop below its minimum. + +-- by :user:`rm-you` diff --git a/docs/conf.py b/docs/conf.py index 89292604d8..506cd68708 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -96,6 +96,7 @@ 'coverage': ('https://coverage.readthedocs.io/en/latest/', None), 'towncrier': ('https://towncrier.readthedocs.io/en/latest/', None), 'sphinx': ('https://www.sphinx-doc.org', None), + 'pytest': ('https://docs.pytest.org/en/stable', None), } linkcheck_ignore = [ From eb62843a33c9cb4e100ae91f3f94ba56ce22ee77 Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Sun, 15 Nov 2026 07:30:04 -0500 Subject: [PATCH 2/6] Reword retirement comments, as in review This takes the reviewer's wording for the docstrings and comments of the retirement checks and the idle test, and the test's new name. The _get_request() docstring keeps "shutdown request", since that is what the method returns, for a retirement too. Assisted-By: Anthropic Claude Opus 5.5 Signed-off-by: Adam Harwell --- cheroot/test/test_server.py | 4 ++-- cheroot/workers/threadpool.py | 16 +++++++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/cheroot/test/test_server.py b/cheroot/test/test_server.py index 8109662fac..e207720162 100644 --- a/cheroot/test/test_server.py +++ b/cheroot/test/test_server.py @@ -687,10 +687,10 @@ def _read_idle_while_retiring(pool: ThreadPool) -> list[int]: return wrong -def test_threadpool_idle_is_exact_while_threads_retire( +def test_threadpool_idle_is_accurate_while_threads_retire( single_thread_pool: ThreadPool, ) -> None: - """A thread taking its shutdown never shows as idle and due at once.""" + """pool.idle is accurate throughout concurrent retirements.""" pool = single_thread_pool with contextlib.ExitStack() as cleanup: cleanup.callback(sys.setswitchinterval, sys.getswitchinterval()) diff --git a/cheroot/workers/threadpool.py b/cheroot/workers/threadpool.py index 1aeaebd76b..514b5a0e67 100644 --- a/cheroot/workers/threadpool.py +++ b/cheroot/workers/threadpool.py @@ -158,7 +158,7 @@ def run(self): self.ready = False def _get_request(self): - """Get a connection, or a shutdown request if this thread exits.""" + """Get a connection, or a shutdown request for this thread to exit.""" while True: conn = self.server.requests.get() if not isinstance(conn, _RetirementRequest): @@ -339,7 +339,7 @@ def _clear_dead_threads(self): self._threads.remove(t) def _serving(self): - """Return the threads that run and that are not shutting down.""" + """Return the threads that run and that are not retiring.""" # A thread clears `ready` as it exits. Workers call this, and before # Python 3.13, is_alive() can fail when two threads call it, or # join(), at once for a thread that is exiting. @@ -410,15 +410,21 @@ def shrink(self, amount): def _decide_retirement(self, worker, request): """Decide whether a worker that took a retirement request retires. - The request stops being due whatever the answer, and the worker is + The retirement stops being due whatever the answer, and the worker is marked as retiring when it is yes. """ with self._lock: - # Its shrink() call may have taken it back + # If interrupted, the shrink() call that placed this request + # on the queue may have withdrawn it from _retirements_due. + # If not in _retirements_due, the request should be ignored. if request not in self._retirements_due: return False self._retirements_due.remove(request) - # Another thread may have exited since shrink() was called + # Serving threads may have exited since shrink() was called, + # for reasons unrelated to any retirement tickets (e.g. + # fatal exceptions). Recheck against self.min here, before + # committing this worker to retire, to ensure the pool never + # drops below it. if len(self._serving()) <= self.min: return False worker._retiring = True From 6654d3fbffe66b308733fc8d0f1feb4d1ba4f4e5 Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Sun, 15 Nov 2026 00:17:37 -0500 Subject: [PATCH 3/6] Make leftover shutdown requests harmless to a restarted pool stop() queued a shutdown request for every thread in its list, and each request ended whichever thread took it. A thread already shutting down, such as one that shrink() had retired, takes none, and neither does a worker that stops its own pool on an interrupt, such as a KeyboardInterrupt from the application. Their requests stayed in the queue, as did those that shrink() queued while the pool stopped. The next start() lost its new threads to them and waited for them forever. A dead thread still in the list also got a request, which could wait for room in a bounded queue forever, and an interrupted stop() could not be repeated, as it had emptied the list. stop() now ends the pool's run. The retirements that shrink() asked for are no longer due, and their requests do nothing in a later run. A thread shuts down on a stop request only if its run has ended, so a request that a stop() left in the queue does nothing to the threads of a later run. stop() queues one request for each live thread that has not taken one yet, even when the queue is full of connections, so it always reaches the timeout that closes stuck connections. The threads that still run when it returns stay listed, so that a later stop() ends them, and start() refuses to start the pool again until they have exited. grow() and start() take the pool's lock, so stop() also ends the threads that a grow() call was starting. grow() refuses while a thread of an ended run has not taken its stop request, which a new thread could otherwise take and drop. Assisted-By: Anthropic Claude Opus 5.5 Assisted-By: OpenAI Codex Signed-off-by: Adam Harwell --- cheroot/test/test_server.py | 574 ++++++++++++++++++++++ cheroot/workers/threadpool.py | 111 ++++- cheroot/workers/threadpool.pyi | 8 + docs/changelog-fragments.d/882.bugfix.rst | 12 + 4 files changed, 681 insertions(+), 24 deletions(-) create mode 100644 docs/changelog-fragments.d/882.bugfix.rst diff --git a/cheroot/test/test_server.py b/cheroot/test/test_server.py index e207720162..53d74eb9db 100644 --- a/cheroot/test/test_server.py +++ b/cheroot/test/test_server.py @@ -17,6 +17,7 @@ import typing as _t import urllib.parse # noqa: WPS301 import uuid +from concurrent.futures import ThreadPoolExecutor from http import HTTPStatus import pytest @@ -24,6 +25,7 @@ import requests import requests_unixsocket +from .. import wsgi from .._compat import IS_LINUX, IS_MACOS, IS_WINDOWS, SYS_PLATFORM, bton, ntob from ..server import IS_UID_GID_RESOLVABLE, Gateway, HTTPServer from ..testing import ( @@ -33,6 +35,7 @@ SUCCESSFUL_SUBPROCESS_EXIT, ) from ..workers.threadpool import ThreadPool, WorkerThread +from . import webtest IS_SLOW_ENV = IS_MACOS or IS_WINDOWS @@ -508,6 +511,15 @@ def many_open_sockets(request, resource_limit): test_socket.close() +def _make_wsgi_server(app: _t.Callable[..., object]) -> wsgi.Server: + """Make a WSGI server with one worker on an ephemeral port.""" + return wsgi.Server( + (ANY_INTERFACE_IPV4, EPHEMERAL_PORT), + app, + numthreads=1, + ) + + @pytest.mark.parametrize( ('minthreads', 'maxthreads', 'inited_maxthreads'), ( @@ -1162,6 +1174,568 @@ def test_threadpool_shrink_skips_threads_shutting_down( assert _wait_for_thread_count(pool, 1) +@pytest.mark.parametrize('shrinking', ('done', 'in progress')) +def test_threadpool_restarts_after_stop( + request: pytest.FixtureRequest, + shrinking: str, +) -> None: + """Test that a pool stopped after or during shrinking restarts.""" + pool = _prepared_pool(request, minthreads=2) + pool.grow(5) + pool.shrink(5) + if shrinking == 'done': + assert _wait_until( + compute_condition=lambda: _count_live_threads(pool) == 2, + ) + pool.stop() + # A leftover request would retire a restarted thread, and a leftover + # pending shutdown would hide the restarted threads from idle + assert not pool._retirements_due + pool.start() + assert pool.idle == 2 + + +def test_threadpool_stop_ends_threads_whatever_is_pending( + request: pytest.FixtureRequest, +) -> None: + """Test that stop() ends every thread even if a request went missing.""" + pool = _prepared_pool(request, minthreads=2) + # A retirement due whose request never reached the queue + pool._retirements_due.add(object()) + # Stop in a thread, so that a thread left waiting for a request fails + # the test instead of hanging the run + stopper = threading.Thread(target=pool.stop, daemon=True) + stopper.start() + stopper.join(10) + assert not stopper.is_alive() + assert pool.qsize == 0 + + +def test_threadpool_stopped_by_its_own_worker() -> None: + """Test that a worker that stops its own pool still exits.""" + + def app( + _environ: dict[str, object], + start_response: _t.Callable[..., object], + ) -> list[bytes]: + server.requests.stop() + start_response('200 OK', [('Content-Length', '2')]) + return [b'ok'] + + server = _make_wsgi_server(app) + with server._run_in_thread(): + workers = list(server.requests._threads) + host = webtest.interface(ANY_INTERFACE_IPV4) + response = requests.get( + f'http://{host}:{server.bind_addr[1]}/', + headers={'Connection': 'close'}, + timeout=10, + ) + assert response.status_code == HTTPStatus.OK + assert _wait_until( + compute_condition=lambda: ( + not any(worker.is_alive() for worker in workers) + ), + ) + assert server.requests.qsize == 0 + + +def test_threadpool_stopped_on_interrupt_by_its_own_worker() -> None: + """Test that a worker that interrupts its server leaves no request.""" + + def app( + _environ: dict[str, object], + _start_response: _t.Callable[..., object], + ) -> list[bytes]: + raise KeyboardInterrupt('simulated test handler keyboard interrupt') + + server = _make_wsgi_server(app) + with server._run_in_thread() as serve_thread: + host = webtest.interface(ANY_INTERFACE_IPV4) + with pytest.raises(requests.ConnectionError): + requests.get( + f'http://{host}:{server.bind_addr[1]}/', + headers={'Connection': 'close'}, + timeout=10, + ) + serve_thread.join(10) + assert not serve_thread.is_alive() + # The worker exits without taking a request + _assert_restart_ignores_leftovers(server.requests) + + +def test_threadpool_interrupted_stop_lets_running_threads_exit( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Test that a thread still running after an interrupted stop() exits.""" + release = threading.Event() + + def app( + _environ: dict[str, object], + start_response: _t.Callable[..., object], + ) -> list[bytes]: + release.wait(10) + start_response('200 OK', [('Content-Length', '2')]) + return [b'ok'] + + server = _make_wsgi_server(app) + with server._run_in_thread(): + worker = server.requests._threads[0] + host = webtest.interface(ANY_INTERFACE_IPV4) + with ThreadPoolExecutor(max_workers=1) as client: + response = client.submit( + requests.get, + f'http://{host}:{server.bind_addr[1]}/', + headers={'Connection': 'close'}, + timeout=10, + ) + assert _wait_until( + compute_condition=lambda: worker.conn is not None, + ) + + def _interrupted_join(*_args: object) -> None: + # Such as a second Ctrl-C while stop() waits for the thread + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(worker, 'join', _interrupted_join) + server.requests.stop() + release.set() + assert response.result().status_code == HTTPStatus.OK + assert _wait_until(compute_condition=lambda: not worker.is_alive()) + + +def _assert_empty_pool_queue(pool: ThreadPool) -> None: + """Check that no connection or retirement request remains queued.""" + assert pool.qsize == 0 + + +def _assert_restart_ignores_leftovers(pool: ThreadPool) -> None: + """Check that a request left by a stop does not end a restarted thread.""" + pool.start() + threads = list(pool._threads) + assert _wait_for_empty_queue(pool) + for thread in threads: + # A thread that took a leftover request as its own exits at once + thread.join(0.5) + assert thread.is_alive() + assert pool.idle == pool.min + pool.stop() + + +def test_threadpool_stop_drops_requests_already_consumed( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An interrupted join must not retain requests for retiring workers.""" + with contextlib.ExitStack() as cleanup: + with _hold_retiring_workers(monkeypatch) as at_exit: + pool = _prepared_pool(request, minthreads=1) + pool.grow(1) + for worker in pool._threads: + cleanup.callback(_join_thread, worker) + pool.shrink(2) + assert _wait_until(compute_condition=lambda: at_exit.qsize() == 1) + + def _interrupted_join(*_args: object) -> None: + assert _wait_until( + compute_condition=lambda: at_exit.qsize() == 2, + ) + raise KeyboardInterrupt + + with monkeypatch.context() as joins: + for worker in pool._threads: + joins.setattr(worker, 'join', _interrupted_join) + pool.stop() + _assert_empty_pool_queue(pool) + with pytest.raises(RuntimeError, match='can only be started once'): + pool.start() + + +def _stop_during_shrink_enqueue( + pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Stop the pool while a shrink caller has yet to insert its request.""" + entered = threading.Event() + release = threading.Event() + original_put = pool._queue.put + + def _held_put(obj: object) -> None: + if threading.current_thread() is shrinker: + entered.set() + assert release.wait(10) + original_put(obj) + + shrinker = threading.Thread(target=pool.shrink, args=(1,)) + with contextlib.ExitStack() as cleanup, monkeypatch.context() as patch: + cleanup.callback(_join_thread, shrinker) + cleanup.callback(release.set) + patch.setattr(pool._queue, 'put', _held_put) + shrinker.start() + assert entered.wait(10) + pool.stop() + + +def test_threadpool_shrink_interrupted_after_a_stop( + single_thread_pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A shrink() interrupted after a stop() leaves the next run's count.""" + pool = single_thread_pool + pool.grow(1) + release = threading.Event() + + def _held_interrupted_put(_obj: object) -> None: + assert release.wait(10) + raise KeyboardInterrupt + + def _shrink() -> None: + with contextlib.suppress(KeyboardInterrupt): + pool.shrink(amount=1) + + shrinker = threading.Thread(target=_shrink) + with contextlib.ExitStack() as cleanup, monkeypatch.context() as patch: + cleanup.callback(_join_thread, shrinker) + cleanup.callback(release.set) + patch.setattr(pool._queue, 'put', _held_interrupted_put) + shrinker.start() + # The call has reserved its shutdown + assert _wait_until( + compute_condition=lambda: len(pool._retirements_due) == 1, + ) + pool.stop() + pool.start() + # stop() forgot the retirement, so the interrupted call gives none back + assert not pool._retirements_due + assert pool.idle == pool.min + + +def test_threadpool_restarts_after_late_shrink_enqueue( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A retirement request arriving after stop must not retire a new worker.""" + + def app( + _environ: dict[str, object], + start_response: _t.Callable[..., object], + ) -> list[bytes]: + start_response('200 OK', [('Content-Length', '2')]) + return [b'ok'] + + server = _make_wsgi_server(app) + with server._run_in_thread(): + pool = server.requests + pool.grow(1) + _stop_during_shrink_enqueue(pool, monkeypatch) + # Hold new workers until start() has observed their ready flag. + # Otherwise the old bug hangs inside grow() before we can assert it. + # With a thread above the minimum, only a shutdown still due would + # retire one. + with _paused_workers(monkeypatch): + pool.start() + pool.grow(1) + + host = webtest.interface(ANY_INTERFACE_IPV4) + response = requests.get( + f'http://{host}:{server.bind_addr[1]}/', + headers={'Connection': 'close'}, + timeout=10, + ) + assert response.status_code == HTTPStatus.OK + assert response.content == b'ok' + assert _wait_until(compute_condition=lambda: pool.idle == 2) + _assert_empty_pool_queue(pool) + assert _count_live_threads(pool) == 2 + + +@contextlib.contextmanager +def _bounded_pool_put( + pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> _t.Iterator[None]: + """Bound the old enqueue deadlock so regressions fail without hanging.""" + original_put = pool._queue.put + + def _bounded_put( + obj: object, + *, + block: bool = True, + timeout: float | None = None, + ) -> None: + # Bound the old deadlock so a regression fails rather than hanging. + original_put(obj, block=block, timeout=timeout or 1) + + with monkeypatch.context() as patch: + patch.setattr(pool._queue, 'put', _bounded_put) + yield + + +def test_threadpool_stop_with_a_bounded_queue( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Stop must finish even when dead workers outnumber queue slots.""" + server = _make_server(minthreads=1) + server.requests = ThreadPool( + server, + min=1, + accepted_queue_size=1, + ) + pool = server.requests + server.prepare() + request.addfinalizer(server.stop) + pool.grow(3) + pool.shrink(3) + assert _wait_for_thread_count(pool, 1) + workers = list(pool._threads) + with _bounded_pool_put(pool, monkeypatch): + pool.stop(timeout=0.1) + assert not any(worker.is_alive() for worker in workers) + _assert_empty_pool_queue(pool) + + +def test_threadpool_stop_preserves_queued_connections( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Stop queues no request for a thread that does not run.""" + server = _make_server(minthreads=1) + pool = ThreadPool(server, min=1, accepted_queue_size=2) + first, second = object(), object() + pool.put(first) + pool.put(second) + with pytest.raises(queue.Full): + pool._queue.put_nowait(object()) + # A thread that never ran would leave a request behind a full queue + pool._threads.append(WorkerThread(server)) + with _bounded_pool_put(pool, monkeypatch): + pool.stop() + assert pool.get(block=False) is first + assert pool.get(block=False) is second + _assert_empty_pool_queue(pool) + + +def _interrupt_after( + put: _t.Callable[[object], None], +) -> _t.Callable[[object], None]: + """Wrap a put() so that an interrupt follows the request it queues.""" + + def _put_then_interrupt(obj: object) -> None: + put(obj) + raise KeyboardInterrupt + + return _put_then_interrupt + + +def test_threadpool_stop_retries_an_interrupted_enqueue( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A second stop can complete an interrupted batch of stop requests.""" + with _paused_workers(monkeypatch) as release: + pool = _prepared_pool(request, minthreads=2) + workers = list(pool._threads) + queue_put = pool._queue.put_shutdown + queued: list[object] = [] + + def _put_then_release(obj: object) -> None: + queue_put(obj) + queued.append(obj) + # Both workers still need a request, so the first one is left + if len(queued) == len(workers): + release.set() + + with monkeypatch.context() as patch: + patch.setattr( + pool._queue, + 'put_shutdown', + _interrupt_after(queue_put), + ) + with pytest.raises(KeyboardInterrupt): + pool.stop() + patch.setattr(pool._queue, 'put_shutdown', _put_then_release) + pool.stop() + assert not any(worker.is_alive() for worker in workers) + assert pool.qsize == 1 + _assert_restart_ignores_leftovers(pool) + + +class _HeldConnection: + """A connection that its worker handles until it is closed.""" + + def __init__(self) -> None: + self.closed = threading.Event() + self.rfile = types.SimpleNamespace(closed=False) + self.socket = types.SimpleNamespace(shutdown=self._shutdown) + + def communicate(self) -> bool: + """Handle the connection until it is closed.""" + self.closed.wait(30) + return False + + def close(self) -> None: + """Close nothing: the worker closes the connection it handled.""" + + def _shutdown(self, *_args: object) -> None: + self.closed.set() + + +def _pool_with_one_slot( + request: pytest.FixtureRequest, + *, + minthreads: int, +) -> ThreadPool: + """Start a pool whose queue holds one item.""" + pool = ThreadPool(_make_server(), min=minthreads, accepted_queue_size=1) + pool.server.requests = pool + pool.start() + request.addfinalizer(pool.stop) + return pool + + +def test_threadpool_stop_with_a_full_queue_reaches_force_close( + request: pytest.FixtureRequest, +) -> None: + """A full queue must not keep stop() from closing a stuck connection.""" + pool = _pool_with_one_slot(request, minthreads=1) + worker = pool._threads[0] + stuck = _HeldConnection() + pool.put(stuck) + assert _wait_until(compute_condition=lambda: worker.conn is stuck) + # Another connection fills the queue + waiting = _HeldConnection() + waiting.closed.set() + pool.put(waiting) + stopper = threading.Thread(target=pool.stop, args=(0,), daemon=True) + with contextlib.ExitStack() as cleanup: + cleanup.callback(stuck.closed.set) + stopper.start() + stopper.join(5) + # Checked while the connection is still stuck + assert not stopper.is_alive() + assert not worker.is_alive() + + +def test_threadpool_overlapping_stops_end_every_thread( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Two stop() calls at once, each asking every thread, both finish.""" + pool = _pool_with_one_slot(request, minthreads=2) + workers = list(pool._threads) + put_shutdown = pool._queue.put_shutdown + together = threading.Barrier(2) + + def _put_together(obj: object) -> None: + # Each call has counted every thread before either queues + with contextlib.suppress(threading.BrokenBarrierError): + together.wait(timeout=5) + put_shutdown(obj) + + monkeypatch.setattr(pool._queue, 'put_shutdown', _put_together) + stoppers = [threading.Thread(target=pool.stop, daemon=True) for _ in '12'] + for stopper in stoppers: + stopper.start() + for stopper in stoppers: + stopper.join(10) + assert not any(stopper.is_alive() for stopper in stoppers) + assert not any(worker.is_alive() for worker in workers) + + +def test_threadpool_grow_while_stopping_is_refused( + single_thread_pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A thread grown during stop() could take a busy thread's request.""" + pool = single_thread_pool + worker = pool._threads[0] + busy = _HeldConnection() + pool.put(busy) + assert _wait_until(compute_condition=lambda: worker.conn is busy) + joining = threading.Event() + release = threading.Event() + original_join = worker.join + + def _held_join(timeout: float | None = None) -> None: + joining.set() + assert release.wait(10) + original_join(timeout) + + monkeypatch.setattr(worker, 'join', _held_join) + stopper = threading.Thread(target=pool.stop, daemon=True) + with contextlib.ExitStack() as cleanup: + cleanup.callback(_join_thread, stopper) + cleanup.callback(_release_events, busy.closed, release) + stopper.start() + # stop() has queued the busy thread's request + assert joining.wait(10) + with pytest.raises(RuntimeError, match='while it stops'): + pool.grow(1) + assert not worker.is_alive() + + +class _ObservedLock: + """Report a caller that has to wait for the pool's lock.""" + + def __init__(self, pool: ThreadPool, waiting: threading.Event) -> None: + self._lock = pool._lock + self._waiting = waiting + + def __enter__(self) -> None: + if not self._lock.acquire(blocking=False): + self._waiting.set() + self._lock.acquire() + + def __exit__(self, *_exc: object) -> None: + self._lock.release() + + +def _stop_during_growth( + pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Overlap growth and stop without using timing to order the calls.""" + entered = threading.Event() + release = threading.Event() + stop_progress = threading.Event() + original_spawn = pool._spawn_worker + + def _held_spawn() -> WorkerThread: + entered.set() + assert release.wait(10) + return original_spawn() + + with ThreadPoolExecutor(max_workers=2) as callers: + with contextlib.ExitStack() as cleanup, monkeypatch.context() as patch: + cleanup.callback(release.set) + patch.setattr(pool, '_spawn_worker', _held_spawn) + patch.setattr( + pool, + '_lock', + _ObservedLock(pool, stop_progress), + ) + growing = callers.submit(pool.grow, 1) + assert entered.wait(10) + stopping = callers.submit(pool.stop) + stopping.add_done_callback(lambda _future: stop_progress.set()) + assert stop_progress.wait(10) + release.set() + # Propagate their failures + growing.result(timeout=10) + stopping.result(timeout=10) + + +def test_threadpool_stop_includes_growing_workers( + single_thread_pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A stop overlapping growth must leave no worker behind.""" + pool = single_thread_pool + _stop_during_growth(pool, monkeypatch) + assert not _count_live_threads(pool) + pool.stop() + + def test_overload_results_in_suitable_http_error(request): """A server that can't keep up with requests returns a 503 HTTP error.""" localhost = '127.0.0.1' diff --git a/cheroot/workers/threadpool.py b/cheroot/workers/threadpool.py index 514b5a0e67..aff3608e1a 100644 --- a/cheroot/workers/threadpool.py +++ b/cheroot/workers/threadpool.py @@ -37,6 +37,19 @@ class _RetirementRequest: """A ticket that shrink() queues, for any one thread to take and retire.""" +class _RequestQueue(queue.Queue): + """A queue of connections, and of requests for workers to shut down.""" + + def put_shutdown(self, request): + """Queue a shutdown request, even when the queue has no room.""" + # stop() then always reaches its timeout, which closes the + # connection that a worker may be stuck on + with self.not_empty: + self._put(request) + self.unfinished_tasks += 1 + self.not_empty.notify() + + class WorkerThread(threading.Thread): """Thread which continuously polls a Queue for Connection objects. @@ -58,7 +71,10 @@ class WorkerThread(threading.Thread): has begun polling the Queue.""" _retiring = False - """Whether this thread took a retirement request, and is exiting.""" + """Whether this thread took a retirement or a stop request, and exits.""" + + _run = None + """The run of the pool that started this thread, if one did.""" def __init__(self, server): """Initialize WorkerThread instance. @@ -161,9 +177,12 @@ def _get_request(self): """Get a connection, or a shutdown request for this thread to exit.""" while True: conn = self.server.requests.get() - if not isinstance(conn, _RetirementRequest): + if conn is _SHUTDOWNREQUEST: + if self._run is None or self.server.requests._stops(self): + return conn + elif not isinstance(conn, _RetirementRequest): return conn - if self.server.requests._decide_retirement(self, conn): + elif self.server.requests._decide_retirement(self, conn): return _SHUTDOWNREQUEST def _process_connections_until_interrupted(self): @@ -298,22 +317,27 @@ def __init__( # pylint: disable=too-many-positional-arguments self.min = min self.max = max self._threads = [] - self._queue = queue.Queue(maxsize=accepted_queue_size) + self._queue = _RequestQueue(maxsize=accepted_queue_size) self._queue_put_timeout = accepted_queue_timeout self.get = self._queue.get - # Guards _retirements_due and _threads against concurrent access - # from `idle`, `shrink()`, and a worker claiming its own retirement. + # Guards _retirements_due, _threads and the pool's run against + # concurrent access from `idle`, `grow()`, `shrink()`, `stop()`, + # and a worker claiming its own retirement or stop request. stop() + # ends a run, and the threads of the runs it ended shut down on a + # stop request. self._lock = threading.Lock() self._retirements_due = set() + self._run = 0 def start(self): """Start the pool of threads. :raises RuntimeError: if the pool is already started """ - if self._threads: - raise RuntimeError('Threadpools can only be started once.') - self.grow(self.min) + with self._lock: + if self._threads: + raise RuntimeError('Threadpools can only be started once.') + self._grow(self.min) @property def idle(self): @@ -343,10 +367,28 @@ def _serving(self): # A thread clears `ready` as it exits. Workers call this, and before # Python 3.13, is_alive() can fail when two threads call it, or # join(), at once for a thread that is exiting. - return [t for t in self._threads if t.ready and not t._retiring] + return [ + t + for t in self._threads + if t.ready and t._run == self._run and not t._retiring + ] def grow(self, amount): - """Spawn new worker threads (not above self.max).""" + """Spawn new worker threads (not above self.max). + + :raises RuntimeError: while stop() ends the threads + """ + with self._lock: + # A new thread could take the stop request that one of them + # still needs + if any( + t.ready and t._run != self._run and not t._retiring + for t in self._threads + ): + raise RuntimeError('Cannot grow a threadpool while it stops.') + self._grow(amount) + + def _grow(self, amount): budget = max(self.max - len(self._threads), 0) n_new = min(amount, budget) @@ -359,6 +401,7 @@ def grow(self, amount): def _spawn_worker(self): worker = WorkerThread(self.server) worker.name = f'CP Server {worker.name!s}' + worker._run = self._run worker.start() return worker @@ -430,6 +473,15 @@ def _decide_retirement(self, worker, request): worker._retiring = True return True + def _stops(self, worker): + """Tell whether a worker that took a stop request shuts down.""" + with self._lock: + # One that a stop() left behind does not end a later run + if worker._run == self._run: + return False + worker._retiring = True + return True + def stop(self, timeout=5): """Terminate all worker threads. @@ -451,10 +503,19 @@ def stop(self, timeout=5): else: endtime = time.time() + timeout + with self._lock: + # End the run. The retirements that shrink() asked for are no + # longer due, and every thread that has not taken a request, + # of this run or of a stop() that was interrupted, needs one. + self._run += 1 + self._retirements_due.clear() + threads = [t for t in self._threads if t.is_alive()] + n_running = len([t for t in threads if not t._retiring]) + # Must shut down threads here so the code that calls # this method can know when all threads are stopped. - for _worker in self._threads: - self._queue.put(_SHUTDOWNREQUEST) + for _ in range(n_running): + self._queue.put_shutdown(_SHUTDOWNREQUEST) ignored_errors = ( # Raised when start_response called >1 time w/o exc_info or @@ -464,7 +525,10 @@ def stop(self, timeout=5): KeyboardInterrupt, ) - for worker in self._clear_threads(): + current_thread = threading.current_thread() + for worker in threads: + if worker is current_thread: + continue remaining_time = timeout and endtime - time.time() try: worker.join(remaining_time) @@ -475,6 +539,15 @@ def stop(self, timeout=5): except ignored_errors: pass + with self._lock: + # A thread still running keeps the pool from starting again, + # unless it is this one, which exits after its connection + self._threads[:] = [ + t + for t in self._threads + if t.is_alive() and t is not current_thread + ] + @staticmethod @pass_none def _force_close(conn): @@ -491,16 +564,6 @@ def _force_close(conn): # ref #238 pass - def _clear_threads(self): - """Clear self._threads and yield all joinable threads.""" - # threads = pop_all(self._threads) - threads, self._threads[:] = self._threads[:], [] - return ( - thread - for thread in threads - if thread is not threading.current_thread() - ) - @property def qsize(self): """The queue size.""" diff --git a/cheroot/workers/threadpool.pyi b/cheroot/workers/threadpool.pyi index 801a74d6b8..6ec7ea0162 100644 --- a/cheroot/workers/threadpool.pyi +++ b/cheroot/workers/threadpool.pyi @@ -1,3 +1,4 @@ +import queue import threading import typing as _t @@ -11,11 +12,15 @@ trueyzero: TrueyZero class _RetirementRequest: ... +class _RequestQueue(queue.Queue[_t.Any]): + def put_shutdown(self, request: object) -> None: ... + class WorkerThread(threading.Thread): conn: _t.Any server: _t.Any ready: bool _retiring: bool + _run: int | None requests_seen: int bytes_read: int bytes_written: int @@ -33,6 +38,7 @@ class ThreadPool: get: _t.Any _lock: threading.Lock _retirements_due: set[_RetirementRequest] + _run: int def __init__( self, server, @@ -46,6 +52,7 @@ class ThreadPool: def idle(self): ... def put(self, obj) -> None: ... def grow(self, amount) -> None: ... + def _grow(self, amount) -> None: ... def shrink(self, amount) -> None: ... def _serving(self) -> list[WorkerThread]: ... def _decide_retirement( @@ -53,6 +60,7 @@ class ThreadPool: worker: WorkerThread, request: _RetirementRequest, ) -> bool: ... + def _stops(self, worker: WorkerThread) -> bool: ... def stop(self, timeout: int = ...) -> None: ... @property def qsize(self) -> int: ... diff --git a/docs/changelog-fragments.d/882.bugfix.rst b/docs/changelog-fragments.d/882.bugfix.rst new file mode 100644 index 0000000000..d513b81300 --- /dev/null +++ b/docs/changelog-fragments.d/882.bugfix.rst @@ -0,0 +1,12 @@ +Fixed :py:meth:`ThreadPool.stop() ` +leaving shutdown requests queued that ended the threads of the pool when it +started again, so that starting it hung. This happened after stopping a pool +that was still shrinking, one that its own worker stopped on an interrupt, or +one whose stop was interrupted. A stopped pool now starts again once its +previous threads have exited, and stopping it no longer waits for room in a +full connection queue. :py:meth:`ThreadPool.grow() +` now raises +:py:exc:`RuntimeError` while :py:meth:`ThreadPool.stop() +` ends the pool's threads. + +-- by :user:`rm-you` From 4575f5dea21b2e27ba36c3cef0afec7936bbe51d Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Sun, 15 Nov 2026 00:17:37 -0500 Subject: [PATCH 4/6] Let one stop() call at a time end the pool's threads A worker that called stop() on its own pool joined the other threads, so two workers that stopped the pool at once each waited for the other. stop() also dropped the worker that called it from the pool's threads while that worker still handled its connection, so start() could start new threads, one of which could take the stop request that the old worker still needed. And grow() could start a thread while stop() still waited for the old ones, which stop() then left running. A lock now lets one stop() call at a time end the threads. A thread of the pool that finds a call under way returns at once, since that call may be waiting for it to exit. Any other caller waits for that call to finish, then ends the threads still running within what is left of its own timeout, so it still returns only once every thread has exited. grow() and start() refuse while the lock is held. An interrupted call releases the lock and leaves the threads that still run listed, so the next call goes on from there. A worker that ends the threads waits for them no longer than the timeout, closes the connections of those still running, and does not wait for them after that; without a timeout, it waits for none. It stays among the pool's threads until it exits, so the pool starts again only once it has, and grow() refuses meanwhile. Assisted-By: Anthropic Claude Opus 5.5 Signed-off-by: Adam Harwell --- cheroot/test/test_server.py | 333 +++++++++++++++++++++- cheroot/workers/threadpool.py | 87 ++++-- cheroot/workers/threadpool.pyi | 7 + docs/changelog-fragments.d/882.bugfix.rst | 7 +- 4 files changed, 390 insertions(+), 44 deletions(-) diff --git a/cheroot/test/test_server.py b/cheroot/test/test_server.py index 53d74eb9db..49a8adf0c3 100644 --- a/cheroot/test/test_server.py +++ b/cheroot/test/test_server.py @@ -3,6 +3,7 @@ from __future__ import annotations import contextlib +import functools import gc import os import pathlib @@ -1620,28 +1621,334 @@ def test_threadpool_overlapping_stops_end_every_thread( request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Two stop() calls at once, each asking every thread, both finish.""" + """A stop() that comes as another queues on a full queue, both finish.""" pool = _pool_with_one_slot(request, minthreads=2) workers = list(pool._threads) put_shutdown = pool._queue.put_shutdown - together = threading.Barrier(2) + queueing = threading.Event() + resume = threading.Event() - def _put_together(obj: object) -> None: - # Each call has counted every thread before either queues - with contextlib.suppress(threading.BrokenBarrierError): - together.wait(timeout=5) + def _held_put(obj: object) -> None: + queueing.set() + assert resume.wait(10) put_shutdown(obj) - monkeypatch.setattr(pool._queue, 'put_shutdown', _put_together) - stoppers = [threading.Thread(target=pool.stop, daemon=True) for _ in '12'] - for stopper in stoppers: - stopper.start() - for stopper in stoppers: - stopper.join(10) - assert not any(stopper.is_alive() for stopper in stoppers) + waiting = threading.Event() + with monkeypatch.context() as patch, contextlib.ExitStack() as cleanup: + patch.setattr(pool, '_stop_lock', _ObservedStopLock(pool, waiting)) + patch.setattr(pool._queue, 'put_shutdown', _held_put) + cleanup.callback(_join_thread, _stop_in_daemon(pool)) + assert queueing.wait(10) + cleanup.callback(_join_thread, _stop_in_daemon(pool)) + cleanup.callback(_release_events, resume) + assert waiting.wait(10) assert not any(worker.is_alive() for worker in workers) +def _pool_of_daemon_threads( + request: pytest.FixtureRequest, + *, + minthreads: int, +) -> ThreadPool: + """Start a pool whose threads do not keep the tests from ending. + + Threads inherit their daemon flag, so starting the pool from a daemon + thread makes a regression that leaves threads waiting fail the test + instead of hanging the run. + """ + pool = ThreadPool(_make_server(), min=minthreads) + pool.server.requests = pool + starter = threading.Thread(target=pool.start, daemon=True) + starter.start() + _join_thread(starter) + request.addfinalizer(functools.partial(_stop_in_daemon, pool)) + return pool + + +def _stop_in_daemon(pool: ThreadPool) -> threading.Thread: + """Stop a pool in a thread that does not keep the tests from ending.""" + stopper = threading.Thread(target=pool.stop, daemon=True) + stopper.start() + return stopper + + +class _StoppingConnection(_HeldConnection): + """A connection whose handler stops the pool, then waits to be closed.""" + + def __init__( + self, + pool: ThreadPool, + together: threading.Barrier | None = None, + stop_kwargs: dict[str, float | None] | None = None, + ) -> None: + super().__init__() + self.stopped = threading.Event() + self._pool = pool + self._together = together + self._stop_kwargs = ( + {'timeout': 0} if stop_kwargs is None else stop_kwargs + ) + + def communicate(self) -> bool: + """Stop the pool, then handle the connection until it is closed.""" + if self._together is not None: + self._together.wait(10) + self._pool.stop(**self._stop_kwargs) + self.stopped.set() + return super().communicate() + + +class _ObservedStopLock: + """Report a stop() call that has to wait for the one under way.""" + + def __init__(self, pool: ThreadPool, waiting: threading.Event) -> None: + self._lock = pool._stop_lock + self._waiting = waiting + + def acquire(self, *, blocking: bool = True) -> bool: + """Take the lock, reporting a caller that waits for it.""" + if self._lock.acquire(blocking=False): + return True + if blocking: + self._waiting.set() + return self._lock.acquire(blocking=blocking) + + def release(self) -> None: + """Release the lock.""" + self._lock.release() + + def locked(self) -> bool: + """Tell whether a stop() call is under way.""" + return self._lock.locked() + + +@pytest.mark.parametrize('n_workers', (2, 3)) +@pytest.mark.parametrize( + 'stop_kwargs', + ( + pytest.param({}, id='default-timeout'), + pytest.param({'timeout': 0}, id='zero-timeout'), + pytest.param({'timeout': 60}, id='long-timeout'), + pytest.param({'timeout': None}, id='no-timeout'), + ), +) +def test_threadpool_workers_that_stop_their_pool_at_once( + request: pytest.FixtureRequest, + n_workers: int, + stop_kwargs: dict[str, float | None], +) -> None: + """Workers that stop their pool at once do not wait for each other.""" + pool = _pool_of_daemon_threads(request, minthreads=n_workers) + workers = tuple(pool._threads) + together = threading.Barrier(n_workers) + connections = [ + _StoppingConnection(pool, together, stop_kwargs) for _ in workers + ] + for connection in connections: + connection.closed.set() + pool.put(connection) + # Well within the default timeout, which workers that wait for each + # other spend in full + assert all(connection.stopped.wait(3) for connection in connections) + assert _wait_until( + compute_condition=lambda: not any(t.is_alive() for t in workers), + ) + + +def test_threadpool_worker_stop_during_an_outside_stop( + request: pytest.FixtureRequest, +) -> None: + """A worker's stop() returns at once while another call ends the threads.""" + pool = _pool_of_daemon_threads(request, minthreads=2) + workers = tuple(pool._threads) + stuck = _HeldConnection() + together = threading.Barrier(2) + stopping = _StoppingConnection(pool, together, stop_kwargs={}) + stopping.closed.set() + pool.put(stuck) + pool.put(stopping) + assert _wait_until( + compute_condition=lambda: all(t.conn is not None for t in workers), + ) + with contextlib.ExitStack() as cleanup: + cleanup.callback(_join_thread, _stop_in_daemon(pool)) + cleanup.callback(_release_events, stuck.closed) + # That call has asked both threads, and waits for the stuck one + assert _wait_until( + compute_condition=lambda: pool.qsize == len(workers), + ) + together.wait(10) + # Well within the default timeout, which that call spends waiting + assert stopping.stopped.wait(3) + # That call returns only once every thread has exited + assert not any(t.is_alive() for t in workers) + + +def test_threadpool_outside_stop_during_a_worker_stop( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A stop() that comes during a worker's waits for it, then for all.""" + pool = _pool_of_daemon_threads(request, minthreads=2) + workers = tuple(pool._threads) + stuck = _HeldConnection() + pool.put(stuck) + assert _wait_until( + compute_condition=lambda: any(t.conn is stuck for t in workers), + ) + stopping = _StoppingConnection(pool, stop_kwargs={}) + stopping.closed.set() + pool.put(stopping) + # The worker's stop() has asked both threads, and waits for the stuck one + assert _wait_until(compute_condition=lambda: pool.qsize == len(workers)) + waiting = threading.Event() + with monkeypatch.context() as patch, contextlib.ExitStack() as cleanup: + patch.setattr(pool, '_stop_lock', _ObservedStopLock(pool, waiting)) + cleanup.callback(_join_thread, _stop_in_daemon(pool)) + cleanup.callback(_release_events, stuck.closed) + assert waiting.wait(10) + assert stopping.stopped.is_set() + # It returns only once every thread has exited, the worker included + assert not any(t.is_alive() for t in workers) + + +def test_threadpool_worker_stop_without_a_timeout_does_not_wait( + request: pytest.FixtureRequest, +) -> None: + """A worker's stop() without a timeout only asks the threads to stop.""" + pool = _pool_of_daemon_threads(request, minthreads=2) + workers = tuple(pool._threads) + stuck = _HeldConnection() + pool.put(stuck) + assert _wait_until( + compute_condition=lambda: any(t.conn is stuck for t in workers), + ) + stopping = _StoppingConnection(pool, stop_kwargs={'timeout': None}) + stopping.closed.set() + with contextlib.ExitStack() as cleanup: + cleanup.callback(_release_events, stuck.closed) + pool.put(stopping) + assert stopping.stopped.wait(10) + assert not stuck.closed.is_set() + assert _wait_until( + compute_condition=lambda: not any(t.is_alive() for t in workers), + ) + + +def test_threadpool_stop_interrupted_while_waiting_can_be_repeated( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A stop() interrupted as it waits leaves the next call to end the pool.""" + pool = _pool_of_daemon_threads(request, minthreads=1) + worker = pool._threads[0] + stuck = _HeldConnection() + pool.put(stuck) + assert _wait_until(compute_condition=lambda: worker.conn is stuck) + + def _exiting_join(*_args: object) -> None: + sys.exit() + + with monkeypatch.context() as patch: + patch.setattr(worker, 'join', _exiting_join) + with pytest.raises(SystemExit): + pool.stop() + stopper = threading.Thread( + target=functools.partial(pool.stop, timeout=0), + daemon=True, + ) + stopper.start() + _join_thread(stopper) + assert stuck.closed.is_set() + assert _wait_until(compute_condition=lambda: not worker.is_alive()) + + +def test_threadpool_worker_that_stops_its_pool_closes_stuck_connections( + request: pytest.FixtureRequest, +) -> None: + """A worker that stops its pool still closes a stuck thread's connection.""" + pool = _pool_of_daemon_threads(request, minthreads=2) + stuck = _HeldConnection() + pool.put(stuck) + assert _wait_until( + compute_condition=lambda: any(t.conn is stuck for t in pool._threads), + ) + stopping = _StoppingConnection(pool) + stopping.closed.set() + pool.put(stopping) + assert stopping.stopped.wait(10) + # Its stop() had a timeout of 0, after which it closes the connection + assert stuck.closed.is_set() + assert _wait_until( + compute_condition=lambda: not any(t.is_alive() for t in pool._threads), + ) + + +def test_threadpool_restart_waits_for_a_worker_that_stopped_it( + request: pytest.FixtureRequest, +) -> None: + """A pool that its worker stopped starts again once that worker exits.""" + pool = _pool_of_daemon_threads(request, minthreads=1) + worker = pool._threads[0] + connection = _StoppingConnection(pool) + pool.put(connection) + assert connection.stopped.wait(10) + # A new thread could take the request that this one still needs + with pytest.raises(RuntimeError, match='can only be started once'): + pool.start() + connection.closed.set() + assert _wait_until(compute_condition=lambda: not worker.is_alive()) + pool.start() + assert pool.idle == pool.min + + +def test_threadpool_grow_is_refused_until_stop_returns( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A thread grown while stop() waits for old ones would outlive it.""" + with _hold_retiring_workers(monkeypatch) as at_exit: + pool = _pool_of_daemon_threads(request, minthreads=1) + stopper = threading.Thread(target=pool.stop, daemon=True) + stopper.start() + # The old thread took its stop request, but has not exited yet + assert at_exit.get(timeout=10) + with pytest.raises(RuntimeError, match='while it stops'): + pool.grow(3) + _join_thread(stopper) + assert not any(t.is_alive() for t in pool._threads) + + +def test_threadpool_start_is_refused_until_stop_returns( + single_thread_pool: ThreadPool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A pool started again before stop() returns would outlive it.""" + pool = single_thread_pool + worker = pool._threads[0] + exited = threading.Event() + resume = threading.Event() + original_join = worker.join + + def _join_then_hold(timeout: float | None = None) -> None: + original_join(timeout) + exited.set() + assert resume.wait(10) + + monkeypatch.setattr(worker, 'join', _join_then_hold) + stopper = threading.Thread(target=pool.stop, daemon=True) + with contextlib.ExitStack() as cleanup: + cleanup.callback(_join_thread, stopper) + cleanup.callback(resume.set) + stopper.start() + # The old thread has exited, but stop() has not returned + assert exited.wait(10) + with pytest.raises(RuntimeError, match='only be started once'): + pool.start() + pool.start() + assert len(pool._threads) == pool.min + + def test_threadpool_grow_while_stopping_is_refused( single_thread_pool: ThreadPool, monkeypatch: pytest.MonkeyPatch, diff --git a/cheroot/workers/threadpool.py b/cheroot/workers/threadpool.py index aff3608e1a..175e96de5e 100644 --- a/cheroot/workers/threadpool.py +++ b/cheroot/workers/threadpool.py @@ -328,6 +328,8 @@ def __init__( # pylint: disable=too-many-positional-arguments self._lock = threading.Lock() self._retirements_due = set() self._run = 0 + # Held by the stop() call that ends the threads + self._stop_lock = threading.Lock() def start(self): """Start the pool of threads. @@ -335,7 +337,9 @@ def start(self): :raises RuntimeError: if the pool is already started """ with self._lock: - if self._threads: + # Forget the threads that have exited since stop() + self._threads[:] = [t for t in self._threads if t.ready] + if self._threads or self._stop_lock.locked(): raise RuntimeError('Threadpools can only be started once.') self._grow(self.min) @@ -379,9 +383,9 @@ def grow(self, amount): :raises RuntimeError: while stop() ends the threads """ with self._lock: - # A new thread could take the stop request that one of them - # still needs - if any( + # stop() would not know of a new thread, which could also take + # the stop request that one of the old ones still needs + if self._stop_lock.locked() or any( t.ready and t._run != self._run and not t._retiring for t in self._threads ): @@ -485,8 +489,13 @@ def _stops(self, worker): def stop(self, timeout=5): """Terminate all worker threads. + One call at a time ends the threads. A call from a thread of the + pool returns at once while another call does. Any other call waits + for that one to finish, then ends the threads still running. + Args: - timeout (int): time to wait for threads to stop gracefully + timeout (int): time to wait for threads to stop gracefully, + counted from the call, before closing their connections """ # for compatability, negative timeouts are treated like None # TODO: treat negative timeouts like already expired timeouts @@ -503,20 +512,40 @@ def stop(self, timeout=5): else: endtime = time.time() + timeout + # One call at a time ends the threads. A thread of the pool returns + # at once while another call does, as that call may be waiting for + # it to exit. Any other caller waits for that call, then ends what + # is left within what remains of its own timeout. with self._lock: - # End the run. The retirements that shrink() asked for are no - # longer due, and every thread that has not taken a request, - # of this run or of a stop() that was interrupted, needs one. - self._run += 1 - self._retirements_due.clear() - threads = [t for t in self._threads if t.is_alive()] - n_running = len([t for t in threads if not t._retiring]) - - # Must shut down threads here so the code that calls - # this method can know when all threads are stopped. - for _ in range(n_running): - self._queue.put_shutdown(_SHUTDOWNREQUEST) - + from_worker = threading.current_thread() in self._threads + if not self._stop_lock.acquire(blocking=not from_worker): + return + try: + with self._lock: + # End the run. The retirements that shrink() asked for are no + # longer due, and every thread that has not taken a request, + # of this run or of a stop() that was interrupted, needs one. + self._run += 1 + self._retirements_due.clear() + threads = [t for t in self._threads if t.is_alive()] + n_running = len([t for t in threads if not t._retiring]) + + # Must shut down threads here so the code that calls + # this method can know when all threads are stopped. + for _ in range(n_running): + self._queue.put_shutdown(_SHUTDOWNREQUEST) + + self._wait_for(threads, timeout, endtime) + finally: + with self._lock: + # A thread still running, even this one, keeps the pool + # from starting again: a new thread could take its stop + # request + self._threads[:] = [t for t in self._threads if t.ready] + self._stop_lock.release() + + def _wait_for(self, threads, timeout, endtime): + """Wait for threads to exit, closing connections after the timeout.""" ignored_errors = ( # Raised when start_response called >1 time w/o exc_info or # wsgi write is called before start_response. See cheroot#261 @@ -525,29 +554,27 @@ def stop(self, timeout=5): KeyboardInterrupt, ) + # A thread of the pool that stops it keeps the pool from stopping + # until it returns, so it waits no longer than the timeout, and not + # at all without one current_thread = threading.current_thread() + from_worker = current_thread in threads + if from_worker: + threads.remove(current_thread) + if timeout is None: + return for worker in threads: - if worker is current_thread: - continue remaining_time = timeout and endtime - time.time() try: worker.join(remaining_time) if worker.is_alive(): # Timeout exhausted; forcibly shut down the socket. self._force_close(worker.conn) - worker.join() + if not from_worker: + worker.join() except ignored_errors: pass - with self._lock: - # A thread still running keeps the pool from starting again, - # unless it is this one, which exits after its connection - self._threads[:] = [ - t - for t in self._threads - if t.is_alive() and t is not current_thread - ] - @staticmethod @pass_none def _force_close(conn): diff --git a/cheroot/workers/threadpool.pyi b/cheroot/workers/threadpool.pyi index 6ec7ea0162..5f188037a7 100644 --- a/cheroot/workers/threadpool.pyi +++ b/cheroot/workers/threadpool.pyi @@ -39,6 +39,7 @@ class ThreadPool: _lock: threading.Lock _retirements_due: set[_RetirementRequest] _run: int + _stop_lock: threading.Lock def __init__( self, server, @@ -62,5 +63,11 @@ class ThreadPool: ) -> bool: ... def _stops(self, worker: WorkerThread) -> bool: ... def stop(self, timeout: int = ...) -> None: ... + def _wait_for( + self, + threads: list[WorkerThread], + timeout: float | None, + endtime: float, + ) -> None: ... @property def qsize(self) -> int: ... diff --git a/docs/changelog-fragments.d/882.bugfix.rst b/docs/changelog-fragments.d/882.bugfix.rst index d513b81300..3270de9005 100644 --- a/docs/changelog-fragments.d/882.bugfix.rst +++ b/docs/changelog-fragments.d/882.bugfix.rst @@ -7,6 +7,11 @@ previous threads have exited, and stopping it no longer waits for room in a full connection queue. :py:meth:`ThreadPool.grow() ` now raises :py:exc:`RuntimeError` while :py:meth:`ThreadPool.stop() -` ends the pool's threads. +` ends the pool's threads, and a +worker that stops its own pool waits for the other threads no longer than the +timeout before it closes their connections. One call at a time now ends the +threads: a call from one of the pool's workers returns at once while another +call does, so workers that stop the pool together no longer wait for each other +until the timeout, and any other call waits for that one to finish. -- by :user:`rm-you` From 557a6863b030abcab4a3c286d19171246d312999 Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Sun, 15 Nov 2026 01:06:06 -0500 Subject: [PATCH 5/6] Release the stop lock even if stop()'s cleanup is interrupted stop() took the pool's lock to tidy up its list of threads, and only then released the lock that marks a stop() under way. An interrupt while it waited for the pool's lock, such as a second Ctrl-C while a worker held it, skipped the release. Every later stop() then waited for that lock forever, and grow() and start() kept refusing, even once every thread had exited. The release now has a finally of its own. The list of threads may then keep some that have exited, which start() and the next stop() forget anyway. Assisted-By: Anthropic Claude Opus 5.5 Signed-off-by: Adam Harwell --- cheroot/test/test_server.py | 46 +++++++++++++++++++++++++++++++++++ cheroot/workers/threadpool.py | 15 +++++++----- 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/cheroot/test/test_server.py b/cheroot/test/test_server.py index 49a8adf0c3..c87b05c0a6 100644 --- a/cheroot/test/test_server.py +++ b/cheroot/test/test_server.py @@ -1863,6 +1863,52 @@ def _exiting_join(*_args: object) -> None: assert _wait_until(compute_condition=lambda: not worker.is_alive()) +class _LockInterruptedOnAcquire: + """The pool's lock, interrupted once before one thread acquires it.""" + + def __init__(self, pool: ThreadPool, thread: threading.Thread) -> None: + self.lock = pool._lock + self.interrupted = False + self._thread = thread + + def __enter__(self) -> None: + if threading.current_thread() is self._thread and not self.interrupted: + self.interrupted = True + # Such as a second Ctrl-C while the thread waits for the lock + raise KeyboardInterrupt + self.lock.acquire() + + def __exit__(self, *_exc: object) -> None: + self.lock.release() + + +def test_threadpool_stop_interrupted_in_its_cleanup_can_be_repeated( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A stop() interrupted as it tidies up lets the pool stop and start.""" + pool = _pool_of_daemon_threads(request, minthreads=2) + workers = tuple(pool._threads) + original_wait_for = pool._wait_for + interrupted = _LockInterruptedOnAcquire(pool, threading.current_thread()) + with monkeypatch.context() as patch: + + def _wait_then_interrupt(*args: object) -> None: + original_wait_for(*args) + # The next time this thread takes the pool's lock is to tidy up + patch.setattr(pool, '_lock', interrupted) + + patch.setattr(pool, '_wait_for', _wait_then_interrupt) + with pytest.raises(KeyboardInterrupt): + pool.stop() + assert interrupted.interrupted + # Checked first, as a later stop() would wait for it forever + assert not pool._stop_lock.locked() + assert not any(t.is_alive() for t in workers) + pool.stop() + _assert_restart_ignores_leftovers(pool) + + def test_threadpool_worker_that_stops_its_pool_closes_stuck_connections( request: pytest.FixtureRequest, ) -> None: diff --git a/cheroot/workers/threadpool.py b/cheroot/workers/threadpool.py index 175e96de5e..db5bc9bb52 100644 --- a/cheroot/workers/threadpool.py +++ b/cheroot/workers/threadpool.py @@ -537,12 +537,15 @@ def stop(self, timeout=5): self._wait_for(threads, timeout, endtime) finally: - with self._lock: - # A thread still running, even this one, keeps the pool - # from starting again: a new thread could take its stop - # request - self._threads[:] = [t for t in self._threads if t.ready] - self._stop_lock.release() + try: + with self._lock: + # A thread still running, even this one, keeps the pool + # from starting again: a new thread could take its stop + # request + self._threads[:] = [t for t in self._threads if t.ready] + finally: + # Even if an interrupt came as it waited for the lock above + self._stop_lock.release() def _wait_for(self, threads, timeout, endtime): """Wait for threads to exit, closing connections after the timeout.""" From 0329e2df12048eb007e4e7a59e7783d5e3ace92f Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Sun, 15 Nov 2026 02:17:10 -0500 Subject: [PATCH 6/6] Queue stop requests with the queue's own put() again put_shutdown() let a stop request into a full connection queue by using queue.Queue internals: its not_empty condition, _put() and unfinished_tasks. Those are private, and under Eventlet's monkey patching queue.Queue is Eventlet's own class, which lacks them, so every stop() raised AttributeError. stop() now uses put(), as on main. Since only one stop() call at a time queues requests, two calls can no longer fill a bounded queue with requests for each other's threads. What is left is what main does too: with a bounded queue full of connections and every thread stuck on one, stop() waits for room before it can reach the timeout. Assisted-By: Anthropic Claude Opus 5.5 Signed-off-by: Adam Harwell --- cheroot/test/test_server.py | 47 ++++++----------------- cheroot/workers/threadpool.py | 17 +------- cheroot/workers/threadpool.pyi | 4 -- docs/changelog-fragments.d/882.bugfix.rst | 3 +- 4 files changed, 15 insertions(+), 56 deletions(-) diff --git a/cheroot/test/test_server.py b/cheroot/test/test_server.py index c87b05c0a6..620b767378 100644 --- a/cheroot/test/test_server.py +++ b/cheroot/test/test_server.py @@ -1386,8 +1386,12 @@ def test_threadpool_shrink_interrupted_after_a_stop( pool = single_thread_pool pool.grow(1) release = threading.Event() + queue_put = pool._queue.put - def _held_interrupted_put(_obj: object) -> None: + def _held_interrupted_put(obj: object) -> None: + # Only the shrink() call waits; stop() queues its requests + if threading.current_thread() is not shrinker: + return queue_put(obj) assert release.wait(10) raise KeyboardInterrupt @@ -1536,7 +1540,7 @@ def test_threadpool_stop_retries_an_interrupted_enqueue( with _paused_workers(monkeypatch) as release: pool = _prepared_pool(request, minthreads=2) workers = list(pool._threads) - queue_put = pool._queue.put_shutdown + queue_put = pool._queue.put queued: list[object] = [] def _put_then_release(obj: object) -> None: @@ -1547,14 +1551,10 @@ def _put_then_release(obj: object) -> None: release.set() with monkeypatch.context() as patch: - patch.setattr( - pool._queue, - 'put_shutdown', - _interrupt_after(queue_put), - ) + patch.setattr(pool._queue, 'put', _interrupt_after(queue_put)) with pytest.raises(KeyboardInterrupt): pool.stop() - patch.setattr(pool._queue, 'put_shutdown', _put_then_release) + patch.setattr(pool._queue, 'put', _put_then_release) pool.stop() assert not any(worker.is_alive() for worker in workers) assert pool.qsize == 1 @@ -1594,49 +1594,26 @@ def _pool_with_one_slot( return pool -def test_threadpool_stop_with_a_full_queue_reaches_force_close( - request: pytest.FixtureRequest, -) -> None: - """A full queue must not keep stop() from closing a stuck connection.""" - pool = _pool_with_one_slot(request, minthreads=1) - worker = pool._threads[0] - stuck = _HeldConnection() - pool.put(stuck) - assert _wait_until(compute_condition=lambda: worker.conn is stuck) - # Another connection fills the queue - waiting = _HeldConnection() - waiting.closed.set() - pool.put(waiting) - stopper = threading.Thread(target=pool.stop, args=(0,), daemon=True) - with contextlib.ExitStack() as cleanup: - cleanup.callback(stuck.closed.set) - stopper.start() - stopper.join(5) - # Checked while the connection is still stuck - assert not stopper.is_alive() - assert not worker.is_alive() - - def test_threadpool_overlapping_stops_end_every_thread( request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, ) -> None: - """A stop() that comes as another queues on a full queue, both finish.""" + """A stop() that comes as another queues on a small queue, both finish.""" pool = _pool_with_one_slot(request, minthreads=2) workers = list(pool._threads) - put_shutdown = pool._queue.put_shutdown + queue_put = pool._queue.put queueing = threading.Event() resume = threading.Event() def _held_put(obj: object) -> None: queueing.set() assert resume.wait(10) - put_shutdown(obj) + queue_put(obj) waiting = threading.Event() with monkeypatch.context() as patch, contextlib.ExitStack() as cleanup: patch.setattr(pool, '_stop_lock', _ObservedStopLock(pool, waiting)) - patch.setattr(pool._queue, 'put_shutdown', _held_put) + patch.setattr(pool._queue, 'put', _held_put) cleanup.callback(_join_thread, _stop_in_daemon(pool)) assert queueing.wait(10) cleanup.callback(_join_thread, _stop_in_daemon(pool)) diff --git a/cheroot/workers/threadpool.py b/cheroot/workers/threadpool.py index db5bc9bb52..027d305ad3 100644 --- a/cheroot/workers/threadpool.py +++ b/cheroot/workers/threadpool.py @@ -37,19 +37,6 @@ class _RetirementRequest: """A ticket that shrink() queues, for any one thread to take and retire.""" -class _RequestQueue(queue.Queue): - """A queue of connections, and of requests for workers to shut down.""" - - def put_shutdown(self, request): - """Queue a shutdown request, even when the queue has no room.""" - # stop() then always reaches its timeout, which closes the - # connection that a worker may be stuck on - with self.not_empty: - self._put(request) - self.unfinished_tasks += 1 - self.not_empty.notify() - - class WorkerThread(threading.Thread): """Thread which continuously polls a Queue for Connection objects. @@ -317,7 +304,7 @@ def __init__( # pylint: disable=too-many-positional-arguments self.min = min self.max = max self._threads = [] - self._queue = _RequestQueue(maxsize=accepted_queue_size) + self._queue = queue.Queue(maxsize=accepted_queue_size) self._queue_put_timeout = accepted_queue_timeout self.get = self._queue.get # Guards _retirements_due, _threads and the pool's run against @@ -533,7 +520,7 @@ def stop(self, timeout=5): # Must shut down threads here so the code that calls # this method can know when all threads are stopped. for _ in range(n_running): - self._queue.put_shutdown(_SHUTDOWNREQUEST) + self._queue.put(_SHUTDOWNREQUEST) self._wait_for(threads, timeout, endtime) finally: diff --git a/cheroot/workers/threadpool.pyi b/cheroot/workers/threadpool.pyi index 5f188037a7..63aa47d94f 100644 --- a/cheroot/workers/threadpool.pyi +++ b/cheroot/workers/threadpool.pyi @@ -1,4 +1,3 @@ -import queue import threading import typing as _t @@ -12,9 +11,6 @@ trueyzero: TrueyZero class _RetirementRequest: ... -class _RequestQueue(queue.Queue[_t.Any]): - def put_shutdown(self, request: object) -> None: ... - class WorkerThread(threading.Thread): conn: _t.Any server: _t.Any diff --git a/docs/changelog-fragments.d/882.bugfix.rst b/docs/changelog-fragments.d/882.bugfix.rst index 3270de9005..c964b093bd 100644 --- a/docs/changelog-fragments.d/882.bugfix.rst +++ b/docs/changelog-fragments.d/882.bugfix.rst @@ -3,8 +3,7 @@ leaving shutdown requests queued that ended the threads of the pool when it started again, so that starting it hung. This happened after stopping a pool that was still shrinking, one that its own worker stopped on an interrupt, or one whose stop was interrupted. A stopped pool now starts again once its -previous threads have exited, and stopping it no longer waits for room in a -full connection queue. :py:meth:`ThreadPool.grow() +previous threads have exited. :py:meth:`ThreadPool.grow() ` now raises :py:exc:`RuntimeError` while :py:meth:`ThreadPool.stop() ` ends the pool's threads, and a