Skip to content

Commit aaef25f

Browse files
committed
Fix SOE with select (WIP)
* onSend/onReceive clauses on the same channel: Instead of StackOverflowError we throw IllegalStateException and leave the channel in the original state. * Fix SOE in select with "opposite channels" stress-test. The fix is based on the sequential numbering of atomic select operation. Deadlock is detected and the operation with the lower sequential number is aborted and restarted (with a larger number). Fixes #504 Fixes #1411
1 parent 1be2bf6 commit aaef25f

23 files changed

+517
-122
lines changed

binary-compatibility-validator/reference-public-api/kotlinx-coroutines-core.txt

+9-2
Original file line numberDiff line numberDiff line change
@@ -1049,7 +1049,9 @@ public final class kotlinx/coroutines/selects/SelectBuilderImpl : kotlinx/corout
10491049
public fun performAtomicTrySelect (Lkotlinx/coroutines/internal/AtomicDesc;)Ljava/lang/Object;
10501050
public fun resumeSelectCancellableWithException (Ljava/lang/Throwable;)V
10511051
public fun resumeWith (Ljava/lang/Object;)V
1052-
public fun trySelect (Ljava/lang/Object;)Z
1052+
public fun toString ()Ljava/lang/String;
1053+
public fun trySelect ()Z
1054+
public fun trySelectIdempotent (Ljava/lang/Object;)Ljava/lang/Object;
10531055
}
10541056

