Skip to content

Make leftover shutdown requests harmless to a restarted pool - #882

Open
rm-you wants to merge 6 commits into
cherrypy:mainfrom
rm-you:fix/threadpool-stop-leftovers
Open

rm-you wants to merge 6 commits into
cherrypy:mainfrom
rm-you:fix/threadpool-stop-leftovers

Conversation

@rm-you

@rm-you rm-you commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Note

Second PR in the thread-pool series: #859 → #882. It includes #859 until that merges.
This PR's own changes: https://github.com/cherrypy/cheroot/compare/eb62843a33c9cb4e100ae91f3f94ba56ce22ee77..0329e2df12048eb007e4e7a59e7783d5e3ace92f

What kind of change does this PR introduce?

  • 🐞 bug fix
  • 🐣 feature
  • 📋 docs update
  • 📋 tests/coverage improvement
  • 📋 refactoring
  • 💥 other

What do these changes do?

Stopping a pool could leave shutdown requests in its queue. stop() queued one for every thread in its list, and each ended whichever thread took it. But a thread that shrink() had already retired takes none, and neither does a worker that stops its own pool on an interrupt, such as a KeyboardInterrupt from the application. Requests that shrink() queued while the pool stopped stayed too. When the pool started again, its new threads took those requests and exited, and start() waited for them forever. A dead thread still in the list also got a request, which could wait forever for room in a bounded queue. And an interrupted stop() could not be repeated, because it had already emptied the list.

Now each thread records the run of the pool that it serves, and stop() ends the run:

  • The shutdowns that shrink() asked for are no longer due.
  • 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, and nothing has to be removed from the queue.
  • stop() queues one request for each live thread that has not taken one yet.
  • Threads still running when stop() returns stay in the list, so a later stop() ends them.
  • grow() and start() take the pool's lock, so stop() also ends the threads that a grow() call was starting.
  • grow() and start() refuse until stop() has returned, since stop() would not know of a new thread. grow() also refuses while a thread of the ended run has not taken its stop request, since a new thread could otherwise take it.
  • A worker that stops its own pool waits for the other threads no longer than the timeout and closes the connections of those still running, as any caller does. It then does not wait for them to exit, since another worker may be stopping the pool too and waiting for it. Without a timeout, it waits for none. It stays in the pool's threads until it exits, so the pool does not start again before then.
  • One stop() call at a time ends the threads. A worker that calls stop() while another call does returns at once, since 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. So workers that stop the pool together no longer wait for each other until the timeout, and a second call from outside the pool still returns only once every thread has exited.
  • Stop requests go into the queue with its own put(), as on main. Since one stop() call at a time queues them, two calls cannot fill a bounded queue with requests for each other's threads.

Are there changes in behavior for the user?

  • start() raises RuntimeError while a thread of the last run still runs, as it did whenever the list was not empty, including a worker that stopped its own pool, and until stop() has returned.
  • stop() called from one of the pool's workers waits for the other threads no longer than its timeout, closes the connections of those still running, and returns without waiting for them to exit. Without a timeout, it returns at once.
  • A stop() call that comes while another runs returns at once if it is from one of the pool's workers. From any other thread, it waits for that call to finish, then ends the threads still running. Its timeout counts from its own start, including that wait. While it waits, it leaves closing connections to the call under way, so behind a call without a timeout it waits as long as that call does.
  • A stopped pool may keep a request in its queue, which qsize shows, until it starts again. Its first idle thread then drops it.
  • grow() raises RuntimeError until stop() has returned. After that, it starts threads in the new run, and a later stop() ends them.
  • Connections in the queue are left alone.
  • With a bounded queue full of connections while every worker is stuck, stop() still waits for room before it reaches its timeout, as on main. That is ThreadPool.stop() waits for room in a full queue before it closes stuck connections #889.

Is it a substantial burden for the maintainers to support this?

It adds one run number to the pool and to each worker, a check when a worker takes a stop request, and a lock that the stop() call under way holds.

