GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — SingleThreadEventExecutor: do not start threads when shutting down never-used executors by arimu1 · Pull Request #17183 · netty/netty ConversationMotivation:
EventLoopGroup group = new MultiThreadIoEventLoopGroup(300, NioIoHandler.newFactory()); group.shutdownGracefully(); // previously started 300 threads See #17135. Modification: In If work is present (or the processing lock is already held by a worker), Result: Fixes #17135.
Tested:
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
Member
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
arimu1
force-pushed
the
fix/17135-shutdown-unstarted-threads
branch
from
f4286c9 to
d515a51
Compare
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
arimu1
added a commit
to arimu1/netty
that referenced
this pull request
Never-started executors with a non-zero quiet period stay SHUTTING_DOWN without starting a worker, schedule a GlobalEventExecutor timer to terminate when quiet elapses with no work, and start a worker only if execute() arrives during the quiet period. MultithreadEventExecutorGroup no longer forces quietPeriod=0 on unused children. Addresses mega12345mega's design feedback on netty#17183 / netty#17135. Signed-off-by: arimu1 <[email protected]>
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
Member
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
normanmaurer
reviewed
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. imho all of this can be removed... and so there needs to be no changes at all to this class
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
Member
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
arimu1
added a commit
to arimu1/netty
that referenced
this pull request
SingleThreadEventExecutor.tryTerminateIfNeverStarted() calls cleanup() off-thread before run()/initialize(). IoUring rings are created disabled; destroy()'s submission path needs enable() first, which caused io_uring_enter error -77 in IoUringEventLoopTest.shutdownBeforeStart. Skip submission-based teardown when initialize() never ran; release buffer rings and close the ring directly instead. Fixes CI failures reported on netty#17183. Signed-off-by: arimu1 <[email protected]> Co-authored-by: Cursor <[email protected]>
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
arimu1
added a commit
to arimu1/netty
that referenced
this pull request
SingleThreadEventExecutor.tryTerminateIfNeverStarted() calls cleanup() off-thread before run()/initialize(). IoUring rings are created disabled; destroy()'s submission path needs enable() first, which caused io_uring_enter error -77 in IoUringEventLoopTest.shutdownBeforeStart. Skip submission-based teardown when initialize() never ran; release buffer rings and close the ring directly instead. Fixes CI failures reported on netty#17183. Signed-off-by: arimu1 <[email protected]>
arimu1
force-pushed
the
fix/17135-shutdown-unstarted-threads
branch
from
32772f7 to
2bb0c8a
Compare
2 tasks
chrisvest
requested changes
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This code introduces a problem where suspension and task submission can both race, and hit an unfortunate interleaving where the existing executor thread suspends, but the task submission moves the state to I… tried creating a test for this, which seems to catch the scenario (and pass on base 4.2), but I don't love how it looks. Maybe it can be written in a different/simpler way. @Test @Timeout(value = 10, unit = TimeUnit.SECONDS) public void testExecuteRacingSuspensionDoesNotStrandExecutor() throws Exception { final AtomicBoolean armed = new AtomicBoolean(); final AtomicInteger armedCanSuspendCalls = new AtomicInteger(); final CountDownLatch executorThreadAtReengage = new CountDownLatch(1); final CountDownLatch externalDone = new CountDownLatch(1); final SingleThreadEventExecutor executor = new SingleThreadEventExecutor( null, new DefaultThreadFactory("suspend-race"), false, true, Integer.MAX_VALUE, RejectedExecutionHandlers.reject()) { @Override protected void run() { for (;;) { if (confirmShutdown()) { return; } Runnable task = takeTask(); if (task != null) { task.run(); } if (isSuspended()) { // Suspension requested: return so the base class can suspend this thread. // Note: run() intentionally does not call canSuspend() so that the only // canSuspend(int) calls after arming are the base class' two checks. return; } } } @Override protected boolean canSuspend(int state) { if (armed.get() && armedCanSuspendCalls.incrementAndGet() == 2) { // Second armed call is the re-engage check canSuspend(ST_SUSPENDED): at this // point the executor thread has already CAS'd the state to ST_SUSPENDED but // has not yet reset the start gate. Let an external execute() race in now. executorThreadAtReengage.countDown(); boolean interrupted = false; while (externalDone.getCount() > 0) { try { externalDone.await(); } catch (InterruptedException e) { interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } } return super.canSuspend(state); } @Override protected void wakeup(boolean inEventLoop) { interruptThread(); } }; // Start the executor thread and make sure it is parked in takeTask(). LatchTask started = new LatchTask(); executor.execute(started); started.await(); // Arm the interception, then request suspension, then wait for executor to hit suspension point. armed.set(true); assertTrue(executor.trySuspend()); assertTrue(executorThreadAtReengage.await(5, TimeUnit.SECONDS)); // Racy external submission: CASing state from ST_SUSPENDED to ST_STARTED. // Despite the race, this *should* punt the executor thread back to started *or* start a new executor // thread (which will wait for the existing one to completely finish its suspension). LatchTask raced = new LatchTask(); executor.execute(raced); // Let the old executor thread finish suspending. externalDone.countDown(); // The expected behavior is that the raced task must eventually run, and not leave the executor stuck // in ST_STARTED state with no actual thread started. assertTrue(raced.await(10, TimeUnit.SECONDS)); executor.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).syncUninterruptibly(); }
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Move this declaration up with the other fields.
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactionsWhen shutdownGracefully() runs on an executor that was never started and has no pending work, terminate without creating a worker thread. MultithreadEventExecutorGroup walks every child on shutdown; without this path, constructing a group of N and shutting it down unused spun up all N threads only to exit immediately (netty#17135). Local SingleThreadEventExecutorTest is 18/18 green (JDK 21). CI failures (TestLens / KQueue / Nio) showed AssertionError in SingleThreadIoEventLoop.cleanup() when tryTerminateIfNeverStarted called cleanup() off the event-loop thread. - Bind current thread for cleanup so constructor-created IoHandler is destroyed - Only fast-path when quietPeriod == 0 (honor graceful quiet period otherwise) - MultithreadEventExecutorGroup uses quietPeriod=0 for never-started children so default shutdownGracefully() no longer starts unused workers (netty#17135) Never-started MultithreadEventExecutorGroup children still force quietPeriod=0 so unused workers are not started. Document that late execute after group.shutdownGracefully(nonZero) is rejected on those children, and add a regression test covering that contract. Never-started executors with a non-zero quiet period stay SHUTTING_DOWN without starting a worker, schedule a GlobalEventExecutor timer to terminate when quiet elapses with no work, and start a worker only if execute() arrives during the quiet period. MultithreadEventExecutorGroup no longer forces quietPeriod=0 on unused children. Addresses mega12345mega's design feedback on netty#17183 / netty#17135. Signed-off-by: arimu1 <[email protected]> SingleThreadEventExecutor.tryTerminateIfNeverStarted() calls cleanup() off-thread before run()/initialize(). IoUring rings are created disabled; destroy()'s submission path needs enable() first, which caused io_uring_enter error -77 in IoUringEventLoopTest.shutdownBeforeStart. Skip submission-based teardown when initialize() never ran; release buffer rings and close the ring directly instead. Fixes CI failures reported on netty#17183. Signed-off-by: arimu1 <[email protected]> …d isNeverStarted Norman noted the group-level comment-only change was unnecessary. Zero-diff that file vs 4.2 and delete the unused never-started helper. Signed-off-by: arimu1 <[email protected]> When execute() CASes ST_SUSPENDED to ST_STARTED while the event-loop thread is still winding down, re-engage that thread or wake it so tasks are not left on a started executor with no worker. Includes regression test from review and moves neverStartedQuietPeriodTask with other fields.
arimu1
force-pushed
the
fix/17135-shutdown-unstarted-threads
branch
from
4936f8c to
3373ed5
Compare
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. …work arrived After canSuspend(ST_SUSPENDED) returns true, execute() may still CAS to ST_STARTED while threadStartIssued is held during removeAll(). Recheck state after clearing the start gate and issue a replacement worker when needed. Adds regression test for that window and restores chrisvest's test comments for the re-engage interleaving.
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
Member
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
Contributor
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
normanmaurer
added a commit
that referenced
this pull request
Motivation: Since #15766, `trySuspend()` moves an executor that was never started directly from `ST_NOT_STARTED` to `ST_SUSPENDED`. `startThread()` reads the state once and then does a single CAS from that value to `ST_STARTED`: ```java int currentState = state; if (currentState == ST_NOT_STARTED || currentState == ST_SUSPENDED) { if (STATE_UPDATER.compareAndSet(this, currentState, ST_STARTED)) { ``` If `trySuspend()` runs between the read and the CAS, the CAS fails and `startThread()` returns without starting a thread. The task that `execute()` just added then sits in the queue of an executor that reports `isSuspended() == true` and has no thread. It only runs if something else is submitted later. `AutoScalingEventExecutorChooserFactory` can hit this: its monitor calls `trySuspend()` on idle executors that were never started, while `next()` may still hand the same executor out. A `Channel` registration on such an event loop never completes, and because the loop is no longer in the active set, nothing else is likely to wake it. Modification: Re-read the state and retry the CAS in `startThread()` while the state is still `ST_NOT_STARTED` or `ST_SUSPENDED` (the `if` becomes a `while`, plus a `break` after a successful start). The loop only retries when another thread changed the state between the read and the CAS, so it cannot spin: each extra round needs a new state change by someone else. It can take more than two rounds, though. For example, the CAS loses to `trySuspend()` (`ST_NOT_STARTED` to `ST_SUSPENDED`), then another thread's `startThread()` wins, its `doStartThread()` fails and it resets the state to `ST_NOT_STARTED`, and then this thread retries again. Any state other than `ST_NOT_STARTED` or `ST_SUSPENDED` means another thread started the executor, the old thread re-engaged, or the executor is shutting down, and each of those already takes care of the queued task. The retry may deliberately un-suspend an executor that `trySuspend()` has just suspended. That is the same thing `execute()` already does for an executor that is suspended, and the code comment at the retry says so. Add `SingleThreadEventExecutorTest.testExecuteRacingTrySuspendWhenExecutorIsNotStarted`. The race cannot be forced deterministically because there is no hook between the state read and the CAS, so the test repeats `execute()` against a concurrent `trySuspend()` on fresh executors 10000 times. The executors use an `Executor` that only counts start requests, so no threads are created and the check (exactly one start request per `execute()`) is exact. It takes about 0.1s. The test is regression-sensitive, not deterministic. Without the fix it needs the two threads to actually run in parallel and hit the window between the read and the CAS, so it may pass on machines with only 1 or 2 CPUs. With the fix it cannot fail falsely: every interleaving leads to exactly one start request. Result: A task added by `execute()` always gets a thread, even if it races with `trySuspend()`. This regressed in #15766. Testing: - Without the fix the new test failed in every run on a 12-CPU machine, typically within the first 20 to 140 iterations, for example: `AssertionFailedError: iteration 69 (isSuspended=true) ==> expected: <1> but was: <0>` As said above, it may pass without the fix on machines with 1 or 2 CPUs. - With the fix: `SingleThreadEventExecutorTest` 16 tests, 0 failures; `common` module 1449 tests, 0 failures, 19 skipped; checkstyle passes. - Standalone harnesses against the real classes: `execute()` racing `trySuspend()` stranded the task in 5445 of 300000 iterations before the fix and 0 of 300000 after. `SingleThreadIoEventLoop.register(channel)` on NIO racing `trySuspend()` hung 39 of 4000 registrations before and 0 of 3000 after. Interaction with open PRs: - #17601 (port of #17589) changes the post-`run()` decision in `doStartThread()`, a different code path (a running thread that is suspending). The two merge cleanly, and `SingleThreadEventExecutorTest` passes with both (17 tests). The model below was checked with both fixes applied. - #17183 and #15813 also edit `startThread()` and conflict textually, since this change turns the `if` into a `while`. Their extra `else if` branch moves after the loop as a plain `if` on the last observed state. With that resolution the tests pass for this change with #17183 (23 tests) and with #15813 (`SingleThreadEventExecutorTest` and `AutoScalingEventExecutorChooserFactoryTest`, 24 tests). This was found with a TLA+ model of the executor state machine (liveness property "an accepted task eventually runs" violated) and reproduced with the real classes. With the retry, the model passes `MutualExclusion`, `RunningHasThread` and `TaskRuns`/`TaskResolved`. It was checked alone and together with the #17589 fix (where it also passes `NoSpuriousShutdown`), with 2 submitters, up to 2 `trySuspend()` calls, graceful shutdown and scheduled-task cancellation, starting from both `ST_NOT_STARTED` and `ST_STARTED`, up to 1.44M distinct states. Co-authored-by: Norman Maurer <[email protected]>
normanmaurer
added a commit
that referenced
this pull request
…hread() (#17654) Auto-port of #17608 to 5.0 Cherry-picked commit: c4e7d1e --- Motivation: Since #15766, `trySuspend()` moves an executor that was never started directly from `ST_NOT_STARTED` to `ST_SUSPENDED`. `startThread()` reads the state once and then does a single CAS from that value to `ST_STARTED`: ```java int currentState = state; if (currentState == ST_NOT_STARTED || currentState == ST_SUSPENDED) { if (STATE_UPDATER.compareAndSet(this, currentState, ST_STARTED)) { ``` If `trySuspend()` runs between the read and the CAS, the CAS fails and `startThread()` returns without starting a thread. The task that `execute()` just added then sits in the queue of an executor that reports `isSuspended() == true` and has no thread. It only runs if something else is submitted later. `AutoScalingEventExecutorChooserFactory` can hit this: its monitor calls `trySuspend()` on idle executors that were never started, while `next()` may still hand the same executor out. A `Channel` registration on such an event loop never completes, and because the loop is no longer in the active set, nothing else is likely to wake it. Modification: Re-read the state and retry the CAS in `startThread()` while the state is still `ST_NOT_STARTED` or `ST_SUSPENDED` (the `if` becomes a `while`, plus a `break` after a successful start). The loop only retries when another thread changed the state between the read and the CAS, so it cannot spin: each extra round needs a new state change by someone else. It can take more than two rounds, though. For example, the CAS loses to `trySuspend()` (`ST_NOT_STARTED` to `ST_SUSPENDED`), then another thread's `startThread()` wins, its `doStartThread()` fails and it resets the state to `ST_NOT_STARTED`, and then this thread retries again. Any state other than `ST_NOT_STARTED` or `ST_SUSPENDED` means another thread started the executor, the old thread re-engaged, or the executor is shutting down, and each of those already takes care of the queued task. The retry may deliberately un-suspend an executor that `trySuspend()` has just suspended. That is the same thing `execute()` already does for an executor that is suspended, and the code comment at the retry says so. Add `SingleThreadEventExecutorTest.testExecuteRacingTrySuspendWhenExecutorIsNotStarted`. The race cannot be forced deterministically because there is no hook between the state read and the CAS, so the test repeats `execute()` against a concurrent `trySuspend()` on fresh executors 10000 times. The executors use an `Executor` that only counts start requests, so no threads are created and the check (exactly one start request per `execute()`) is exact. It takes about 0.1s. The test is regression-sensitive, not deterministic. Without the fix it needs the two threads to actually run in parallel and hit the window between the read and the CAS, so it may pass on machines with only 1 or 2 CPUs. With the fix it cannot fail falsely: every interleaving leads to exactly one start request. Result: A task added by `execute()` always gets a thread, even if it races with `trySuspend()`. This regressed in #15766. Testing: - Without the fix the new test failed in every run on a 12-CPU machine, typically within the first 20 to 140 iterations, for example: `AssertionFailedError: iteration 69 (isSuspended=true) ==> expected: <1> but was: <0>` As said above, it may pass without the fix on machines with 1 or 2 CPUs. - With the fix: `SingleThreadEventExecutorTest` 16 tests, 0 failures; `common` module 1449 tests, 0 failures, 19 skipped; checkstyle passes. - Standalone harnesses against the real classes: `execute()` racing `trySuspend()` stranded the task in 5445 of 300000 iterations before the fix and 0 of 300000 after. `SingleThreadIoEventLoop.register(channel)` on NIO racing `trySuspend()` hung 39 of 4000 registrations before and 0 of 3000 after. Interaction with open PRs: - #17601 (port of #17589) changes the post-`run()` decision in `doStartThread()`, a different code path (a running thread that is suspending). The two merge cleanly, and `SingleThreadEventExecutorTest` passes with both (17 tests). The model below was checked with both fixes applied. - #17183 and #15813 also edit `startThread()` and conflict textually, since this change turns the `if` into a `while`. Their extra `else if` branch moves after the loop as a plain `if` on the last observed state. With that resolution the tests pass for this change with #17183 (23 tests) and with #15813 (`SingleThreadEventExecutorTest` and `AutoScalingEventExecutorChooserFactoryTest`, 24 tests). This was found with a TLA+ model of the executor state machine (liveness property "an accepted task eventually runs" violated) and reproduced with the real classes. With the retry, the model passes `MutualExclusion`, `RunningHasThread` and `TaskRuns`/`TaskResolved`. It was checked alone and together with the #17589 fix (where it also passes `NoSpuriousShutdown`), with 2 submitters, up to 2 `trySuspend()` calls, graceful shutdown and scheduled-task cancellation, starting from both `ST_NOT_STARTED` and `ST_STARTED`, up to 1.44M distinct states. Co-authored-by: allthingssecurity <[email protected]> Co-authored-by: Norman Maurer <[email protected]>
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I ran the executor tests and a race harness against this PR: head A task accepted by
The terminating thread then does the CAS, runs Once the lock is released, the worker takes it and enters
The comment at Deterministic reproducer (run on this PR merged with 4.2, so the line number in the trace comes from that merge). A On 4.2 this window does not exist: the executor is shut down by its own worker, and the late Without hooks. Each iteration runs
Possible direction. The never-started termination and the
Merge conflict with #17608. #17608 (merged yesterday) turned the
With that resolution these all pass:
The race above is unchanged after the merge (3 lost in 30,000). Claude Code on behalf of allthingssecurity
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. An Claude Code on behalf of allthingssecurity
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This branch can issue a worker after Claude Code on behalf of allthingssecurity
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The lock only protects against a worker that already holds it. A worker issued while this method runs waits on Claude Code on behalf of allthingssecurity
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactionsKeep the netty#17608 startThread retry loop, and run the never-started SHUTTING_DOWN worker start only after that loop. …nation tryTerminateIfNeverStarted() checked the queue and then jumped to TERMINATED while the executor was still SHUTTING_DOWN, so a concurrent execute() could enqueue a task and start a worker that ran after cleanup(). Publish SHUTDOWN before the last emptiness check and hold the start gate so the task is rejected or a worker drains it. Signed-off-by: arimu1 <[email protected]>
Author
All reactions
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page.
|
There was an error while loading. Please reload this page.
🚨 TestLens detected 2 failed tests 🚨Test SummaryTip Inspect all details with the TestLens CLI: Build PR / linux-x86_64-java11-boringssl build > Netty/Handler/Ssl/Ocsp
Build PR / macos-aarch64-java11-boringssl build > Netty/Transport/Native/KQueue
🏷️ Commit: 378d158 Test FailuresOcspServerCertificateValidatorTest > connectUsingHttpAndValidateCertificateUsingOcspTest() (Netty/Handler/Ssl/Ocsp in Build PR / linux-x86_64-java11-boringssl build)
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendDirectByteBuf(TestInfo) (Netty/Transport/Native/KQueue in Build PR / macos-aarch64-java11-boringssl build)Rerun ControlsSelect tests to mute in this pull request:
Reuse successful test results:
Click the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
These changes are looking increasingly complicated and fragile, so I'm starting to think that either the approach is wrong, or the juice might not be worth the squeeze. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
I agree with @chrisvest here |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Closing this |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
Shutting down MultiThreadIoEventLoopGroup starts all unstarted threads
There was an error while loading. Please reload this page.