10551057
public abstract interface class kotlinx/coroutines/selects/SelectClause0 {
@@ -1070,13 +1072,18 @@ public abstract interface class kotlinx/coroutines/selects/SelectInstance {
10701072
public abstract fun isSelected ()Z
10711073
public abstract fun performAtomicTrySelect (Lkotlinx/coroutines/internal/AtomicDesc;)Ljava/lang/Object;
10721074
public abstract fun resumeSelectCancellableWithException (Ljava/lang/Throwable;)V
1073-
public abstract fun trySelect (Ljava/lang/Object;)Z
1075+
public abstract fun trySelect ()Z
1076+
public abstract fun trySelectIdempotent (Ljava/lang/Object;)Ljava/lang/Object;
10741077
}
10751078

10761079
public final class kotlinx/coroutines/selects/SelectKt {
10771080
public static final fun select (Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
10781081
}
10791082

1083+
public synthetic class kotlinx/coroutines/selects/SelectKtSelectOpSequenceNumberRefVolatile {
1084+
public fun <init> (J)V
1085+
}
1086+
10801087
public final class kotlinx/coroutines/selects/SelectUnbiasedKt {
10811088
public static final fun selectUnbiased (Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
10821089
}

kotlinx-coroutines-core/common/src/JobSupport.kt

+4-4
Original file line numberDiff line numberDiff line change
@@ -553,7 +553,7 @@ public open class JobSupport constructor(active: Boolean) : Job, ChildJob, Paren
553553
if (select.isSelected) return
554554
if (state !is Incomplete) {
555555
// already complete -- select result
556-
if (select.trySelect(null)) {
556+
if (select.trySelect()) {
557557
block.startCoroutineUnintercepted(select.completion)
558558
}
559559
return
@@ -1181,7 +1181,7 @@ public open class JobSupport constructor(active: Boolean) : Job, ChildJob, Paren
11811181
if (select.isSelected) return
11821182
if (state !is Incomplete) {
11831183
// already complete -- select result
1184-
if (select.trySelect(null)) {
1184+
if (select.trySelect()) {
11851185
if (state is CompletedExceptionally) {
11861186
select.resumeSelectCancellableWithException(state.cause)
11871187
}
@@ -1362,7 +1362,7 @@ private class SelectJoinOnCompletion<R>(
13621362
private val block: suspend () -> R
13631363
) : JobNode<JobSupport>(job) {
13641364
override fun invoke(cause: Throwable?) {
1365-
if (select.trySelect(null))
1365+
if (select.trySelect())
13661366
block.startCoroutineCancellable(select.completion)
13671367
}
13681368
override fun toString(): String = "SelectJoinOnCompletion[$select]"
@@ -1374,7 +1374,7 @@ private class SelectAwaitOnCompletion<T, R>(
13741374
private val block: suspend (T) -> R
13751375
) : JobNode<JobSupport>(job) {
13761376
override fun invoke(cause: Throwable?) {
1377-
if (select.trySelect(null))
1377+
if (select.trySelect())
13781378
job.selectAwaitCompletion(select, block)
13791379
}
13801380
override fun toString(): String = "SelectAwaitOnCompletion[$select]"

kotlinx-coroutines-core/common/src/channels/AbstractChannel.kt

+35-20
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
5656

5757
/**
5858
* Tries to add element to buffer or to queued receiver if select statement clause was not selected yet.
59-
* Return type is `ALREADY_SELECTED | OFFER_SUCCESS | OFFER_FAILED | Closed`.
59+
* Return type is `ALREADY_SELECTED | OFFER_SUCCESS | OFFER_FAILED | RETRY_ATOMIC | Closed`.
6060
* @suppress **This is unstable API and it is subject to change.**
6161
*/
6262
protected open fun offerSelectInternal(element: E, select: SelectInstance<*>): Any {
@@ -345,10 +345,11 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
345345
else -> null
346346
}
347347

348-
override fun validatePrepared(node: ReceiveOrClosed<E>): Boolean {
349-
val token = node.tryResumeReceive(element, idempotent = this) ?: return false
348+
override fun validatePrepared(node: ReceiveOrClosed<E>): Any? {
349+
val token = node.tryResumeReceive(element, idempotent = this) ?: return REMOVE_PREPARED
350+
if (token === RETRY_ATOMIC) return RETRY_ATOMIC
350351
resumeToken = token
351-
return true
352+
return null
352353
}
353354
}
354355

@@ -384,6 +385,9 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
384385
when {
385386
offerResult === ALREADY_SELECTED -> return
386387
offerResult === OFFER_FAILED -> {} // retry
388+
offerResult === RETRY_ATOMIC -> {
389+
// println("registerSelectSend($element): RETRY")
390+
} // retry
387391
offerResult === OFFER_SUCCESS -> {
388392
block.startCoroutineUnintercepted(receiver = this, completion = select.completion)
389393
return
@@ -436,20 +440,25 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
436440
@JvmField val select: SelectInstance<R>,
437441
@JvmField val block: suspend (SendChannel<E>) -> R
438442
) : Send(), DisposableHandle {
439-
override fun tryResumeSend(idempotent: Any?): Any? =
440-
if (select.trySelect(idempotent)) SELECT_STARTED else null
443+
override fun tryResumeSend(idempotent: Any?): Any? {
444+
val result = select.trySelectIdempotent(idempotent)
445+
// println("SendSelect($pollResult) tryResumeSend=$result")
446+
return result
447+
}
441448

442449
override fun completeResumeSend(token: Any) {
443450
assert { token === SELECT_STARTED }
451+
// println("SendSelect($pollResult) completeResumeSend")
444452
block.startCoroutine(receiver = channel, completion = select.completion)
445453
}
446454

447455
override fun dispose() { // invoked on select completion
456+
// println("SendSelect($pollResult) dispose")
448457
remove()
449458
}
450459

451460
override fun resumeSendClosed(closed: Closed<*>) {
452-
if (select.trySelect(null))
461+
if (select.trySelect())
453462
select.resumeSelectCancellableWithException(closed.sendException)
454463
}
455464

@@ -504,7 +513,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
504513

505514
/**
506515
* Tries to remove element from buffer or from queued sender if select statement clause was not selected yet.
507-
* Return type is `ALREADY_SELECTED | E | POLL_FAILED | Closed`
516+
* Return type is `ALREADY_SELECTED | E | POLL_FAILED | RETRY_ATOMIC | Closed`
508517
* @suppress **This is unstable API and it is subject to change.**
509518
*/
510519
protected open fun pollSelectInternal(select: SelectInstance<*>): Any? {
@@ -644,7 +653,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
644653
* @suppress **This is unstable API and it is subject to change.**
645654
*/
646655
protected class TryPollDesc<E>(queue: LockFreeLinkedListHead) : RemoveFirstDesc<Send>(queue) {
647-
@JvmField var resumeToken: Any? = null
656+
@JvmField var resumeToken: Any? = null // can be RETRY_ATOMIC
648657
@JvmField var pollResult: E? = null
649658

650659
override fun failure(affected: LockFreeLinkedListNode): Any? = when (affected) {
@@ -654,11 +663,12 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
654663
}
655664

656665
@Suppress("UNCHECKED_CAST")
657-
override fun validatePrepared(node: Send): Boolean {
658-
val token = node.tryResumeSend(idempotent = this) ?: return false
666+
override fun validatePrepared(node: Send): Any? {
667+
val token = node.tryResumeSend(idempotent = this) ?: return REMOVE_PREPARED
668+
if (token === RETRY_ATOMIC) return RETRY_ATOMIC
659669
resumeToken = token
660670
pollResult = node.pollResult as E
661-
return true
671+
return null
662672
}
663673
}
664674

@@ -680,6 +690,9 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
680690
when {
681691
pollResult === ALREADY_SELECTED -> return
682692
pollResult === POLL_FAILED -> {} // retry
693+
pollResult === RETRY_ATOMIC -> {
694+
// println("registerSelectReceive(): RETRY")
695+
} // retry
683696
pollResult is Closed<*> -> throw recoverStackTrace(pollResult.receiveException)
684697
else -> {
685698
block.startCoroutineUnintercepted(pollResult as E, select.completion)
@@ -708,9 +721,10 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
708721
when {
709722
pollResult === ALREADY_SELECTED -> return
710723
pollResult === POLL_FAILED -> {} // retry
724+
pollResult === RETRY_ATOMIC -> {} // retry
711725
pollResult is Closed<*> -> {
712726
if (pollResult.closeCause == null) {
713-
if (select.trySelect(null))
727+
if (select.trySelect())
714728
block.startCoroutineUnintercepted(null, select.completion)
715729
return
716730
} else {
@@ -745,6 +759,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
745759
when {
746760
pollResult === ALREADY_SELECTED -> return
747761
pollResult === POLL_FAILED -> {} // retry
762+
pollResult === RETRY_ATOMIC -> {} // retry
748763
pollResult is Closed<*> -> {
749764
block.startCoroutineUnintercepted(ValueOrClosed.closed(pollResult.closeCause), select.completion)
750765
}
@@ -927,8 +942,10 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
927942
@JvmField val block: suspend (Any?) -> R,
928943
@JvmField val receiveMode: Int
929944
) : Receive<E>(), DisposableHandle {
930-
override fun tryResumeReceive(value: E, idempotent: Any?): Any? =
931-
if (select.trySelect(idempotent)) (value ?: NULL_VALUE) else null
945+
override fun tryResumeReceive(value: E, idempotent: Any?): Any? {
946+
val result = select.trySelectIdempotent(idempotent)
947+
return if (result === SELECT_STARTED) value ?: NULL_VALUE else result
948+
}
932949

933950
@Suppress("UNCHECKED_CAST")
934951
override fun completeResumeReceive(token: Any) {
@@ -937,7 +954,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
937954
}
938955

939956
override fun resumeReceiveClosed(closed: Closed<*>) {
940-
if (!select.trySelect(null)) return
957+
if (!select.trySelect()) return
941958
when (receiveMode) {
942959
RECEIVE_THROWS_ON_CLOSE -> select.resumeSelectCancellableWithException(closed.receiveException)
943960
RECEIVE_RESULT -> block.startCoroutine(ValueOrClosed.closed<R>(closed.closeCause), select.completion)
@@ -984,10 +1001,6 @@ internal val POLL_FAILED: Any = Symbol("POLL_FAILED")
9841001
@SharedImmutable
9851002
internal val ENQUEUE_FAILED: Any = Symbol("ENQUEUE_FAILED")
9861003

987-
@JvmField
988-
@SharedImmutable
989-
internal val SELECT_STARTED: Any = Symbol("SELECT_STARTED")
990-
9911004
@JvmField
9921005
@SharedImmutable
9931006
internal val NULL_VALUE: Symbol = Symbol("NULL_VALUE")
@@ -1011,6 +1024,7 @@ internal typealias Handler = (Throwable?) -> Unit
10111024
*/
10121025
internal abstract class Send : LockFreeLinkedListNode() {
10131026
abstract val pollResult: Any? // E | Closed
1027+
// Returns: null - failure, RETRY_ATOMIC for retry (only when idempotent != null), otherwise token for completeResumeSend
10141028
abstract fun tryResumeSend(idempotent: Any?): Any?
10151029
abstract fun completeResumeSend(token: Any)
10161030
abstract fun resumeSendClosed(closed: Closed<*>)
@@ -1021,6 +1035,7 @@ internal abstract class Send : LockFreeLinkedListNode() {
10211035
*/
10221036
internal interface ReceiveOrClosed<in E> {
10231037
val offerResult: Any // OFFER_SUCCESS | Closed
1038+
// Returns: null - failure, RETRY_ATOMIC for retry (only when idempotent != null), otherwise token for completeResumeReceive
10241039
fun tryResumeReceive(value: E, idempotent: Any?): Any?
10251040
fun completeResumeReceive(token: Any)
10261041
}

kotlinx-coroutines-core/common/src/channels/ArrayBroadcastChannel.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ internal class ArrayBroadcastChannel<E>(
105105
val size = this.size
106106
if (size >= capacity) return OFFER_FAILED
107107
// let's try to select sending this element to buffer
108-
if (!select.trySelect(null)) { // :todo: move trySelect completion outside of lock
108+
if (!select.trySelect()) { // :todo: move trySelect completion outside of lock
109109
return ALREADY_SELECTED
110110
}
111111
val tail = this.tail
@@ -299,7 +299,7 @@ internal class ArrayBroadcastChannel<E>(
299299
result === POLL_FAILED -> { /* just bail out of lock */ }
300300
else -> {
301301
// let's try to select receiving this element from buffer
302-
if (!select.trySelect(null)) { // :todo: move trySelect completion outside of lock
302+
if (!select.trySelect()) { // :todo: move trySelect completion outside of lock
303303
result = ALREADY_SELECTED
304304
} else {
305305
// update subHead after retrieiving element from buffer

kotlinx-coroutines-core/common/src/channels/ArrayChannel.kt

+4-2
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ internal open class ArrayChannel<E>(
105105
return@withLock
106106
}
107107
failure === OFFER_FAILED -> break@loop // cannot offer -> Ok to queue to buffer
108+
failure === RETRY_ATOMIC -> {} // retry
108109
failure === ALREADY_SELECTED || failure is Closed<*> -> {
109110
this.size = size // restore size
110111
return failure
@@ -114,7 +115,7 @@ internal open class ArrayChannel<E>(
114115
}
115116
}
116117
// let's try to select sending this element to buffer
117-
if (!select.trySelect(null)) { // :todo: move trySelect completion outside of lock
118+
if (!select.trySelect()) { // :todo: move trySelect completion outside of lock
118119
this.size = size // restore size
119120
return ALREADY_SELECTED
120121
}
@@ -206,6 +207,7 @@ internal open class ArrayChannel<E>(
206207
break@loop
207208
}
208209
failure === POLL_FAILED -> break@loop // cannot poll -> Ok to take from buffer
210+
failure === RETRY_ATOMIC -> {} // retry
209211
failure === ALREADY_SELECTED -> {
210212
this.size = size // restore size
211213
buffer[head] = result // restore head
@@ -226,7 +228,7 @@ internal open class ArrayChannel<E>(
226228
buffer[(head + size) % buffer.size] = replacement
227229
} else {
228230
// failed to poll or is already closed --> let's try to select receiving this element from buffer
229-
if (!select.trySelect(null)) { // :todo: move trySelect completion outside of lock
231+
if (!select.trySelect()) { // :todo: move trySelect completion outside of lock
230232
this.size = size // restore size
231233
buffer[head] = result // restore head
232234
return ALREADY_SELECTED

kotlinx-coroutines-core/common/src/channels/ConflatedBroadcastChannel.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ public class ConflatedBroadcastChannel<E>() : BroadcastChannel<E> {
273273
}
274274

275275
private fun <R> registerSelectSend(select: SelectInstance<R>, element: E, block: suspend (SendChannel<E>) -> R) {
276-
if (!select.trySelect(null)) return
276+
if (!select.trySelect()) return
277277
offerInternal(element)?.let {
278278
select.resumeSelectCancellableWithException(it.sendException)
279279
return

kotlinx-coroutines-core/common/src/channels/ConflatedChannel.kt

+1
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ internal open class ConflatedChannel<E> : AbstractChannel<E>() {
8585
result === ALREADY_SELECTED -> return ALREADY_SELECTED
8686
result === OFFER_SUCCESS -> return OFFER_SUCCESS
8787
result === OFFER_FAILED -> {} // retry
88+
result === RETRY_ATOMIC -> {} // retry
8889
result is Closed<*> -> return result
8990
else -> error("Invalid result $result")
9091
}

kotlinx-coroutines-core/common/src/channels/LinkedListChannel.kt

+2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
package kotlinx.coroutines.channels
66

7+
import kotlinx.coroutines.internal.*
78
import kotlinx.coroutines.selects.*
89

910
/**
@@ -52,6 +53,7 @@ internal open class LinkedListChannel<E> : AbstractChannel<E>() {
5253
result === ALREADY_SELECTED -> return ALREADY_SELECTED
5354
result === OFFER_SUCCESS -> return OFFER_SUCCESS
5455
result === OFFER_FAILED -> {} // retry
56+
result === RETRY_ATOMIC -> {} // retry
5557
result is Closed<*> -> return result
5658
else -> error("Invalid result $result")
5759
}

0 commit comments

Comments
 (0)