Skip to content

Commit 7e0184a

Browse files
committed
Fix SOE with select (WIP, DO NOT MERGE)
* 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). * TODO:NOTE: SelectDeadlockLFStressTest does not pass and is disabled. !!! DO NOT MERGE !!! Fixes #504 Fixes #1411
1 parent 57cc364 commit 7e0184a

23 files changed

+498
-128
lines changed

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

Lines changed: 9 additions & 2 deletions
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

Lines changed: 4 additions & 4 deletions
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

Lines changed: 24 additions & 18 deletions
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,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
384385
when {
385386
offerResult === ALREADY_SELECTED -> return
386387
offerResult === OFFER_FAILED -> {} // retry
388+
offerResult === RETRY_ATOMIC -> {} // retry
387389
offerResult === OFFER_SUCCESS -> {
388390
block.startCoroutineUnintercepted(receiver = this, completion = select.completion)
389391
return
@@ -437,7 +439,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
437439
@JvmField val block: suspend (SendChannel<E>) -> R
438440
) : Send(), DisposableHandle {
439441
override fun tryResumeSend(idempotent: Any?): Any? =
440-
if (select.trySelect(idempotent)) SELECT_STARTED else null
442+
select.trySelectIdempotent(idempotent)
441443

442444
override fun completeResumeSend(token: Any) {
443445
assert { token === SELECT_STARTED }
@@ -449,7 +451,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
449451
}
450452

451453
override fun resumeSendClosed(closed: Closed<*>) {
452-
if (select.trySelect(null))
454+
if (select.trySelect())
453455
select.resumeSelectCancellableWithException(closed.sendException)
454456
}
455457

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

505507
/**
506508
* 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`
509+
* Return type is `ALREADY_SELECTED | E | POLL_FAILED | RETRY_ATOMIC | Closed`
508510
* @suppress **This is unstable API and it is subject to change.**
509511
*/
510512
protected open fun pollSelectInternal(select: SelectInstance<*>): Any? {
@@ -654,11 +656,12 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
654656
}
655657

656658
@Suppress("UNCHECKED_CAST")
657-
override fun validatePrepared(node: Send): Boolean {
658-
val token = node.tryResumeSend(idempotent = this) ?: return false
659+
override fun validatePrepared(node: Send): Any? {
660+
val token = node.tryResumeSend(idempotent = this) ?: return REMOVE_PREPARED
661+
if (token === RETRY_ATOMIC) return RETRY_ATOMIC
659662
resumeToken = token
660663
pollResult = node.pollResult as E
661-
return true
664+
return null
662665
}
663666
}
664667

@@ -680,6 +683,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
680683
when {
681684
pollResult === ALREADY_SELECTED -> return
682685
pollResult === POLL_FAILED -> {} // retry
686+
pollResult === RETRY_ATOMIC -> {}
683687
pollResult is Closed<*> -> throw recoverStackTrace(pollResult.receiveException)
684688
else -> {
685689
block.startCoroutineUnintercepted(pollResult as E, select.completion)
@@ -708,9 +712,10 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
708712
when {
709713
pollResult === ALREADY_SELECTED -> return
710714
pollResult === POLL_FAILED -> {} // retry
715+
pollResult === RETRY_ATOMIC -> {} // retry
711716
pollResult is Closed<*> -> {
712717
if (pollResult.closeCause == null) {
713-
if (select.trySelect(null))
718+
if (select.trySelect())
714719
block.startCoroutineUnintercepted(null, select.completion)
715720
return
716721
} else {
@@ -745,6 +750,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
745750
when {
746751
pollResult === ALREADY_SELECTED -> return
747752
pollResult === POLL_FAILED -> {} // retry
753+
pollResult === RETRY_ATOMIC -> {} // retry
748754
pollResult is Closed<*> -> {
749755
block.startCoroutineUnintercepted(ValueOrClosed.closed(pollResult.closeCause), select.completion)
750756
}
@@ -927,8 +933,10 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
927933
@JvmField val block: suspend (Any?) -> R,
928934
@JvmField val receiveMode: Int
929935
) : Receive<E>(), DisposableHandle {
930-
override fun tryResumeReceive(value: E, idempotent: Any?): Any? =
931-
if (select.trySelect(idempotent)) (value ?: NULL_VALUE) else null
936+
override fun tryResumeReceive(value: E, idempotent: Any?): Any? {
937+
val result = select.trySelectIdempotent(idempotent)
938+
return if (result === SELECT_STARTED) value ?: NULL_VALUE else result
939+
}
932940

933941
@Suppress("UNCHECKED_CAST")
934942
override fun completeResumeReceive(token: Any) {
@@ -937,7 +945,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
937945
}
938946

939947
override fun resumeReceiveClosed(closed: Closed<*>) {
940-
if (!select.trySelect(null)) return
948+
if (!select.trySelect()) return
941949
when (receiveMode) {
942950
RECEIVE_THROWS_ON_CLOSE -> select.resumeSelectCancellableWithException(closed.receiveException)
943951
RECEIVE_RESULT -> block.startCoroutine(ValueOrClosed.closed<R>(closed.closeCause), select.completion)
@@ -984,10 +992,6 @@ internal val POLL_FAILED: Any = Symbol("POLL_FAILED")
984992
@SharedImmutable
985993
internal val ENQUEUE_FAILED: Any = Symbol("ENQUEUE_FAILED")
986994

987-
@JvmField
988-
@SharedImmutable
989-
internal val SELECT_STARTED: Any = Symbol("SELECT_STARTED")
990-
991995
@JvmField
992996
@SharedImmutable
993997
internal val NULL_VALUE: Symbol = Symbol("NULL_VALUE")
@@ -1011,6 +1015,7 @@ internal typealias Handler = (Throwable?) -> Unit
10111015
*/
10121016
internal abstract class Send : LockFreeLinkedListNode() {
10131017
abstract val pollResult: Any? // E | Closed
1018+
// Returns: null - failure, RETRY_ATOMIC for retry (only when idempotent != null), otherwise token for completeResumeSend
10141019
abstract fun tryResumeSend(idempotent: Any?): Any?
10151020
abstract fun completeResumeSend(token: Any)
10161021
abstract fun resumeSendClosed(closed: Closed<*>)
@@ -1021,6 +1026,7 @@ internal abstract class Send : LockFreeLinkedListNode() {
10211026
*/
10221027
internal interface ReceiveOrClosed<in E> {
10231028
val offerResult: Any // OFFER_SUCCESS | Closed
1029+
// Returns: null - failure, RETRY_ATOMIC for retry (only when idempotent != null), otherwise token for completeResumeReceive
10241030
fun tryResumeReceive(value: E, idempotent: Any?): Any?
10251031
fun completeResumeReceive(token: Any)
10261032
}

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2+
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
33
*/
44

55
package kotlinx.coroutines.channels
@@ -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

Lines changed: 4 additions & 2 deletions
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2+
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
33
*/
44

55
package kotlinx.coroutines.channels
@@ -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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
/*
2-
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2+
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
33
*/
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)