Skip to content

SingleThreadEventExecutor: fix race between suspend and cancellation … - #17589

Merged
normanmaurer merged 1 commit into
5.0from
suspend_race_fix
Sep 23, 2026
Merged

normanmaurer merged 1 commit into
5.0from
suspend_race_fix

Conversation

@normanmaurer

Copy link
Copy Markdown
Member

…of scheduled tasks

Motivation:

Cancelling a scheduled task removes it by resubmitting it via scheduleRemoveScheduled(), which can land in the task queue in the narrow window between run() deciding it can suspend and doStartThread() re-checking canSuspend() afterwards. doStartThread() only knew how to recover from a task racing in once the state had already reached ST_SUSPENDED; if the re-check simply saw canSuspend() return false while the state was still ST_SUSPENDING/ST_SUSPENDED, it fell through and treated the situation as if run() had returned without confirming shutdown, forcing the executor into a real shutdown even though nobody requested one. Once terminated, trySuspend() can never succeed again, so a caller looping on trySuspend() (as recommended when removal of a cancelled scheduled task may be lazy) spins until it times out.

Modifications:

  • doStartThread() now goes around the loop again instead of shutting down when canSuspend() is false but the state is still ST_SUSPENDING/ST_SUSPENDED, letting run() pick up whatever raced in.
  • Add SingleThreadEventExecutorTest.testSuspendDoesNotRaceWithCancelledScheduledTask, which repeats the schedule/suspend/cancel sequence many times to make the race reproducible.

Result:

Cancelling a scheduled task while an executor is suspending no longer risks a spurious shutdown.

…of scheduled tasks

Motivation:

Cancelling a scheduled task removes it by resubmitting it via
scheduleRemoveScheduled(), which can land in the task queue in the
narrow window between run() deciding it can suspend and
doStartThread() re-checking canSuspend() afterwards. doStartThread()
only knew how to recover from a task racing in once the state had
already reached ST_SUSPENDED; if the re-check simply saw canSuspend()
return false while the state was still ST_SUSPENDING/ST_SUSPENDED, it
fell through and treated the situation as if run() had returned
without confirming shutdown, forcing the executor into a real shutdown
even though nobody requested one. Once terminated, trySuspend() can
never succeed again, so a caller looping on trySuspend() (as
recommended when removal of a cancelled scheduled task may be lazy)
spins until it times out.

Modifications:

- doStartThread() now goes around the loop again instead of shutting
  down when canSuspend() is false but the state is still
  ST_SUSPENDING/ST_SUSPENDED, letting run() pick up whatever raced in.
- Add SingleThreadEventExecutorTest.testSuspendDoesNotRaceWithCancelledScheduledTask,
  which repeats the schedule/suspend/cancel sequence many times to make
  the race reproducible.

Result:

Cancelling a scheduled task while an executor is suspending no longer
risks a spurious shutdown.
@normanmaurer

Copy link
Copy Markdown
Member Author

This was found by AI but I was able to reproduce it with the test-code.

@normanmaurer normanmaurer added this to the 5.0.0.Final milestone Sep 22, 2026
@normanmaurer normanmaurer added the needs-cherry-pick-4.2 This PR should be cherry-picked to 4.2 once merged. label Sep 22, 2026
@testlens-app

testlens-app Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

⚠️ TestLens detected flakiness ⚠️

Test Summary

Build PR / macos-x86_64-java25-boringssl build > Netty/Transport/Native/KQueue

Test Runs Flakiness
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendDirectByteBuf(TestInfo) ❌ ✅ 1% 🟡

🏷️ Commit: 97cc8ce
▶️ Tests: 788 executed
⚪️ Checks: 14/14 completed

Test Failures

KQueueDatagramUnicastIPv6MappedTest > testSimpleSendDirectByteBuf(TestInfo) (Netty/Transport/Native/KQueue in Build PR / macos-x86_64-java25-boringssl build | Attempt 1/2)
org.opentest4j.AssertionFailedError
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSend0(DatagramUnicastTest.java:367)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSend(DatagramUnicastTest.java:194)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSendDirectByteBuf(DatagramUnicastTest.java:90)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest$1.run(DatagramUnicastTest.java:84)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest$1.run(DatagramUnicastTest.java:81)
	at io.netty.testsuite.transport.AbstractComboTestsuiteTest.run(AbstractComboTestsuiteTest.java:52)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSendDirectByteBuf(DatagramUnicastTest.java:81)
	at java.base/java.lang.reflect.Method.invoke(Method.java:565)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1604)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1604)

Learn more about TestLens at testlens.app/docs.

@normanmaurer
normanmaurer merged commit bcc636d into 5.0 Sep 23, 2026
26 of 27 checks passed
@normanmaurer
normanmaurer deleted the suspend_race_fix branch September 23, 2026 00:28
@netty-project-bot

Copy link
Copy Markdown
Contributor

Auto-port PR for 4.2: #17601

