Skip to content

Fix ThreadPool.shrink() accounting of pending shutdowns - #859

Open
rm-you wants to merge 3 commits into
cherrypy:mainfrom
rm-you:fix/threadpool-shrink-accounting
Open

rm-you wants to merge 3 commits into
cherrypy:mainfrom
rm-you:fix/threadpool-shrink-accounting

Conversation

@rm-you

@rm-you rm-you commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What kind of change does this PR introduce?

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

What do these changes do?

shrink() has three separate bugs in how it keeps track of the number of threads it should shut down:

  1. Requested shrinkage is wrongly reduced by anything that is pending from a previous call. A second shrink call that comes in before the first call has finished shutting down threads may be incorrectly ignored. For example, if two shrink(20) calls occur in quick succession, the second call may do nothing because the system immediately deducts the 20 pending shutdowns from the first before considering what to do with the second call.
  2. The code ignores pending shutdowns when checking against the minimum. This bug works in the opposite direction to bug 1 because a second shrink call can queue an excessive number of shutdowns, pushing the pool below the minimum. For example, shrink(40) followed by shrink(80) on a pool of 50 threads with a minimum of 10 can end up shutting down all 50.
  3. A thread is marked pending before its shutdown request is actually queued. If queue.put() gets interrupted while waiting for room, that leaves a phantom pending count with no real queued request behind it. An incorrect pending count gives incorrect results from calls to idle and throws off the accounting for new calls to shrink().

Review found two more ways for the count to go wrong: reaping dropped one pending shutdown for each dead thread, whatever killed it, and two calls at once could both spend the same threads. All of these come from one thing: the pending count had to match the shutdown requests in the queue exactly.

So the pool's own state now says how many retirements are due. This keeps the logic of the previous version (reserve under a lock before queueing, and decide under the same lock when a worker takes a request), but the pool, not the request, records whether a retirement is due. Naming follows julianz-'s reviews (_get_request(), n_removable, _RetirementRequest, _retirements_due, _decide_retirement()). shrink() reserves them under a lock and queues one retirement request for each. A request only wakes a worker. The worker asks the pool, under the same lock, whether a shutdown is still due and whether the pool keeps min without it. If not, it goes on serving. So a request that an interrupted call gave back, or one that outlived a thread that exited for another reason, does nothing. A thread that takes a request is marked as shutting down, so idle and later calls leave it out. This is the per-thread flag suggested in review, set when a thread takes a request, since the shared queue cannot pick the thread in advance. The pool keeps the retirement requests that are due. A call interrupted anywhere, before or while it queues, gives back only its own requests that it has not queued, by removing them, which does nothing for one that a worker already took; a worker skips a request that is no longer due. Reaping only removes dead threads; it never touches the retirements due. idle reads the threads and the retirements due under the same lock, so it stays exact while threads take their requests. Workers tell which threads still serve from each thread's ready flag, since before Python 3.13 Thread.is_alive() can fail when two threads call it at once for a thread that is exiting.

cheroot 11.1.2 this change
4 × shrink(20) on 90 threads, min 10 70 left 10 left
shrink(40), then shrink(80), on 50 threads, min 10 0 left, 30 requests queued 10 left, none queued

Both rows are for calls made before the threads they retire have exited.

Are there changes in behavior for the user?

shrink(amount) now retires up to amount more threads, counting those already shutting down as gone, as idle does, and never below min, even if calls overlap or a thread exits for another reason. #204 made shrink() subtract the shutdowns already scheduled from amount, and made idle leave them out too, so a caller that sizes amount from idle had them subtracted twice. Such a caller now gets what it asks for. One that subtracts pending shutdowns itself would now shrink more. Nothing in cheroot or CherryPy's main calls shrink().

stop() is unchanged here; #882 deals with stopping and restarting a pool.

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

It adds one lock, the set of retirement requests that are due and a retirement request class to ThreadPool, and one flag to each worker. The lock is never held while waiting on the queue. The tests order the races with events, not timing.

Related issue number

Part of #861.

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). The three-bug explanation above uses julianz-'s wording. Several regression tests build on ones written with OpenAI Codex for the previous version of this PR.

This PR is two commits: the fix, which takes in the follow-ups from three independent reviews, CI and julianz-'s first review (an interrupted call could give back another call's shutdown, or keep one due when interrupted right after reserving it; is_alive() from workers; and the retirement names), and julianz-'s wording for its comments.

