Skip to content

Update state in SingleThreadEventExecutor from SUSPENDING to STARTED on new work - #15813

Open
isaacrivriv wants to merge 6 commits into
netty:4.2from
isaacrivriv:15809-fix-suspendingThread-not-started
Open

isaacrivriv wants to merge 6 commits into
netty:4.2from
isaacrivriv:15809-fix-suspendingThread-not-started

Conversation

@isaacrivriv

Copy link
Copy Markdown
Contributor

Added changes to fix suspending threads that should be re-activated when new work is added but are not. Added test to verify state properly updates and auto scaler can properly scale down the executors.

Motivation:

Discovered while working with dynamic scaling that state is not properly updated from ST_SUSPENDING when new work is added for an executor awaiting suspension.

Modification:

Updated the startThread method in the SingleThreadEventExecutor class to handle the suspending state and switch to started if so.

Result:

Fixes #15809

@isaacrivriv

Copy link
Copy Markdown
Contributor Author

Two follow-ups I have on this PR to check my understanding

  1. I noticed that on the tests for SingleThreadEventExecutor the implementations add a check in the run method if the executor canSuspend to stop working but the DefaultEventExecutor run method doesn't have that check. Just runs until it confirms shutdown. Is this normal/expected? Would it affect anything with state management given that the thread updates the state after the run method finishes?

    protected void run() {
    for (;;) {
    Runnable task = takeTask();
    if (task != null) {
    runTask(task);
    updateLastExecutionTime();
    }
    if (confirmShutdown()) {
    break;
    }
    }

  2. I also noticed that in the same class, the ensureThreadStarted method (called from shutdown0()) has a similar behavior of checking if the executor is started/suspended. Should a similar change go there to move the state to started if in suspending?

    private boolean ensureThreadStarted(int oldState) {
    if (oldState == ST_NOT_STARTED || oldState == ST_SUSPENDED) {
    try {
    doStartThread();
    } catch (Throwable cause) {
    STATE_UPDATER.set(this, ST_TERMINATED);
    terminationFuture.tryFailure(cause);
    if (!(cause instanceof Exception)) {
    // Also rethrow as it may be an OOME for example
    PlatformDependent.throwException(cause);
    }
    return true;
    }
    }
    return false;
    }

@isaacrivriv
isaacrivriv marked this pull request as ready for review October 29, 2025 19:36
@franz1981

Copy link
Copy Markdown
Contributor

@georgebanasios

@isaacrivriv

Copy link
Copy Markdown
Contributor Author

Ping to see if we can get this reviewed and possibly merged in...

@normanmaurer

Copy link
Copy Markdown
Member

@georgebanasios ping

@georgebanasios

Copy link
Copy Markdown
Contributor

Logically I'd say it makes sense.
Also I see this test failed: MultiThreadIoEventLoopGroupTest.testScalingWithIoRegistrationLifecycle:169->waitForSuspension:248 Timed out waiting for 2 executor(s) to suspend. which I don't remember it being flaky.

@normanmaurer

Copy link
Copy Markdown
Member

@isaacrivriv can you check ^^?

@isaacrivriv

isaacrivriv commented Nov 10, 2025 •

Copy link
Copy Markdown
Contributor Author

After making the changes I ran the common tests locally and saw no failures. With the mentioned failure, I have ran the transport tests locally and they all pass too... I don't think I have access to see what were the specific failures (or maybe I don't know where to look for them?) that happened in (I'm assuming) the GH actions build? If anyone can share more details I can take a deeper look to see what could be the issue

I realized where the test output was. I'm debugging things locally but I can't seem to be able to reproduce the issue. Can we re-run the test and see if it continues to reproduce?
Was able to reproduce after a many tries and config changes to make it more common. I'm working on identifying the root cause and providing a solution.

@isaacrivriv

Copy link
Copy Markdown
Contributor Author

Funny thing is the issue was pretty much what I mentioned in the comment here. Seems like a race condition where the loop entered but a context switch happened and the thread stopped. On return, the state switched to started but it was already suspended so it wasn't running. Pushed a fix that should help with this.

@franz1981 franz1981 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

@franz1981 franz1981 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I still see last test run to reports:

Error:  Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 4.871 s <<< FAILURE! -- in io.netty.channel.MultiThreadIoEventLoopGroupTest
Error:  io.netty.channel.MultiThreadIoEventLoopGroupTest.testScalingWithIoRegistrationLifecycle -- Time elapsed: 2.861 s <<< FAILURE!
org.opentest4j.AssertionFailedError: Timed out waiting for 2 executor(s) to suspend.
	at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:38)
	at org.junit.jupiter.api.Assertions.fail(Assertions.java:138)
	at io.netty.channel.MultiThreadIoEventLoopGroupTest.waitForSuspension(MultiThreadIoEventLoopGroupTest.java:248)
	at io.netty.channel.MultiThreadIoEventLoopGroupTest.testScalingWithIoRegistrationLifecycle(MultiThreadIoEventLoopGroupTest.java:169)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)