@github-actions github-actions Bot removed the needs-cherry-pick-4.2 This PR should be cherry-picked to 4.2 once merged. label Sep 23, 2026
normanmaurer added a commit that referenced this pull request Sep 25, 2026
…d cancellation … (#17601)

Auto-port of #17589 to 4.2
Cherry-picked commit: bcc636d

---
…of scheduled tasks

Motivation:

Cancelling a scheduled task removes it by resubmitting it via
scheduleRemoveScheduled(), which can land in the task queue in the
narrow window between run() deciding it can suspend and doStartThread()
re-checking canSuspend() afterwards. doStartThread() only knew how to
recover from a task racing in once the state had already reached
ST_SUSPENDED; if the re-check simply saw canSuspend() return false while
the state was still ST_SUSPENDING/ST_SUSPENDED, it fell through and
treated the situation as if run() had returned without confirming
shutdown, forcing the executor into a real shutdown even though nobody
requested one. Once terminated, trySuspend() can never succeed again, so
a caller looping on trySuspend() (as recommended when removal of a
cancelled scheduled task may be lazy) spins until it times out.

Modifications:

- doStartThread() now goes around the loop again instead of shutting
down when canSuspend() is false but the state is still
ST_SUSPENDING/ST_SUSPENDED, letting run() pick up whatever raced in.
- Add
SingleThreadEventExecutorTest.testSuspendDoesNotRaceWithCancelledScheduledTask,
which repeats the schedule/suspend/cancel sequence many times to make
the race reproducible.

Result:

Cancelling a scheduled task while an executor is suspending no longer
risks a spurious shutdown.

Co-authored-by: Norman Maurer <[email protected]>
normanmaurer added a commit that referenced this pull request Sep 26, 2026
…17627)

Motivation:

testSuspendDoesNotRaceWithCancelledScheduledTask (added to guard the
previous suspend/cancellation race fix) is still flaky: the worker
thread occasionally never terminates after trySuspend() reports the
executor as suspended.

scheduleRemoveScheduled() only wraps the scheduled-task removal with a
"try to suspend again afterwards" step when the executor has already
reached ST_SUSPENDED. If a scheduled task is cancelled while the
executor is still ST_SUSPENDING, the bare removal task is submitted
instead. Should that removal task race with doStartThread()'s
ST_SUSPENDED -> ST_STARTED recovery (which re-engages the thread as a
normal event loop once it notices the removal task queued up), nobody
ever re-requests suspension afterwards: the thread just blocks forever
in takeTask() waiting for new work, even though trySuspend() already
told callers it was suspended/suspending.

Separately, doStartThread()'s suspend-confirmation CAS hardcoded
ST_SUSPENDING as the expected current state, but the loop can re-enter
that check with the state already at ST_SUSPENDED (via the
ST_SUSPENDING/ST_SUSPENDED "something raced in" branch). The CAS would
then spuriously "fail" forever, livelocking the thread instead of
finishing the suspend.

Modifications:

- scheduleRemoveScheduled() now takes the "wrap with a re-suspend
attempt" path for ST_SUSPENDING too, not just ST_SUSPENDED.
- doStartThread() CASes from the actual currentState instead of the
hardcoded ST_SUSPENDING.
- add unit test

Result:

Cancelling a scheduled task while an executor is suspending reliably
lets the worker thread terminate (or keep running, if something new
raced in) instead of occasionally hanging forever.

Related to #17589
normanmaurer added a commit that referenced this pull request Sep 28, 2026
…ace (#17627) (#17649)

Motivation:

testSuspendDoesNotRaceWithCancelledScheduledTask (added to guard the
previous suspend/cancellation race fix) is still flaky: the worker
thread occasionally never terminates after trySuspend() reports the
executor as suspended.

scheduleRemoveScheduled() only wraps the scheduled-task removal with a
"try to suspend again afterwards" step when the executor has already
reached ST_SUSPENDED. If a scheduled task is cancelled while the
executor is still ST_SUSPENDING, the bare removal task is submitted
instead. Should that removal task race with doStartThread()'s
ST_SUSPENDED -> ST_STARTED recovery (which re-engages the thread as a
normal event loop once it notices the removal task queued up), nobody
ever re-requests suspension afterwards: the thread just blocks forever
in takeTask() waiting for new work, even though trySuspend() already
told callers it was suspended/suspending.

Separately, doStartThread()'s suspend-confirmation CAS hardcoded
ST_SUSPENDING as the expected current state, but the loop can re-enter
that check with the state already at ST_SUSPENDED (via the
ST_SUSPENDING/ST_SUSPENDED "something raced in" branch). The CAS would
then spuriously "fail" forever, livelocking the thread instead of
finishing the suspend.

Modifications:

- scheduleRemoveScheduled() now takes the "wrap with a re-suspend
attempt" path for ST_SUSPENDING too, not just ST_SUSPENDED.
- doStartThread() CASes from the actual currentState instead of the
hardcoded ST_SUSPENDING.
- add unit test

Result:

Cancelling a scheduled task while an executor is suspending reliably
lets the worker thread terminate (or keep running, if something new
raced in) instead of occasionally hanging forever.

Related to #17589
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]>
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.

3 participants