Repository navigation
Conversation
Mixed activityActivity patterns show a mix of organic and automated signals. Evidence
Last 5 PRs:
This is an automated analysis by AgentScan |
d6337a6 to
1df9482
Compare
Codecov Report❌ Patch coverage is 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 |
|
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! |
|
I'm pretty sure the failed test is not related to this, maybe someone can re-run it? |
|
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 |
|
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-
left a comment
There was a problem hiding this comment.
Overall logic seems fine but I have reworded various descriptions to make them easier to understand.
|
I pushed one more commit, fe81ecd, which only adds a test: it stops the |
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>
|
One more small test-only commit, b25eaf2: the thread pool tests now use a general |
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>
b25eaf2 to
d641734
Compare
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>
d641734 to
4408b02
Compare
webknjaz
left a comment
There was a problem hiding this comment.
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.
|
@julianz- this needs a more in-depth review now with full approval if all's good. |
fd1f02d to
9ddaf0a
Compare
|
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. |
Understood. To make it easier, I split it. This PR now only fixes the |
@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. |
9ddaf0a to
c058dec
Compare
|
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 ( This replaces what I said above about |
|
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.
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). |
|
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. |
c058dec to
e5da0a6
Compare
julianz-
left a comment
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
🟡 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
| self._pending_shutdowns.append(None) | ||
| self._queue.put(_SHUTDOWNREQUEST) | ||
| # only once queued: an interrupted put() leaves nothing pending | ||
| self._pending_shutdowns.append(None) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
julianz-
left a comment
There was a problem hiding this comment.
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.
7fd1947 to
66c2d7a
Compare
rm-you
left a comment
There was a problem hiding this comment.
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.
| self._pending_shutdowns.append(None) | ||
| self._queue.put(_SHUTDOWNREQUEST) | ||
| # only once queued: an interrupted put() leaves nothing pending | ||
| self._pending_shutdowns.append(None) |
There was a problem hiding this comment.
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.
66c2d7a to
6fd7ea0
Compare
| # 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 |
There was a problem hiding this comment.
# If shrink() was interrupted, remove the ones we added to
# _retirements_due that never made it onto the queue.
There was a problem hiding this comment.
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.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>
bcee240 to
d46908a
Compare
| # 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 |
There was a problem hiding this comment.
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.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>
| # 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. |
There was a problem hiding this comment.
Two problems with this.
put()is atomic and so it either succeeds or fails. The issue isput()can succeed but then an interrupt preventsn_queuedfrom incrementing.- 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>

What kind of change does this PR introduce?
What do these changes do?
shrink()has three separate bugs in how it keeps track of the number of threads it should shut down: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 toidleand 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 keepsminwithout 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, soidleand 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.idlereads 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'sreadyflag, since before Python 3.13Thread.is_alive()can fail when two threads call it at once for a thread that is exiting.shrink(20)on 90 threads,min10shrink(40), thenshrink(80), on 50 threads,min10Both 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 toamountmore threads, counting those already shutting down as gone, asidledoes, and never belowmin, even if calls overlap or a thread exits for another reason. #204 madeshrink()subtract the shutdowns already scheduled fromamount, and madeidleleave them out too, so a caller that sizesamountfromidlehad 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'smaincallsshrink().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.
and description in grammatically correct, complete sentences
docs/) and inline docstrings reflect the changes(see good commit messages)
(can be done once the PR number is known; alternatively, you can
use a related issue number if one exists)
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 onmainhides. No test covers the lock thatshrink()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 atmin.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, andmain, 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.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()plusstart()took about 1.1 ms with all three.grow(20)andshrink(20)cycle took about 2.9 ms with both versions of the fix. Onmainit hangs on the bug fixed here.