the CI has pretty cheap machines in github so that's why you cannot reproduce it...unless you decide to run it w dev containers and dedicate 1 core or less

@isaacrivriv

isaacrivriv commented Nov 13, 2025 •

Copy link
Copy Markdown
Contributor Author

Looks like on the last build it was a different failure not the same one...
AutoScalingEventExecutorChooserFactoryTest.testSmarterPickingConsolidatesWorkOnActiveExecutor:267 Should consolidate the trickle of work onto the single active executor, without waking up the suspended ones ==> expected: <1> but was: <2>

This one to me looks more of an issue with the test itself... I believe it's scaling up detecting that "trickle" of work to be more than a trickle. From what I could see locally (though I couldn't reproduce it completely), the metric from the executor was actually pretty close to the upscale threshold. If it's okay, I'll increase the up threshold and I believe that should help with this last failure.

@franz1981

Copy link
Copy Markdown
Contributor

If it's okay, I'll increase the up threshold and I believe that should help with this last failure.

yep, I think is ok @isaacrivriv

@isaacrivriv

Copy link
Copy Markdown
Contributor Author

Thanks for the suggestion @franz1981! I tried with dev containers and it made it a bit more reproducible but took quite a bit of tries to get it to occurr. I pushed one more change for the errors. Seems like a similar race condition as before where the event loop thread changes state but the thread itself stops and is not started again. I added a flag to attempt to restart it in this case but I'm wondering if this should be a whole new state maybe ST_RESTARTING and requires additional logic... Either way, hoping this helps with the remaining errors.

normanmaurer added a commit that referenced this pull request Sep 28, 2026
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 Sep 29, 2026
…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]>
@isaacrivriv

isaacrivriv commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor Author

It's very possible that what this PR was fixing, was already fixed last month in the following commits

will test after rebasing #15797 to verify if the failures are still there and if solved will close this up.

@isaacrivriv

Copy link
Copy Markdown
Contributor Author

I investigated this a bit more and found that the issue is still valid even with the latest changes. I will work on updating the PR to merge this in if possible.

@isaacrivriv
isaacrivriv force-pushed the 15809-fix-suspendingThread-not-started branch from 15e2500 to ecd9eea Compare October 23, 2026 03:09
@isaacrivriv

Copy link
Copy Markdown
Contributor Author

The failures seem to be unrelated to the changes from what I could tell so this should be safe to merge

Failed to execute goal me.normanmaurer.maven.autobahntestsuite:autobahntestsuite-maven-plugin:0.1.5:fuzzingclient (default) on project netty-testsuite-autobahn: Unable to start server: InvocationTargetException: Address already in use 

@isaacrivriv

Copy link
Copy Markdown
Contributor Author

@normanmaurer @franz1981 should be ready for review/merge when you get a chance

@isaacrivriv

Copy link
Copy Markdown
Contributor Author

@normanmaurer @franz1981 ping again

Motivation:

When `startThread()` moves the executor from `ST_SUSPENDING` back to
`ST_STARTED`, it sets `attemptRestart` before the CAS so the event loop
thread keeps running if it already returned from `run()`. A submitter
that lost the CAS cleared the flag again, which could also clear it
for the submitter that just won. The event loop thread then saw
`ST_STARTED` without the flag, treated it as a `run()` implementation
that did not confirm shutdown and shut down the executor.

There were also some smaller problems:

- The `attemptRestart` check in `doStartThread()` was duplicated.
- `startThread()` called itself recursively when the state changed.
- The idle / busy cycles were not reset when the suspension was
  cancelled, while they are when a suspended executor is started again.
- `testIdleExecutorsWithZeroMinChildren` used the same deadline for
  both waits, so the second one could time out too early.

Modification:

- Never clear `attemptRestart` from a submitting thread, only the event
  loop thread clears it.
- Use a loop in `startThread()` and reset the cycles when the
  suspension is cancelled.
- Remove the duplicated check.
- Document in `EventExecutor.trySuspend()` that submitting work before
  the suspension completed cancels it.
- Use a fresh deadline for the second wait and remove a useless
  assertion in `testIdleExecutorsWithZeroMinChildren`.
- Add `testExecuteWhileSuspendingCancelsSuspension`, which fails
  without the `ST_SUSPENDING` handling in `startThread()` or the
  cycle reset.
- Add `testConcurrentExecuteWhileSuspendingDoesNotShutdownExecutor`,
  which uses `canSuspend(int)` to release multiple submitters at once
  right after `run()` decided it can suspend. It fails if the flag is
  cleared on a failed CAS, never set or ignored.

Result:

Cancelling a suspension from multiple threads concurrently can not shut
down the executor anymore.
@testlens-app

testlens-app Bot commented Nov 27, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 16f8794
▶️ Tests: 58506 executed
⚪️ Checks: 26/26 completed


Learn more about TestLens at testlens.app/docs.

@normanmaurer

Copy link
Copy Markdown
Member

@isaacrivriv I think I fixed the last issues.. PTAL . Also @franz1981

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auto Scaling with minChildren 0 leads to broken dynamic scaling after scale up

4 participants