Of the 14 new tests (17 cases), 13 cases fail on main. The other 4 cases (3 tests) cover cases raised in review (an unrelated thread exit, an interrupt after a request is queued, and reaping before a put returns), which bug 1 on main hides. No test covers the lock that shrink() reserves under on its own: it keeps two calls from reserving the same threads, which no test can set up on demand, and the check that a worker makes when it takes a request also keeps the pool at min.

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.

@agentscanapp

agentscanapp Bot commented Oct 19, 2026

Copy link
Copy Markdown

Mixed activity

Activity patterns show a mix of organic and automated signals.

View full analysis →

Evidence
  • Very high PR volume (daily): 38 PRs within a single 24-hour window

Last 5 PRs:

This is an automated analysis by AgentScan

@read-the-docs-community

read-the-docs-community Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 cheroot | 🛠️ Build #35914282 | 📁 Comparing e66de9e against latest (8402e55)

  🔍 Preview build  

5 files changed · ± 5 modified

± Modified

@rm-you
rm-you force-pushed the fix/threadpool-shrink-accounting branch from d6337a6 to 1df9482 Compare October 19, 2026 08:12
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided A mark meaning that a new change log entry is present within the patch. label Oct 19, 2026
@codecov

codecov Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #859      +/-   ##
==========================================
+ Coverage   75.99%   77.71%   +1.72%     
==========================================
  Files          41       41              
  Lines        4932     5291     +359     
  Branches      561      586      +25     
==========================================
+ Hits         3748     4112     +364     
+ Misses       1045     1037       -8     
- Partials      139      142       +3     

@rm-you

rm-you commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey, just dropping a quick note here since I just posted this and #858 with Claude, as I want to be clear that while Claude wrote most/all of the code here, there is a real human behind these driving and doing first-pass reviews, and these are bugs I've been tracking internally for quite a while.

We use cheroot to serve parts of an in-development RPC system in OpenStack's oslo.messaging project, and we trip over this periodically depending on deployment style. I will be tracking these and am happy to make adjustments based on feedback, or drop these PRs if there's a better approach from someone who knows the codebase better than I (and AI) do. Thanks!

@rm-you
rm-you marked this pull request as ready for review October 19, 2026 10:23
@rm-you

rm-you commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

I'm pretty sure the failed test is not related to this, maybe someone can re-run it?

@webknjaz

Copy link
Copy Markdown
Member

Hi, thanks for the PR. Can't promise timely reviews but maybe @julianz- will be able to spare a minute. Feel free to drop by our matrix. I'm sometimes more responsive there.

I've restarted the job, it seems like it hit GHA-level timeout while also having been marked as green.

It might be wise to tag people who looked at this and some surrounding modules last, just in case. cc @pR0Ps @itamarst

@webknjaz
webknjaz requested a review from julianz- October 21, 2026 14:41
@rm-you

rm-you commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, no worries. I have some workarounds on my side in my oslo.messaging patches, but obviously that's not ideal long term, and I figured someone else may have run into this.

@julianz- julianz- mentioned this pull request Oct 22, 2026
10 of 18 tasks

@julianz- julianz- left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Overall logic seems fine but I have reworded various descriptions to make them easier to understand.

Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/test/test_server.py Resolved
@rm-you

rm-you commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

I pushed one more commit, fe81ecd, which only adds a test: it stops the
pool while a shrink is still pending, then checks that nothing stays
queued and that the restarted pool reports its idle threads correctly.
Nothing else changed. Without the _pending_shutdowns.clear() line in
stop(), this new test is the only one that fails.

rm-you added a commit to rm-you/cheroot that referenced this pull request Oct 29, 2026
Define _wait_until() after the module's markers instead of among the
statistics tests. The thread pool tests of cherrypy#859 need the same helper
and add it, byte for byte, at the same place, so the two changes merge
into a single definition whichever lands first.

Assisted-By: Anthropic Claude Opus 5.5
Signed-off-by: Adam Harwell <flux.adam@gmail.com>
@rm-you

rm-you commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

One more small test-only commit, b25eaf2: the thread pool tests now use a general _wait_until() helper instead of _wait_for_live_threads(). #858 adds the same helper, byte for byte, at the same place in test_server.py, so whichever PR merges second rebases without a conflict and the file keeps one copy. The tests themselves are unchanged and still fail without the fix.

