Fix leaked Main dispatcher flake in AuditHistoryViewModelRoomTest (#376) (#471)

AuditHistoryViewModelRoomTest pointed Dispatchers.Main at the shared
Dispatchers.IO pool and tore down with a fire-and-forget
testScope.coroutineContext[Job]?.cancel() (no join) before resetMain(),
and never cancelled the VM's viewModelScope at all. A viewModelScope
coroutine (the stateIn upstream / Room flow collector) could therefore
still be dispatching on Main when resetMain() ran, and could outlive it.

Unit tests run in a single JVM (no forkEvery), so the leaked Main override
surfaces as an IllegalStateException from kotlinx.coroutines.test's internal
TestMainDispatcher in a random later test's setMain. That is the moving-target
flake in #376 (CI run 27476494784 attempt 1: failures in
AuditHistoryViewModelRoomTest.kt:83 at resetMain and, downstream,
OnboardingViewModelTest).

Fix:
- Add MainDispatcherRule: pairs setMain/resetMain in a TestRule so the reset
  always runs in a finally around the whole test.
- Route Main to a dedicated single-thread executor the test owns (not shared
  IO), preserving the real cross-thread scheduler Room's invalidation tracker
  needs while making the dispatcher drainable.
- Own the VM in a ViewModelStore; in tearDown cancel viewModelScope via
  clear(), then shutdown()+awaitTermination() the executor so Main is fully
  quiescent (worker thread dead) before the rule's resetMain() fires. Join the
  warmup collector with cancelAndJoin on the runBlocking scope.

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
monkopedia-coder 2026-06-13 16:28:09 -04:00 • committed by GitHub
parent e635e73393
commit ce959cd33a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 106 additions and 18 deletions

View file

