From d46908afe02b8d6a569e3a4f013d8280a82352e8 Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Sun, 15 Nov 2026 00:17:37 -0500 Subject: [PATCH 1/3] 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/3] 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 e66de9e9c7c5044451e3b3844c56402144a4cb76 Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Sun, 15 Nov 2026 19:56:48 -0500 Subject: [PATCH 3/3] Reword shrink()'s cleanup comment, as in review The comment in shrink()'s finally block now names both cases that its cleanup handles: a retirement request that never reached the queue, and one that did as shrink() was interrupted before it was counted. Assisted-By: Anthropic Claude Opus 5.5 Signed-off-by: Adam Harwell --- cheroot/workers/threadpool.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/cheroot/workers/threadpool.py b/cheroot/workers/threadpool.py index 514b5a0e67..d986133686 100644 --- a/cheroot/workers/threadpool.py +++ b/cheroot/workers/threadpool.py @@ -399,9 +399,15 @@ def shrink(self, amount): 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. + # As _retirements_due is updated before retirement + # requests are put on the queue, it is possible for the + # queue and _retirements_due to get out of sync if + # shrink() is interrupted. Here we remove any retirement + # requests from _retirements_due that 1) never made it + # into the queue, or 2) entered the queue but shrink() + # was interrupted right before n_queued was incremented. + # A worker that collects such a request will call + # _decide_retirement() which will in turn reject it. with self._lock: self._retirements_due.difference_update( retirement_requests[n_queued:],