rm-you added a commit to rm-you/cheroot that referenced this pull request Nov 4, 2026
Define _wait_until() after the module's markers instead of among the
statistics tests. The thread pool tests of cherrypy#859 need the same helper
and add it, byte for byte, at the same place, so the two changes merge
into a single definition whichever lands first.

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-shrink-accounting branch from b25eaf2 to d641734 Compare November 4, 2026 03:34
rm-you added a commit to rm-you/cheroot that referenced this pull request Nov 4, 2026
Every HTTPServer registered its statistics in the process-wide
logging.statistics when it was constructed, and nothing removed them.
Their callbacks hold the server, so every server ever built stayed
alive with its gateway: stopped ones, ones whose prepare() failed to
bind, and ones that never started. A server is now registered only
while it serves, from prepare() to stop(), and clear_stats() replaces
its entry while it serves.

Every worker thread also left its entry in its server's Worker Threads
statistics when it exited, so a pool that grows and shrinks again kept
every thread it ever started. Each worker now registers with a small
collector that clear_stats() creates. On exit, the worker adds its
final counters to the collector's retired totals and removes its
record, so the server totals still count its work: requests, bytes
read and written, work time, and both throughputs, which remain the
sum of each worker's rate. One lock covers registering, retiring and
reading the totals, so a retiring worker is counted exactly once. A
worker retires into the collector it joined, so one that outlives
clear_stats() cannot bring the cleared counters back. A server whose
own clear_stats() creates no collector keeps no worker records, rather
than failing to start.

The tests define a general _wait_until() helper after the module's
markers. The thread pool tests of cherrypy#859 add the same helper, byte for
byte, at the same place, so the two changes merge into a single
definition whichever lands first.

Assisted-By: Anthropic Claude Opus 5.5
Assisted-By: OpenAI Codex (GPT-6)
Signed-off-by: Adam Harwell <flux.adam@gmail.com>
@rm-you
rm-you force-pushed the fix/threadpool-shrink-accounting branch from d641734 to 4408b02 Compare November 4, 2026 04:26

@webknjaz webknjaz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm not quite comfortable with this part of the code base so I'm going to need more people to give opinions. And maybe run some agentic review against this too.

Maybe @julianz- / @jaraco / @the-allanc / @cyraxjoe could spare a minute.

Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
@webknjaz

Copy link
Copy Markdown
Member

@julianz- this needs a more in-depth review now with full approval if all's good.

@webknjaz
webknjaz requested a max review from Copilot November 11, 2026 22:35
@rm-you
rm-you force-pushed the fix/threadpool-shrink-accounting branch 2 times, most recently from fd1f02d to 9ddaf0a Compare November 12, 2026 08:35
@julianz-

Copy link
Copy Markdown
Member

What's the deal with this PR? This and #858 have somehow grown from single fixes into one 5-deep interdependent behemoth (#880→#858→#881→#859→#882) in the space of a few hours. That's hard to review: GitHub's diff view for each PR now shows the cumulative change of everything below it, not just its own piece, and a change requested anywhere in the middle means rebasing everything above it.

Not sure what to make of this. Getting a bit out of hand.

@rm-you

rm-you commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

I'm not quite comfortable with this part of the code base so I'm going to need more people to give opinions. And maybe run some agentic review against this too.

Understood. To make it easier, I split it. This PR now only fixes the shrink() counting, and the stop() part is #882. The stack is #880 → #858 → #881 → #859 → #882, and each description links a diff of only that PR's own commit. Another AI agent (mine still, but a different model) reviewed the whole stack before this push, and I fixed what it found, but I'm sure there will be other stuff, definitely throw your agents at it.

@rm-you

rm-you commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

What's the deal with this PR? This and #858 have somehow grown from single fixes into one 5-deep interdependent behemoth (#880→#858→#881→#859→#882) in the space of a few hours. That's hard to review: GitHub's diff view for each PR now shows the cumulative change of everything below it, not just its own piece, and a change requested anywhere in the middle means rebasing everything above it.

Not sure what to make of this. Getting a bit out of hand.