@ -0,0 +1,48 @@
package com.rousecontext.app.testing
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
/**
* JUnit rule that installs [dispatcher] as `Dispatchers.Main` for the duration
* of a test and unconditionally restores the original Main afterwards.
*
* Pairing `setMain`/`resetMain` in a rule (rather than ad-hoc `@Before`/`@After`
* methods) makes the reset bulletproof: the rule's teardown runs in a `finally`
* around the whole test even if the body throws, so the Main dispatcher can
* never be left overridden and leak into a subsequent test in the same JVM.
*
* Unit tests run in a single JVM (`testOptions.unitTests` sets no `forkEvery`),
* so a leaked Main override surfaces as an `IllegalStateException` from
* `kotlinx.coroutines.test`'s internal `TestMainDispatcher` in a *random later*
* test's `setMain` — the moving-target flake tracked in issue #376.
*
* The rule's teardown only resets Main; it does NOT join coroutines. A test that
* routes Main to a *real* (thread-backed) dispatcher must ensure its own
* coroutines are cancelled and drained to quiescence in its `@After` (which runs
* before this rule's teardown) so nothing is still dispatching on Main when the
* reset fires.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(private val dispatcher: CoroutineDispatcher = UnconfinedTestDispatcher()) :
TestRule {
override fun apply(base: Statement, description: Description): Statement =
object : Statement() {
override fun evaluate() {
Dispatchers.setMain(dispatcher)
try {
base.evaluate()
} finally {
Dispatchers.resetMain()
}
}
}
}

View file

@ -1,29 +1,30 @@
package com.rousecontext.app.ui.viewmodels
import android.content.Context
import androidx.lifecycle.ViewModelStore
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import com.rousecontext.app.testing.MainDispatcherRule
import com.rousecontext.notifications.audit.AuditDatabase
import com.rousecontext.notifications.audit.AuditEntry
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import kotlinx.coroutines.withTimeout
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@ -49,21 +50,41 @@ import org.robolectric.RobolectricTestRunner
*
* Exercises a real in-memory Room database so the test pins the actual
* `stateIn` lifecycle semantics rather than mocking `observeByDateRange`.
*
* ## Dispatcher discipline (issue #376)
*
* The VM's `viewModelScope` runs on `Dispatchers.Main.immediate`. This test
* points Main at a **dedicated single-thread dispatcher** ([mainExecutor]) so
* Room's reactive Flow and the VM share a real, thread-backed scheduler:
* the invalidation tracker fires on the DB executor threads and must deliver
* a genuine cross-thread wakeup to the `stateIn` collector, exactly as it does
* on-device. An `UnconfinedTestDispatcher` would trampoline emissions on the
* calling thread and miss those wakeups.
*
* Owning the executor (instead of sharing `Dispatchers.IO`, whose threads
* outlive the test) is what makes teardown deterministic: [tearDown] cancels
* the VM's `viewModelScope`, then drains the executor to quiescence before the
* [MainDispatcherRule] resets Main. Once the worker thread is dead no coroutine
* can still be dispatching on Main, so the reset cannot race a leftover
* coroutine — eliminating the leaked-Main flake from issue #376.
*/
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(RobolectricTestRunner::class)
class AuditHistoryViewModelRoomTest {
private val mainExecutor: ExecutorService = Executors.newSingleThreadExecutor()
@get:Rule
val mainDispatcherRule = MainDispatcherRule(mainExecutor.asCoroutineDispatcher())
private lateinit var database: AuditDatabase
private lateinit var testScope: CoroutineScope
// Owns the VM so tearDown can cancel its viewModelScope via clear().
private val viewModelStore = ViewModelStore()
private lateinit var vm: AuditHistoryViewModel
@Before
fun setUp() {
// ViewModel's viewModelScope uses Dispatchers.Main.immediate. Routing
// Main to the IO dispatcher lets Room's reactive Flow and the VM share
// a real scheduler; Unconfined would trampoline emissions on the
// calling thread and miss cross-thread invalidation-tracker wakeups.
Dispatchers.setMain(Dispatchers.IO)
val context = ApplicationProvider.getApplicationContext<Context>()
// Build the database directly so the query/transaction executor is a
// real thread pool. Robolectric's default scheduling can leave Room's
@ -73,21 +94,34 @@ class AuditHistoryViewModelRoomTest {
.setQueryExecutor(Executors.newSingleThreadExecutor())
.setTransactionExecutor(Executors.newSingleThreadExecutor())
.build()
testScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
vm = AuditHistoryViewModel(auditDao = database.auditDao())
viewModelStore.put("audit", vm)
}
@After
fun tearDown() {
testScope.coroutineContext[Job]?.cancel()
// 1. Cancel the VM's viewModelScope: stops the stateIn upstream and any
// in-flight Room flow collectors. Their cancellation continuations
// are dispatched onto mainExecutor.
viewModelStore.clear()
// 2. Drain Main to quiescence. shutdown() lets the already-queued
// cancellation work finish while rejecting new tasks; awaitTermination
// blocks until the single worker thread is idle and dead. After this,
// nothing can dispatch on Main, so the rule's resetMain() (which runs
// next) cannot race a leftover coroutine.
mainExecutor.shutdown()
check(mainExecutor.awaitTermination(DRAIN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
"Main dispatcher thread did not drain within ${DRAIN_TIMEOUT_MS}ms"
}
database.close()
Dispatchers.resetMain()
// MainDispatcherRule.apply()'s finally runs Dispatchers.resetMain() here,
// on a now-dead dispatcher thread.
}
@Test
fun `re-subscribing after a row insert reflects the new row without stale empty`() {
runBlocking {
val dao = database.auditDao()
val vm = AuditHistoryViewModel(auditDao = dao)
// Phase 1: first subscriber lands on an empty DB and sees groups = [].
val firstLoaded = withTimeout(TIMEOUT_MS) {
@ -101,9 +135,10 @@ class AuditHistoryViewModelRoomTest {
)
// A no-op collector warms the shared flow so stateIn has seen at
// least one live subscriber. Cancelling it simulates the user
// leaving the audit screen.
val warmupJob: Job = vm.state.onEach { /* observe */ }.launchIn(testScope)
// least one live subscriber. Cancelling it (with join) simulates the
// user leaving the audit screen and guarantees the warmup coroutine
// is fully torn down before we proceed.
val warmupJob: Job = vm.state.onEach { /* observe */ }.launchIn(this)
warmupJob.cancelAndJoin()
// Phase 2: insert a row while the user is "away". This mirrors
@ -141,5 +176,10 @@ class AuditHistoryViewModelRoomTest {
// stuck grace window turns into a clear failure rather than a
// flaky hang.
const val TIMEOUT_MS = 10_000L
// Upper bound for cancelled viewModelScope work to drain off Main.
// Cancelled coroutines unwind near-instantly; this is a safety net,
// not an expected wait.
const val DRAIN_TIMEOUT_MS = 10_000L
}
}