Skip to content
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

Fix Flow.timeout swallowing the channel closure exception #4072

Merged
merged 1 commit into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions kotlinx-coroutines-core/common/src/flow/operators/Delay.kt
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ private fun <T> Flow<T>.timeoutInternal(
value.onSuccess {
downStream.emit(it)
}.onClosed {
it?.let { throw it }
Copy link
Contributor

Choose a reason for hiding this comment

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

Is it correct that the reason this issue manifested itself is our fusing optimization?

Copy link
Contributor

Choose a reason for hiding this comment

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

Oh, it boils down to the following:

val job = Job()
val produce = produce<Int>(job) { close(TestException()) }
(produce as Job).join()
job.isCancelled // False

Which makes sense for produce specifically (when it's used as a standalone coroutine builder), but not much when used as part of the flow machinery

Copy link
Contributor

Choose a reason for hiding this comment

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

Also, kind of confusing semantics-wise: close with a cause fails the channel, and when a coroutine fails, the channel fails as well. Yet the channel failure on its now does not represent failure.

return@onReceiveCatching false
}
return@onReceiveCatching true
Expand Down
11 changes: 11 additions & 0 deletions kotlinx-coroutines-core/common/test/flow/operators/TimeoutTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,17 @@ class TimeoutTest : TestBase() {
testImmediateTimeout(-1.seconds)
}

@Test
fun testClosing() = runTest {
assertFailsWith<TestException> {
channelFlow<Int> { close(TestException()) }
.timeout(Duration.INFINITE)
.collect {
expectUnreached()
}
}
}

private fun testImmediateTimeout(timeout: Duration) {
expect(1)
val flow = emptyFlow<Int>().timeout(timeout)
Expand Down