@julianz- Did you see my comments in Matrix chat? There's fixes that need to be made that either had nothing to do with my changes, or were pre-existing, and I originally tried to just throw them in the other PRs to keep things simpler, but reviewers didn't like it and I honestly agreed it was messy, so I split it out. Github sucks at PR Stacks (their new Stack feature is good but doesn't work across forks) so the note at the top with the "changes for this PR only" links is the best I could think to do. It sucks, I know it sucks, I'm not sure a way around it.

@rm-you
rm-you force-pushed the fix/threadpool-shrink-accounting branch from 9ddaf0a to c058dec Compare November 12, 2026 10:13
@rm-you

rm-you commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

I split the stack in two, since the statistics and thread pool fixes don't depend on each other:

The library code is unchanged. The tests here use three helpers that #858 and #881 also add, so this stack carries identical copies at the same places (_wait_until(), _make_server() and _make_wsgi_server()), plus the same pytest inventory line in docs/conf.py. Git keeps one copy once both stacks are in. The imports at the top of test_server.py sit next to each other, though, so whichever stack merges second needs a small rebase. I'll do it when that happens.

This replaces what I said above about _wait_until() being defined once, in #881.

@julianz-

Copy link
Copy Markdown
Member

Can i suggest the following for the opening of your PR description? Also I am not sure you need to mention any of other stacked PRs here as this PR stands perfectly well on its own. #882 can mention this PR if you like but this one is totally fine on it own no? I am trying to make this PR easy to understand without having to worry about any other changes or dependencies.

shrink() has three separate bugs in how it keeps track of the number of threads it should shut down:

  1. Requested shrinkage is wrongly reduced by anything that is pending from a previous call. A second shrink call that comes in before the first call has finished shutting down threads may be incorrectly ignored. For example, if two shrink(20) calls occur in quick succession, the second call may do nothing because the system immediately deducts the 20 pending shutdowns from the first before considering what to do with the second call.
  2. The code ignores pending shutdowns when checking against the minimum. This bug works in the opposite direction to bug 1 because a second shrink call can queue an excessive number of shutdowns, pushing the pool below the minimum. For example, shrink(40) followed by shrink(80) on a pool of 50 threads with a minimum of 10 can end up shutting down all 50.
  3. A thread is marked pending before its shutdown request is actually queued. If queue.put() gets interrupted while waiting for room, that leaves a phantom pending count with no real queued request behind it. An incorrect pending count gives incorrect results from calls to idle and throws off the accounting for new calls to shrink().

Fixed: stopped subtracting pending shutdowns from the requested amount (1); started subtracting them when counting threads available above the minimum (2); moved the pending-mark to after the request is successfully queued, not before (3).

@rm-you

rm-you commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Yeah you're right, that reads much better. There's not really any point in cross-referencing them anymore. I've put your text at the start of the description, kept the before/after table, and dropped the mentions of the other PRs.

@rm-you
rm-you force-pushed the fix/threadpool-shrink-accounting branch from c058dec to e5da0a6 Compare November 13, 2026 02:39

@julianz- julianz- left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I worry that _pending_shutdowns is just a bare count (a deque of Nones), with no link to which thread it's about. _clear_dead_threads() has to guess by popping one entry per dead thread, and guesses incorrectly when a thread dies for an unrelated reason.

Thoughts?

Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/test/test_server.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Shutdown enqueueing and pending-count bookkeeping are not exception-safe or synchronized with reaping, allowing interrupted or overlapping shrink calls to retire workers below the minimum or suppress later shrinkage.

1 open issue
2 resolved since last review

Review effort: Max

Comment thread cheroot/workers/threadpool.py Outdated
self._pending_shutdowns.append(None)
self._queue.put(_SHUTDOWNREQUEST)
# only once queued: an interrupted put() leaves nothing pending
self._pending_shutdowns.append(None)

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.

Fixed in 7fd1947. Reservations are recorded before enqueueing, and an interrupted enqueue cancels only unclaimed requests; already claimed ones stay accounted for until their worker exits. Added regressions for interruption after insertion, both before and after worker claim, and reaping before put() returns.

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.

In the rework, a request only wakes a worker; the count is what counts. An interrupted put() gives its shutdown back, and if the request did get in, the worker that takes it finds nothing due and goes on. Reaping never changes the count. test_threadpool_interrupt_after_enqueue_keeps_minimum, test_threadpool_unneeded_shrink_request_keeps_threads and test_threadpool_reap_before_enqueue_returns_keeps_idle_count cover these.

Comment thread cheroot/test/test_server.py Resolved

@julianz- julianz- left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The logic looks good for solving the race condition and keeping track of the correct number of threads. Some of your wording though I found confusing so have made suggestions for changes.

Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
@rm-you
rm-you force-pushed the fix/threadpool-shrink-accounting branch from 7fd1947 to 66c2d7a Compare November 14, 2026 06:25

@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.

Thanks for the review, @julianz-, I just wish I'd managed to get the next version posted before you did that lol
So I've reworked this, and tried keeping as much as possible of the logic you checked: shutdowns are reserved under a lock before they're queued, and a worker decides under the same lock when it takes a request. What changed is how they're tracked... The pool keeps a count of the shutdowns due instead of request objects that workers claim or cancel. A thread is marked as shutting down when it takes a request, which is your per-thread flag idea. A request that's no longer needed now just does nothing.
The reason is #882. With request objects, stopping and restarting needed a queue subclass, a second lock and a stopping flag. With a count, it needs only a run number. Your naming suggestions are hopefully all taken into account (_get_request(), n_removable and the comment). The tests from the previous version still pass, plus new ones for the cases they didn't reach. A local benchmark shows no throughput change.

Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/workers/threadpool.py Outdated
self._pending_shutdowns.append(None)
self._queue.put(_SHUTDOWNREQUEST)
# only once queued: an interrupted put() leaves nothing pending
self._pending_shutdowns.append(None)

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.

In the rework, a request only wakes a worker; the count is what counts. An interrupted put() gives its shutdown back, and if the request did get in, the worker that takes it finds nothing due and goes on. Reaping never changes the count. test_threadpool_interrupt_after_enqueue_keeps_minimum, test_threadpool_unneeded_shrink_request_keeps_threads and test_threadpool_reap_before_enqueue_returns_keeps_idle_count cover these.

Comment thread cheroot/test/test_server.py Resolved
@rm-you
rm-you force-pushed the fix/threadpool-shrink-accounting branch from 66c2d7a to 6fd7ea0 Compare November 14, 2026 06:50
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Outdated
Comment on lines +398 to +400
# If this was interrupted, such as while put() waited for room,
# give back the shutdowns of its requests that are not queued,
# or that got in as put() was interrupted: a worker skips them

@julianz- julianz- Nov 14, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

# If shrink() was interrupted, remove the ones we added to
# _retirements_due that never made it onto the queue.

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.

Done, with one addition. put() can be interrupted after it has already added the request to the queue. That request isn't counted as queued, so we remove it from _retirements_due too, and the thread that takes it skips it, as it's no longer due. test_threadpool_interrupt_after_enqueue_keeps_minimum covers that case. The comment now reads:

# 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.

Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
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>
@rm-you
rm-you force-pushed the fix/threadpool-shrink-accounting branch from bcee240 to d46908a Compare November 15, 2026 05:21

@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.

Thanks @julianz-. I've taken all nine: the retirement names (_RetirementRequest, _retirements_due, _decide_retirement(), retirement_requests) and your comment wording, with one addition to the interrupt comment. I've squashed this PR into one commit with them, and #882 is rebased onto it.

Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Outdated
Comment on lines +398 to +400
# If this was interrupted, such as while put() waited for room,
# give back the shutdowns of its requests that are not queued,
# or that got in as put() was interrupted: a worker skips them

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.

Done, with one addition. put() can be interrupted after it has already added the request to the queue. That request isn't counted as queued, so we remove it from _retirements_due too, and the thread that takes it skips it, as it's no longer due. test_threadpool_interrupt_after_enqueue_keeps_minimum covers that case. The comment now reads:

# 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.

Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/test/test_server.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/workers/threadpool.py Resolved
Comment thread cheroot/test/test_server.py Resolved
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>
Comment thread cheroot/workers/threadpool.py Outdated
Comment on lines +402 to +404
# 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.

@julianz- julianz- Nov 15, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Two problems with this.

  1. put()is atomic and so it either succeeds or fails. The issue is put() can succeed but then an interrupt prevents n_queued from incrementing.
  2. I really don't like the use of back to back pronouns in phrases like "a thread that takes one skips it" because I am left wondering one what and skips what? These things are not immediately obvious to readers struggling to understand this code.

how about:

# 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.

I know this is now quite long - but I find it helpful for understanding what is happening.

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.

Done, switched to your wording.
One note on 1): I originally assumed that too, but Claude is insistent that "put() can also raise after the request is in the queue, since an interrupt can still arrive in its last steps, after _put()" and does appear to be right, technically? Anyway, I'm fine with what you wrote.

@julianz- julianz- Nov 16, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Interesting about put(). Agree looks like it's not truly atomic but the comment still stands as it's agnostic about where inside put() or between put() and the next line the interrupt landed. Good to know though.

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 <flux.adam@gmail.com>

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:mixed-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.

5 participants