A new Job is passed to a coroutine builder, cutting the coroutine off from its parent

tx0/kotlin:job-passed-to-coroutine-builderrecommendedwarningreliability/concurrencydepth fastbug, concurrency

What it finds

launch(Job()) { ... } or withContext(SupervisorJob()) { ... }: the job in the context becomes the parent of the new coroutine, replacing the job of the scope. The coroutine is then no longer cancelled with its scope, and the scope does not wait for it, which breaks structured concurrency. Passing a job is meant for creating a scope, as in CoroutineScope(SupervisorJob()), which is not reported.

Reported for launch, async, withContext, produce and actor when the context argument is, or adds, a call to Job() or SupervisorJob().

From the rule's source, job_in_builder.rs.

Example from the rule's tests
import kotlinx.coroutines.* class Screen {    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)     fun refresh() {        scope.launch(Job()) { reload() }tx0 reports: Job() passed to launch replaces the parent job        scope.launch(Dispatchers.IO + SupervisorJob()) { reload() }tx0 reports: SupervisorJob() passed to launch        scope.launch(Dispatchers.IO) { reload() }    }     suspend fun save() = withContext(NonCancellable) { store() }    suspend fun store() = withContext(context = Job()) { }tx0 reports: Job() passed to withContext}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:job-passed-to-coroutine-builder" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/kotlin:job-passed-to-coroutine-builder] reason="..."

tx0 explain tx0/kotlin:job-passed-to-coroutine-builder shows the same in the terminal. Found a false positive? Report it.