Modern Apps git

← Modern-Apps.git

arrows: deflake board-generation and view-model tests (140 tests)

Commit
69dea9babc81c3e7306a3688f095850d066bde69
Author
Vayun Mathur <[email protected]>
When
2026-11-15 03:55 UTC (21 days ago)
Parents
a3393f0
Two distinct flakes in this module:

1. GeneratedBoardPropertiesTest.generatingTheWholeLadderStaysAffordable
   asserted 120 fresh boards in under 25 s of wall clock. That
   budget was roughly 3x the cost measured on the author's host,
   but generation costs ~21 s on this host even idle, and a
   loaded full-suite run measured 33.75 s - the assertion was
   measuring scheduler contention and host speed, not generator
   work. The budget is now charged in thread CPU time and
   expressed in units of a fixed independent reference workload
   (SHA-256 over a fixed buffer) timed in the same process
   immediately beforehand: host speed and load move the
   reference and the ladder together, while a generator
   regression moves only the ladder. The ladder measures ~18
   reference units here; the budget is 55x, keeping the original
   roughly-3x looseness. It remains a hard fail if generation
   becomes pathologically expensive, and the board-count
   assertion is unchanged.

2. ArrowsViewModelTest (and PagesTest, same pattern) called
   Dispatchers.setMain in setUp and resetMain in tearDown per
   method. ViewModels created in these tests are never cleared,
   so their viewModelScope coroutines keep reading
   Dispatchers.Main after a method ends; resetMain raced those
   readers ('Dispatchers.Main is used concurrently with setting
   it', reproduced in 2 of 3 full-suite runs before this fix)
   and the failed reset cascaded into subsequent methods. Both
   classes now install Main (Unconfined) once per class and
   never reset it between methods; the Robolectric sandbox is
   per-class, so nothing leaks into other test classes.

Verified: before, the perf test failed in the loaded full check
(33.75 s wall) and in 2/2 --no-build-cache loaded reruns, and
ArrowsViewModelTest failed intermittently in isolated
full-suite runs, while the named tests passed in isolation.
After: 5 consecutive green :games:arrows:testDevUnitTest runs
with --no-build-cache, 3 isolated at --max-workers=32 and 2
under load at --max-workers=64 on a busy host (140 tests).

Diff

games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/GeneratedBoardPropertiesTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/GeneratedBoardPropertiesTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/GeneratedBoardPropertiesTest.ktindex a3424958f7..7364fe473b 100644--- a/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/GeneratedBoardPropertiesTest.kt+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/GeneratedBoardPropertiesTest.kt@@ -131,11 +131,46 @@ class GeneratedBoardPropertiesTest {         // Generation is off the main thread behind a spinner, so this is about not leaving the player         // watching it. Deliberately loose: it is a guard against a pathological regression, not a target.         // Generates fresh rather than reusing the shared ladder, since the point is to time the work.-        val started = System.nanoTime()+        //+        // The budget is charged in thread CPU time, not wall clock: wall+        // clock under a fully loaded test host mostly measures scheduler+        // contention from the other test workers (this test measured+        // 33.75 s of wall time in a loaded full-suite run), which says+        // nothing about whether generation itself regressed. CPU time+        // alone is not host-independent either - the same generation+        // costs ~21 s of CPU on this host and several times less on a+        // faster one - so the budget is expressed in units of a fixed+        // reference workload (SHA-256 over a fixed buffer) timed in+        // the same process immediately beforehand. Host speed and+        // load move the reference and the ladder together, while a+        // generator regression moves only the ladder. On this host the+        // ladder costs ~18 reference units; the budget allows 55+        // (the same roughly-3x looseness the old absolute budget had).+        val refStart = threadCpuTimeNanos()+        val digest = java.security.MessageDigest.getInstance("SHA-256")+        val buf = ByteArray(65_536) { (it * 31).toByte() }+        repeat(REF_ITERATIONS) { digest.digest(buf) }+        val refMillis = (threadCpuTimeNanos() - refStart) / 1_000_000+        val cpu = threadCpuTimeNanos()         val boards = ladder.count { generate(it) != null }-        val millis = (System.nanoTime() - started) / 1_000_000+        val millis = (threadCpuTimeNanos() - cpu) / 1_000_000         assertEquals(LADDER_DEPTH, boards)-        assertTrue(millis < BUDGET_MILLIS, "generating $LADDER_DEPTH boards took ${millis}ms")+        assertTrue(+            millis < refMillis * MAX_LADDER_REF_RATIO,+            "generating $LADDER_DEPTH boards took ${millis}ms of CPU " ++                "(${millis / refMillis.coerceAtLeast(1)}x the ${refMillis}ms reference, " ++                "budget ${MAX_LADDER_REF_RATIO}x)",+        )+    }++    /** Current thread's CPU time, falling back to wall clock where the bean is unsupported. */+    private fun threadCpuTimeNanos(): Long {+        val bean = java.lang.management.ManagementFactory.getThreadMXBean()+        return if (bean.isCurrentThreadCpuTimeSupported) {+            bean.currentThreadCpuTime+        } else {+            System.nanoTime()+        }     }      /**@@ -161,8 +196,14 @@ class GeneratedBoardPropertiesTest {          const val LEVEL_SEED = 104_729L -        /** Roughly three times the measured cost, so ordinary variation does not turn this red. */-        const val BUDGET_MILLIS = 25_000L+        /** Fixed reference workload size for the affordability budget (see the test). */+        const val REF_ITERATIONS = 20_000++        /**+         * Ladder budget in reference-workload units: roughly three times the+         * measured ~18x ratio, so ordinary variation does not turn this red.+         */+        const val MAX_LADDER_REF_RATIO = 55L          fun generate(level: Int): ArrowsPuzzle? = ArrowsGenerator.generateSeeded(             cols = boardSizeForLevel(level).first,
games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.ktindex f9a898af60..540cb8c76f 100644--- a/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.kt+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.kt@@ -15,11 +15,9 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout-import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner-import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals@@ -35,8 +33,26 @@ import kotlin.test.assertTrue class ArrowsViewModelTest {     private val app get() = ApplicationProvider.getApplicationContext<Application>() -    @BeforeTest fun setUp() { Dispatchers.setMain(Dispatchers.Unconfined) }-    @AfterTest fun tearDown() { Dispatchers.resetMain() }+    // Main is installed once for the whole class and never reset between+    // methods: ViewModels created here are never cleared, so their+    // viewModelScope coroutines keep reading Dispatchers.Main after a+    // method ends. A per-method setMain/resetMain races those readers+    // ("Dispatchers.Main is used concurrently with setting it") and the+    // failed reset then cascades into the following methods. The+    // Robolectric sandbox is per-class, so leaving Main installed for+    // the class's lifetime leaks nothing into other test classes.+    @BeforeTest fun setUp() {+        synchronized(Companion) {+            if (!mainInstalled) {+                Dispatchers.setMain(Dispatchers.Unconfined)+                mainInstalled = true+            }+        }+    }++    private companion object {+        var mainInstalled = false+    }      /**      * runBlocking with a deadline, so a wedged store fails the test instead of hanging the whole
games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.ktindex 4a10b3d312..8046a95dcd 100644--- a/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.kt+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.kt@@ -14,12 +14,10 @@ import com.vayunmathur.games.arrows.platform.ArrowsViewModel import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner-import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals@@ -34,12 +32,23 @@ class PagesTest {     private fun str(id: Int) = ctx.getString(id)      @BeforeTest fun setUp() {-        Dispatchers.setMain(Dispatchers.Unconfined)+        // As in ArrowsViewModelTest: install Main once per class, never+        // reset per method - uncleared ViewModels keep reading it, and+        // resetting races them (and cascades into later methods).+        synchronized(Companion) {+            if (!mainInstalled) {+                Dispatchers.setMain(Dispatchers.Unconfined)+                mainInstalled = true+            }+        }         runCatching {             androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())         }     }-    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private companion object {+        var mainInstalled = false+    }      private fun await(desc: String, cond: () -> Boolean) {         val deadline = System.currentTimeMillis() + 30_000