This PR's own changes are four commits: leftover requests and restarts, one stop() call at a time, a fix so that an interrupt during stop()'s final cleanup cannot leave it marked as under way, and stop requests queued with the queue's own put() again, so that stop() works under Eventlet's monkey patching. They take in the follow-ups from four independent reviews (stop requests and a full queue, grow() during stop(), a test, two workers stopping the pool at once, a worker that stops its pool before a restart, a worker's stop() and stuck connections, grow() or start() before stop() returns, and one stop() call at a time).

Of the 24 new tests (32 cases), 17 fail or hang on #859's code. The other 7 cover what #859's code already gets right and the new stop() must keep: stop() ends every thread whatever shrink() counted, a worker that stops its own pool exits, a thread whose join was interrupted exits later, a worker that stops its own pool still closes the connections that threads are stuck on after the timeout, workers that stop the pool together do not wait for each other, a worker's stop() during another call returns at once, and a shrink() interrupted after a stop() leaves the next run's retirements alone. Two defensive checks have no test that fails without them: a run check in the serving count, and marking a thread that takes a stop request so that a repeated stop() does not ask it again. Each matters only in orderings that a test cannot set up without patching the pool's internals.

Stop requests go in with the queue's own put() because an earlier version's put_shutdown() relied on queue.Queue internals that Eventlet's monkey-patched queue.Queue lacks: oslo.messaging's HTTP-RPC driver tests, which run under Eventlet, failed 31 of 248 with AttributeError on that version, and pass with this one, also with #858 and #881 merged in.

Local benchmark of an earlier version of this series (#859 and #882 together; since then, the only change on the per-connection path is one isinstance() check), the previous version of both, and main, on Python 3.11 on one machine. The server (10 worker threads) and the client (8 threads) ran in separate processes, for 6 interleaved rounds of 8 seconds each: 997,184 requests, no errors.

  • Median requests per second against main: this series +0.3% with keep-alive and +1.5% with a new connection per request; the previous version -0.5% and -0.6%. Rounds varied by about ±3%, so none of these differences is real.
  • stop() plus start() took about 1.1 ms with all three.
  • A grow(20) and shrink(20) cycle took about 2.9 ms with both versions of the fix. On main it hangs on the bug fixed here.

Overlapping stop() calls with the default timeout, 5 trials each, real worker threads, against main and the previous version of this PR:

main previous version this version
2 / 3 workers stop the pool together 0.2 / 0.4 ms 5.0 / 5.0 s 0.4 / 0.5 ms
A worker's stop() during an outside one 0.01 ms 250 ms (a 250 ms request drains) 0.01 ms
An outside stop() during a worker's 0.01 ms, with 2 threads still running 250 ms, all exited 250 ms, all exited

Stop and start at 1, 16 and 64 threads, grow and shrink cycles, and 50 ms and 250 ms drains match main within 0.2 ms. The latest change does not touch the per-connection path. An HTTP run after it showed no difference from the previous version, but this machine was too noisy for that run (trials varied by about ±10%) to tell differences of 1 to 2%.

Related issue number

Fixes #861, with #859.

Checklist

Tip

New to open source contributions? Making a lovely PR is a great read.

  • I wrote descriptive pull request text above
  • The PR relates to only one subject with a clear title
    and description in grammatically correct, complete sentences
  • I think the code is well written
  • Unit tests for the changes exist
  • Integration tests for the changes exist (if applicable)
  • I used the same coding conventions as the rest of the project
  • The new code doesn't generate linter offenses
  • Project documentation (in docs/) and inline docstrings reflect the changes
  • My commits each have a descriptive title and a body explaining the why
    (see good commit messages)
  • I have added a change log entry
    (can be done once the PR number is known; alternatively, you can
    use a related issue number if one exists)
  • I'm planning to squash related commits together before final merge
  • I have read the contribution guide and the
    code of conduct

Prepared with Anthropic Claude Opus 5.5 on behalf of Adam Harwell (@rm-you). Several regression tests build on ones written with OpenAI Codex for the previous version of this PR.

@agentscanapp

agentscanapp Bot commented Nov 12, 2026

Copy link
Copy Markdown

Automation signals

Activity patterns show signs of automation.

View full analysis →

Report this account →

Evidence
  • Very high PR volume (daily): 36 PRs within a single 24-hour window
  • High PR volume (weekly): 63 PRs within a single 7-day window
  • 24/7 activity pattern: Active in 23 of 24 hours, with the longest break being only 1.3 hours

Last 5 PRs:

This is an automated analysis by AgentScan

@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.42602% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.88%. Comparing base (47a373f) to head (0329e2d).
⚠️ Report is 98 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #882      +/-   ##
==========================================
+ Coverage   75.99%   79.88%   +3.89%     
==========================================
  Files          41       41              
  Lines        4932     5857     +925     
  Branches      561      642      +81     
==========================================
+ Hits         3748     4679     +931     
+ Misses       1045     1034      -11     
- Partials      139      144       +5     

@rm-you
rm-you force-pushed the fix/threadpool-stop-leftovers branch from 1239a33 to 1d4d6d8 Compare November 12, 2026 07:02
@read-the-docs-community

read-the-docs-community Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 cheroot | 🛠️ Build #35906131 | 📁 Comparing 0329e2d against latest (739664c)

  🔍 Preview build  

5 files changed · ± 5 modified

± Modified

@rm-you
rm-you marked this pull request as ready for review November 12, 2026 07:51
@rm-you
rm-you force-pushed the fix/threadpool-stop-leftovers branch 4 times, most recently from d6cc705 to c1a87ea Compare November 14, 2026 03:41
Comment thread cheroot/test/test_server.py Resolved

@rm-you rm-you left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 5e85181 and c1a87ea, with the follow-up fixes kept as separate commits. Stop now handles late shrink requests and full queues; growth cannot escape shutdown, interrupted preparation can be retried, and restart is rejected until the previous stop finishes cleanup. #859 remains independent.

The three new regressions failed before the fixes and passed 50 repetitions each afterward. The complete local suite passes (237 passed, 3 existing expected failures), as do the pre-commit checks. I ran a local HTTP benchmark and a comparison with the main branch, and it completed almost 700k requests without errors or a material throughput regression.

@rm-you
rm-you force-pushed the fix/threadpool-stop-leftovers branch from c1a87ea to 634e7b7 Compare November 14, 2026 06:25
@rm-you rm-you changed the title Drop leftover shutdown requests when stopping a pool Make leftover shutdown requests harmless to a restarted pool Nov 14, 2026
@rm-you
rm-you force-pushed the fix/threadpool-stop-leftovers branch 4 times, most recently from 6d44fe5 to 7ce9e80 Compare November 14, 2026 13:28
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 <flux.adam@gmail.com>
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 <flux.adam@gmail.com>
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 <flux.adam@gmail.com>
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 <flux.adam@gmail.com>
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 <flux.adam@gmail.com>
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 <flux.adam@gmail.com>
@rm-you
rm-you force-pushed the fix/threadpool-stop-leftovers branch from 6684d7d to 0329e2d Compare November 15, 2026 13:04

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agentscan:automation-signals bot:chronographer:provided A mark meaning that a new change log entry is present within the patch.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ThreadPool.shrink() miscounts pending shutdowns, and a stopped pool can hang on restart

2 participants