Skip to content

Kotlin Coroutines Fail to preserve active request between a suspension and resume #49307

@pcasaes

Description

@pcasaes

Describe the bug

While reviewing possible fixes for #45441
It was noticed that the kotlin coroutine dispatcher for quarkus-messaging in some cases fails to preserve the active request when an incoming message function's coroutine scope is suspended and then resumed.

Looking at the messaging dispatcher https://github.com/quarkusio/quarkus/blob/3.25.0/extensions/smallrye-reactive-messaging/kotlin/src/main/kotlin/io/quarkus/smallrye/reactivemessaging/runtime/kotlin/VertxDispatcher.kt

    override fun dispatch(context: CoroutineContext, block: Runnable) {
        val requestContext = Arc.container().requestContext()
        vertxContext.runOnContext {
            if (requestContext.isActive) {
                block.run()
            } else {
                try {
                    requestContext.activate()
                    block.run()
                } finally {
                    requestContext.terminate()
                }
            }
        }
    }

We can see that in some cases (when requestContext.isActive is false) the dispatcher will create a new request context and terminate once block completes or is suspended (In Kotlin Coroutines Dispatcher's dispatch is always called on resume). This means that on resume the previous active request's data will be lost.

original thread: #49157 (comment)

Expected behavior

The active request should remain the same throughout the execution of the coroutine scope.

Actual behavior

A new active request is created on each resume of the coroutine's scope.

How to Reproduce?

Reproducer available here
https://github.com/pcasaes/kafka-kotlin-repro

Output of uname -a or ver

Darwin MyMachine 24.5.0 Darwin Kernel Version 24.5.0: Tue Apr 22 19:53:27 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T6041 arm64

Output of java -version

openjdk version "21.0.8" 2025-07-15 LTS OpenJDK Runtime Environment Corretto-21.0.8.9.1 (build 21.0.8+9-LTS) OpenJDK 64-Bit Server VM Corretto-21.0.8.9.1 (build 21.0.8+9-LTS, mixed mode, sharing)

Quarkus version or git rev

3.25.0

Build tool (ie. output of mvnw --version or gradlew --version)

Apache Maven 3.9.9 (8e8579a9e76f7d015ee5ec7bfcdc97d260186937) Maven home: `.m2/wrapper/dists/apache-maven-3.9.9-bin/33b4b2b4/apache-maven-3.9.9 Java version: 21.0.8, vendor: Amazon.com Inc., runtime: /Users/paulo.casaes/.sdkman/candidates/java/21.0.8-amzn Default locale: en_US, platform encoding: UTF-8 OS name: "mac os x", version: "15.5", arch: "aarch64", family: "mac"

Additional information

I believe this issue is also present in other extensions like vertx-kotlin and scheduler-kotlin

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions