Skip to content

Fix flaky shared flow subscription #4489

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: fix-flaky-shared-flow-subscription
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions kotlinx-coroutines-core/common/src/flow/internal/ChannelFlow.kt
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,24 @@ public abstract class ChannelFlow<T>(
* For non-atomic start it is possible to observe the situation,
* where the pipeline after the [flowOn] call successfully executes (mostly, its `onCompletion`)
* handlers, while the pipeline before does not, because it was cancelled during its dispatch.
* Thus `onCompletion` and `finally` blocks won't be executed and it may lead to a different kinds of memory leaks.
* Thus `onCompletion` and `finally` blocks won't be executed, and it may lead to a different kind of memory leaks.
*/
public open fun produceImpl(scope: CoroutineScope): ReceiveChannel<T> =
scope.produce(context, produceCapacity, onBufferOverflow, start = CoroutineStart.ATOMIC, block = collectToFun)
produceImplInternal(scope, CoroutineStart.ATOMIC)

internal open fun produceImplInternal(scope: CoroutineScope, start: CoroutineStart): ReceiveChannel<T> =
scope.produce(context, produceCapacity, onBufferOverflow, start = start, block = collectToFun)

override suspend fun collect(collector: FlowCollector<T>): Unit =
coroutineScope {
collector.emitAll(produceImpl(this))
// If upstream and collect have the same dispatcher, launch the `produce` coroutine undispatched.
// This allows the collector to reliably subscribe to the flow before it starts emitting.
val current = currentCoroutineContext()[ContinuationInterceptor]
val desired = context[ContinuationInterceptor]
val start = if (desired == null || desired == current) {
CoroutineStart.UNDISPATCHED
} else CoroutineStart.ATOMIC
collector.emitAll(produceImplInternal(this, start))
}

protected open fun additionalToStringProps(): String? = null
Expand Down
8 changes: 4 additions & 4 deletions kotlinx-coroutines-core/common/test/channels/ProduceTest.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package kotlinx.coroutines.channels

import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.testing.*
import kotlin.coroutines.*
import kotlin.test.*

Expand Down Expand Up @@ -75,7 +75,7 @@ class ProduceTest : TestBase() {
try {
c.receive()
expectUnreached()
} catch (e: TestCancellationException) {
} catch (_: TestCancellationException) {
expect(5)
}
yield() // to produce
Expand Down Expand Up @@ -196,7 +196,7 @@ class ProduceTest : TestBase() {
assertFailsWith<IllegalStateException> { (channel as ProducerScope<*>).awaitClose() }
callbackFlow<Unit> {
expect(1)
launch {
launch(start = CoroutineStart.UNDISPATCHED) {
expect(2)
assertFailsWith<IllegalStateException> {
awaitClose { expectUnreached() }
Expand Down Expand Up @@ -286,7 +286,7 @@ class ProduceTest : TestBase() {
produced.cancel()
try {
source.receive()
} catch (e: CancellationException) {
} catch (_: CancellationException) {
finish(4)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package kotlinx.coroutines.flow

import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.testing.*
import kotlin.test.*

class ChannelFlowTest : TestBase() {
Expand All @@ -20,10 +20,9 @@ class ChannelFlowTest : TestBase() {
fun testBuffer() = runTest {
val flow = channelFlow {
assertTrue(trySend(1).isSuccess)
assertTrue(trySend(2).isSuccess)
assertFalse(trySend(3).isSuccess)
assertFalse(trySend(2).isSuccess)
}.buffer(1)
assertEquals(listOf(1, 2), flow.toList())
assertEquals(listOf(1), flow.toList())
}

@Test
Expand All @@ -34,7 +33,7 @@ class ChannelFlowTest : TestBase() {
assertTrue(trySend(3).isSuccess)
assertTrue(trySend(4).isSuccess)
}.buffer(Channel.CONFLATED)
assertEquals(listOf(1, 4), flow.toList()) // two elements in the middle got conflated
assertEquals(listOf(4), flow.toList())
}

@Test
Expand Down Expand Up @@ -164,14 +163,13 @@ class ChannelFlowTest : TestBase() {
val flow = channelFlow {
// ~ callback-based API, no children
outerScope.launch(Job()) {
expect(2)
send(1)
expectUnreached()
}
expect(1)
}
assertEquals(emptyList(), flow.toList())
finish(3)
finish(2)
}

@Test
Expand Down Expand Up @@ -206,13 +204,12 @@ class ChannelFlowTest : TestBase() {
}

@Test
fun testDoesntDispatchWhenUnnecessarilyWhenCollected() = runTest {
fun testDoesntDispatchUnnecessarilyWhenCollected() = runTest {
// Test that `.collectLatest` consistently subscribes to the flow when invoked on the same dispatcher as upstream.
expect(1)
var subscribed = false
val myFlow = flow<Int> {
expect(3)
subscribed = true
yield()
yield() // In other words, testing that this will be the first suspension point in `collectLatest`.
expect(5)
}
launch(start = CoroutineStart.UNDISPATCHED) {
Expand All @@ -223,6 +220,21 @@ class ChannelFlowTest : TestBase() {
finish(6)
}
expect(4)
assertTrue(subscribed)
}

@Test
fun testDispatchesToDifferentDispatcherWhenCollected() = runTest {
expect(1)
val myFlow = flow<Int> {
expect(4)
}.flowOn(wrapperDispatcher())
launch(start = CoroutineStart.UNDISPATCHED) {
expect(2)
myFlow.collectLatest {
expectUnreached()
}
finish(5)
}
expect(3)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

package kotlinx.coroutines.flow

import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.testing.*
Copy link
Contributor Author

@murfel murfel Aug 8, 2025

Choose a reason for hiding this comment

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

Unrelated: L1: Do we need the suppression on Line 1? I don't quite understand how it is relevant here.

import kotlin.test.*

class FlowCallbackTest : TestBase() {
Expand All @@ -14,24 +14,25 @@ class FlowCallbackTest : TestBase() {
val flow = callbackFlow {
// ~ callback-based API
outerScope.launch(Job()) {
expect(2)
try {
expect(4)
send(1)
expectUnreached()
} catch (e: IllegalStateException) {
expect(3)
expect(5)
assertTrue(e.message!!.contains("awaitClose"))
}
finish(6)
}
expect(1)
}
try {
flow.collect()
} catch (e: IllegalStateException) {
expect(4)
expect(2)
assertTrue(e.message!!.contains("awaitClose"))
}
finish(5)
expect(3)
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package kotlinx.coroutines.flow

import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.testing.*
import kotlin.test.*

/**
* A _behavioral_ test for conflation options that can be configured by the [buffer] operator to test that it is
* implemented properly and that adjacent [buffer] calls are fused properly.
*/
*/
class BufferConflationTest : TestBase() {
private val n = 100 // number of elements to emit for test

Expand All @@ -20,8 +19,8 @@ class BufferConflationTest : TestBase() {
expect(1)
// emit all and conflate, then collect first & last
val expectedList = when (onBufferOverflow) {
BufferOverflow.DROP_OLDEST -> listOf(0) + (n - capacity until n).toList() // first item & capacity last ones
BufferOverflow.DROP_LATEST -> (0..capacity).toList() // first & capacity following ones
BufferOverflow.DROP_OLDEST -> (n - capacity until n).toList() // first item & capacity last ones
BufferOverflow.DROP_LATEST -> (0 until capacity).toList() // first & capacity following ones
else -> error("cannot happen")
}
flow {
Expand All @@ -38,6 +37,26 @@ class BufferConflationTest : TestBase() {
finish(n + 2 + expectedList.size)
}

@Test
fun testConflateExplicit() = runTest {
val n = 3
expect(1)
flow {
expect(2)
emit(0)
expect(3)
emit(1)
expect(4)
emit(2)
}
.conflate()
.collect { value ->
assertEquals(2, value)
expect(n + 2)
}
finish(n + 2 + 1)
}

@Test
fun testConflate() =
checkConflate(1) {
Expand Down Expand Up @@ -138,6 +157,6 @@ class BufferConflationTest : TestBase() {
fun testBuffer3DropOldestOverrideBuffer8DropLatest() =
checkConflate(3, BufferOverflow.DROP_OLDEST) {
buffer(8, onBufferOverflow = BufferOverflow.DROP_LATEST)
.buffer(3, BufferOverflow.DROP_OLDEST)
.buffer(3, BufferOverflow.DROP_OLDEST)
}
}
Loading