Unpredictable tatal exception in kotlinx.coroutines internal machinery with Ktor


I’ve been having a really strange issue for a bit now, related to kotlinx.coroutines and Ktor which I can’t reliably reproduce, let alone start to debug and understand.

It happens, seemingly at random, although seems to happen at roughly the same spots, which may indicate some form of data race (?).

Here’s the exception information I get with coroutine debug mode enabled:

Exception in thread "DefaultDispatcher-worker-11" kotlinx.coroutines.CoroutinesInternalError: Fatal exception in coroutines machinery for DispatchedContinuation[Dispatchers.Default, Continuation at io.ktor.client.HttpClient.execute$ktor_client_core(HttpClient.kt:191)@4b98bc73]. Please read KDoc to 'handleFatalException' method and report this incident to maintainers
	at kotlinx.coroutines.DispatchedTask.handleFatalException(DispatchedTask.kt:144)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:115)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)
	Suppressed: kotlinx.coroutines.internal.DiagnosticCoroutineContextException: [CoroutineId(546), "coroutine#546":StandaloneCoroutine{Completed}@73f0a21a, Dispatchers.Default]
Caused by: java.lang.ClassCastException: class kotlin.coroutines.jvm.internal.CompletedContinuation cannot be cast to class kotlinx.coroutines.internal.DispatchedContinuation (kotlin.coroutines.jvm.internal.CompletedContinuation and kotlinx.coroutines.internal.DispatchedContinuation are in unnamed module of loader 'app')
	at kotlinx.coroutines.CoroutineDispatcher.releaseInterceptedContinuation(CoroutineDispatcher.kt:166)
	at kotlin.coroutines.jvm.internal.ContinuationImpl.releaseIntercepted(ContinuationImpl.kt:118)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:39)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:104)
	... 4 more

The code is rather large and sparse for me to show here, but I don’t even interact with Ktor directly, rather through an API wrapper which handles every call for me. I’ve asked around in that library’s support channels and nobody seems to be having the same issue or even something remotely close, so I suppose it isn’t the origin of this strange problem.

Does anyone have any suggestion, any tip on how to tackle this and start debugging this? I’ve tried messing with that handleFatalException but to no avail, perhaps I did it wrong, I don’t know.

Any help will be immensely appreciated. Thank you!

1 Like

Forgot to mention, I’m using the following versions:
Kotlin 1.8.20
kotlinx.coroutines 1.7.1
Ktor 2.3.0.