Modern Apps git

← Modern-Apps.git

tests: companion tasks finish in minutes under CI CPU caps

Commit
12f96407c63a550ea914b7f3fee0cf5710067334
Author
Vayun Mathur <[email protected]>
When
2026-11-22 10:16 UTC (14 days ago)
Parents
904bdfa
Three tasks held CI at its 45-minute cap. Under 5 CPUs the
wall-clock sleep-poll waits starve: producers never get a
slice before the deadline, and nonogram's suite additionally
raced the sandbox looper via Dispatchers.setMain(Unconfined)
(jstack-proven) with batched forks nested in the task. All
sleep-polls in appstore/backup/nonogram are now step-bounded
pumped waits (pump first, advance the looper, park briefly so
IO producers run, never a wall deadline), nonogram drops the
Unconfined main and pins forkEvery=1 for its ViewModel suite
with the rationale in the file.

Verified in the CI shape (taskset 5 CPUs, no daemon/cache):
appstore Native 3m38s, backup Native 46s, nonogram ~1m20s
twice - all green, far under the cap. No assertions weakened,
no timeout raised.

Diff

appstore/src/test/java/com/vayunmathur/appstore/tv/TvActionIntentsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvActionIntentsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvActionIntentsTest.ktindex 9dc33158e7..2d68401a59 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvActionIntentsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvActionIntentsTest.kt@@ -46,13 +46,48 @@ class TvActionIntentsTest {     private fun nextStarted(): Intent? = Shadows.shadowOf(app).nextStartedActivity      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 10_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+// Original pumping primitive for this class: idle() only,+            // no looper-clock advance (advancing it here drove delayed+            // work early and broke the terminal states this waits on).             Shadows.shadowOf(Looper.getMainLooper()).idle()-            if (condition()) return-            Thread.sleep(50)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description")+    }++    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvCheckBranchesTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvCheckBranchesTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvCheckBranchesTest.ktindex cf7899c6ee..5a55c216b8 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvCheckBranchesTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvCheckBranchesTest.kt@@ -94,14 +94,46 @@ class TvCheckBranchesTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; updates=${vm.updatesUi.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; updates=${vm.updatesUi.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.ktindex 38bfd0a57a..acb435b62d 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt@@ -56,14 +56,46 @@ class TvDetailWrapperAndActionsTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; detail=${vm.detail.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; detail=${vm.detail.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      private fun nextStarted(): Intent? = Shadows.shadowOf(app).nextStartedActivity
appstore/src/test/java/com/vayunmathur/appstore/tv/TvHomeBranchesTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvHomeBranchesTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvHomeBranchesTest.ktindex 692ded4842..00b0fe467f 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvHomeBranchesTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvHomeBranchesTest.kt@@ -43,14 +43,46 @@ class TvHomeBranchesTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; home=${vm.home.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(400, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; home=${vm.home.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 400L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryOpsPlayTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryOpsPlayTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryOpsPlayTest.ktindex 3ebfa94967..4e2d46908c 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryOpsPlayTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryOpsPlayTest.kt@@ -50,13 +50,48 @@ class TvLibraryOpsPlayTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+// Original pumping primitive for this class: idle() only,+            // no looper-clock advance (advancing it here drove delayed+            // work early and broke the terminal states this waits on).             Shadows.shadowOf(Looper.getMainLooper()).idle()-            if (condition()) return-            Thread.sleep(50)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description")+    }++    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test@@ -70,8 +105,17 @@ class TvLibraryOpsPlayTest {         await("refresh settled") {             vm.installedRepo.apps.value.any { it.packageName == app.packageName }         }-        Thread.sleep(500)-        Shadows.shadowOf(Looper.getMainLooper()).idle()+        // Quiescence settle (the negative half of this assertion): pump+        // the looper for a bounded window so any erroneous clear the+        // refresh might still issue has every chance to land, instead+        // of sleeping 500ms and hoping it would have happened by then.+        repeat(50) {+            Shadows.shadowOf(Looper.getMainLooper())+                .idleFor(100, java.util.concurrent.TimeUnit.MILLISECONDS)+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(10),+            )+        }         assertEquals(setOf("com.example.kept"), vm.playInstalledPackagesFlow.value)     } 
appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryTest.ktindex e42ea555f6..6e7abf8f87 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLibraryTest.kt@@ -58,16 +58,46 @@ class TvLibraryTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; library=${vm.library.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvLoadHomePlayAccrescentTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLoadHomePlayAccrescentTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLoadHomePlayAccrescentTest.ktindex 0db7e09312..e5c55ff8b4 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLoadHomePlayAccrescentTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvLoadHomePlayAccrescentTest.kt@@ -99,14 +99,46 @@ class TvLoadHomePlayAccrescentTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; home=${vm.home.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; home=${vm.home.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchLiveSourcesTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchLiveSourcesTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchLiveSourcesTest.ktindex 9294b7a5ca..f05d6c46fc 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchLiveSourcesTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchLiveSourcesTest.kt@@ -56,14 +56,46 @@ class TvSearchLiveSourcesTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; search=${vm.search.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(400, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; search=${vm.search.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 400L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchOpsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchOpsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchOpsTest.ktindex 559fce7632..03fa10c0fc 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchOpsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvSearchOpsTest.kt@@ -64,16 +64,46 @@ class TvSearchOpsTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(400, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; search=${vm.search.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 400L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreLoadHomeTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreLoadHomeTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreLoadHomeTest.ktindex bd7ed2c02c..1c5976a967 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreLoadHomeTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreLoadHomeTest.kt@@ -62,14 +62,46 @@ class TvStoreLoadHomeTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; enabled=${vm.enabledSourcesFlow.value}; home=${vm.home.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; enabled=${vm.enabledSourcesFlow.value}; home=${vm.home.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.ktindex f1dfb0659f..f6920e46cd 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt@@ -51,13 +51,48 @@ class TvStoreViewModelTest {     // The in-memory DB dies with the Robolectric sandbox.      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 10_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; home=${vm.home.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+// Original pumping primitive for this class: idle() only,+            // no looper-clock advance (advancing it here drove delayed+            // work early and broke the terminal states this waits on).             Shadows.shadowOf(Looper.getMainLooper()).idle()-            if (condition()) return-            Thread.sleep(50)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; home=${vm.home.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateAllEligibleTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateAllEligibleTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateAllEligibleTest.ktindex 3a2cbac2e9..b7937eeb57 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateAllEligibleTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateAllEligibleTest.kt@@ -59,14 +59,46 @@ class TvUpdateAllEligibleTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; updates=${vm.updatesUi.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; updates=${vm.updatesUi.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateCheckTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateCheckTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateCheckTest.ktindex a3a4df5b2e..a2ba3f9faa 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateCheckTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvUpdateCheckTest.kt@@ -73,16 +73,46 @@ class TvUpdateCheckTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; updates=${vm.updatesUi.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/ui/PagesWrapperTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/ui/PagesWrapperTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/ui/PagesWrapperTest.ktindex a66bac15c5..9c36f8881f 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/ui/PagesWrapperTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/ui/PagesWrapperTest.kt@@ -74,13 +74,18 @@ class PagesWrapperTest {     @Test     fun `library page attributes the installed app to its catalogue source`() {         rule.setContent { LibraryPage(viewModel = vm, onAppClick = {}) }-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline &&-            vm.library.value.apps.none { it.packageName == ownPackage }-        ) {+        // Step-bounded pump (not a wall-clock deadline, which CI+        // contention can burn before the library flow lands): advance+        // the paused looper and yield a CPU slice per step, then let+        // the assertions below judge the terminal state.+        var steps = 0+        while (vm.library.value.apps.none { it.packageName == ownPackage } && steps++ < 6_000) {             org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            Thread.sleep(50)+                .idleFor(100, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (vm.library.value.apps.any { it.packageName == ownPackage }) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(10),+            )         }         assertTrue(exists("App Store"), "library apps were ${vm.library.value.apps.map { it.name to it.packageName }}")         assertTrue(
appstore/src/test/java/com/vayunmathur/appstore/ui/SourcesPageAllDisabledTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/ui/SourcesPageAllDisabledTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/ui/SourcesPageAllDisabledTest.ktindex 24cccb2914..701b916319 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/ui/SourcesPageAllDisabledTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/ui/SourcesPageAllDisabledTest.kt@@ -42,13 +42,48 @@ class SourcesPageAllDisabledTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+// Original pumping primitive for this class: idle() only,+            // no looper-clock advance (advancing it here drove delayed+            // work early and broke the terminal states this waits on).             Shadows.shadowOf(Looper.getMainLooper()).idle()-            if (condition()) return-            Thread.sleep(50)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description")+    }++    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.ktindex 93b8544fba..ba21aba3ad 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/AccrescentVmOpsW5Test.kt@@ -9,7 +9,6 @@ import com.vayunmathur.appstore.platform.refreshInstalled  import android.app.Application import android.content.Context-import android.os.Looper import androidx.room3.Room import androidx.sqlite.driver.bundled.BundledSQLiteDriver import androidx.test.core.app.ApplicationProvider@@ -36,7 +35,9 @@ import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.accrescent.AccrescentApi import com.vayunmathur.appstore.data.accrescent.AccrescentRepository+import com.vayunmathur.appstore.data.SettingsRepository import com.vayunmathur.appstore.platform.TvStoreViewModel+import android.os.Looper import io.grpc.ManagedChannel import io.grpc.Server import io.grpc.inprocess.InProcessChannelBuilder@@ -46,6 +47,10 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner@@ -152,28 +157,76 @@ class AccrescentVmOpsW5Test {         server.shutdownNow()     } -    // The settings edits below run on Dispatchers.IO, not the bare-    // runBlocking main thread: in the full suite this test class shares-    // the appstore-settings DataStore with every earlier ViewModel's-    // still-collecting SettingsRepository mirror, and an edit issued-    // from the paused Robolectric main thread could wait forever for-    // work queued on that same thread (phoneVmHomeBrowseAndPackageSelection-    // deadlocked at the edit in full-suite runs, while passing alone).+    // The settings edits below are launched on Dispatchers.IO and then+    // awaited by pumping the paused Robolectric main looper — never by+    // parking this thread in runBlocking. Parking the main thread waits+    // forever for work queued on that same thread: every earlier+    // ViewModel's SettingsRepository mirror collects the shared+    // appstore-settings DataStore from viewModelScope (Main), and under+    // CI CPU contention the edit's completion work sits in that paused+    // looper queue behind the parked thread (this class's+    // phoneVmHomeBrowseAndPackageSelection wedged exactly there for+    // 8+ minutes under a 5-CPU cap, while passing alone locally).+    // pumpUntil idles/advances the looper on every check, so the queued+    // collectors run, the edit lands, and only then does the wait end:+    // a deterministic terminal signal, no wall-clock deadline.++    private fun enableAccrescent(settings: SettingsRepository) {+        val done = CompletableDeferred<Unit>()+        CoroutineScope(Dispatchers.IO).launch {+            try {+                settings.setSourceEnabled(AppSource.ACCRESCENT, true)+                done.complete(Unit)+            } catch (e: Throwable) {+                done.completeExceptionally(e)+            }+        }+        pumpUntil("accrescent source enabled") { done.isCompleted }+        done.getCompletionExceptionOrNull()?.let { throw it }+    }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {-            Shadows.shadowOf(Looper.getMainLooper()).idleFor(100, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+        pumpUntil(description, condition)+    }+    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs, and+     * the failure is raised only after [MAX_PUMP_STEPS] pumps.+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+            Shadows.shadowOf(Looper.getMainLooper())+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description")     } +    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000+    }++     @Test     fun phoneVmAccrescentSearchSelectAndUpdateCheck() {         val vm = AppStoreViewModel(app, db, accrescentOverride = repo)-        runBlocking(kotlinx.coroutines.Dispatchers.IO) { vm.settings.setSourceEnabled(AppSource.ACCRESCENT, true) } // off the main thread (see below)+        enableAccrescent(vm.settings)         vm.setSearch("alpha")         await("accrescent search") {             vm.search.value.results.any { it.packageName == "app.alpha" }@@ -205,7 +258,7 @@ class AccrescentVmOpsW5Test {     fun tvVmAccrescentSearchSelectAndUpdateCheck() {         val vm = TvStoreViewModel(app, db, accrescentOverride = repo)         vm.enabledSourcesFlow.value = setOf(AppSource.ACCRESCENT, AppSource.MODERN_APPS)-        runBlocking(kotlinx.coroutines.Dispatchers.IO) { vm.settings.setSourceEnabled(AppSource.ACCRESCENT, true) }+        enableAccrescent(vm.settings)         vm.setSearch("beta")         await("tv accrescent search") {             vm.search.value.results.any { it.packageName == "app.beta" }@@ -236,7 +289,7 @@ class AccrescentVmOpsW5Test {     @Test     fun phoneVmHomeBrowseAndPackageSelection() {         val vm = AppStoreViewModel(app, db, accrescentOverride = repo)-        runBlocking(kotlinx.coroutines.Dispatchers.IO) { vm.settings.setSourceEnabled(AppSource.ACCRESCENT, true) }+        enableAccrescent(vm.settings)         vm.refresh()         await("home sections from accrescent") {             vm.home.value.sections.flatMap { it.apps }.any { it.packageName == "app.alpha" } ||@@ -261,7 +314,7 @@ class AccrescentVmOpsW5Test {     fun tvVmLibraryBrowseInstallAndSourceToggles() {         val vm = TvStoreViewModel(app, db, accrescentOverride = repo)         vm.enabledSourcesFlow.value = setOf(AppSource.ACCRESCENT, AppSource.MODERN_APPS)-        runBlocking(kotlinx.coroutines.Dispatchers.IO) { vm.settings.setSourceEnabled(AppSource.ACCRESCENT, true) }+        enableAccrescent(vm.settings)         vm.loadHome()         await("tv home for browse") { !vm.isLoadingFlow.value }         vm.home.value.categories.firstOrNull()?.let { vm.selectCategory(it) }
appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.ktindex a69bec254a..bb0702b22a 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/AppStoreViewModelTest.kt@@ -61,13 +61,48 @@ class AppStoreViewModelTest {     // The in-memory DB dies with the Robolectric sandbox.      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 10_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; home=${vm.home.value} search=${vm.search.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+// Original pumping primitive for this class: idle() only,+            // no looper-clock advance (advancing it here drove delayed+            // work early and broke the terminal states this waits on).             Shadows.shadowOf(Looper.getMainLooper()).idle()-            if (condition()) return-            Thread.sleep(50)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; home=${vm.home.value} search=${vm.search.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.ktindex e4309d8544..3765b75c16 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt@@ -73,16 +73,46 @@ class DetailAndBrowseOpsTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; detail=${vm.detail.value}; browse=${vm.browse.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/HomeOpsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/HomeOpsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/HomeOpsTest.ktindex 05e3859b6c..0729e31c25 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/HomeOpsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/HomeOpsTest.kt@@ -61,16 +61,46 @@ class HomeOpsTest {     // The in-memory DB dies with the Robolectric sandbox.      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 10_000-        while (System.currentTimeMillis() < deadline) {-            // idleFor advances Robolectric's virtual clock, which the-            // search debounce delay is scheduled against.+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; search=${vm.search.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(400, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; search=${vm.search.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 400L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/LoadHomeTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/LoadHomeTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/LoadHomeTest.ktindex 6a2f13f10e..e9005a46fd 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/LoadHomeTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/LoadHomeTest.kt@@ -66,14 +66,46 @@ class LoadHomeTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; home=${vm.home.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; home=${vm.home.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/PhoneCheckAccrescentTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneCheckAccrescentTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneCheckAccrescentTest.ktindex 46d9dfb997..1284c485e8 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneCheckAccrescentTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneCheckAccrescentTest.kt@@ -81,14 +81,46 @@ class PhoneCheckAccrescentTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; updates=${vm.updatesUi.value}", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description; updates=${vm.updatesUi.value}")+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/PhoneInstallTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneInstallTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneInstallTest.ktindex df5eb7f04e..a15c99b715 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneInstallTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneInstallTest.kt@@ -46,11 +46,17 @@ class PhoneInstallTest {             name = "No Download",         )         vm.install(target)-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {-            Shadows.shadowOf(Looper.getMainLooper()).idle()+        // Step-bounded pump instead of a wall-clock deadline (see+        // PagesWrapperTest): looper steps, not seconds CI contention+        // can burn before the install settles.+        var steps = 0+        while (steps++ < 6_000) {+            Shadows.shadowOf(Looper.getMainLooper())+                .idleFor(100, java.util.concurrent.TimeUnit.MILLISECONDS)             if (vm.installer.stages.value[target.packageName] is InstallStage.Failed) break-            Thread.sleep(50)+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(10),+            )         }         val stage = vm.installer.stages.value[target.packageName]         assertTrue(stage is InstallStage.Failed, "stage was $stage")
appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSearchLiveTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSearchLiveTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSearchLiveTest.ktindex 09f94cfac7..b80fc8e490 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSearchLiveTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSearchLiveTest.kt@@ -15,6 +15,10 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner@@ -53,23 +57,63 @@ class PhoneSearchLiveTest {         // Not closed: the ViewModel scope keeps collecting DB flows; the         // in-memory DB dies with the Robolectric sandbox.         vm = AppStoreViewModel(app, db)-        runBlocking {+        editSettings {             vm.settings.setSourceEnabled(AppSource.ACCRESCENT, false)             vm.settings.setSourceEnabled(AppSource.PLAYSTORE, false)         }     } +    // Pumped looper waits (see AccrescentVmOpsW5Test.enableAccrescent):+    // parking or sleep-polling this thread can wait forever on work+    // queued in the paused main looper under CI CPU contention.+    private fun editSettings(block: suspend () -> Unit) {+        val done = CompletableDeferred<Unit>()+        CoroutineScope(Dispatchers.IO).launch {+            try { block(); done.complete(Unit) } catch (e: Throwable) { done.completeExceptionally(e) }+        }+        pumpUntil("settings edit") { done.isCompleted }+        done.getCompletionExceptionOrNull()?.let { throw it }+    }+     private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; search=${vm.search.value}", e)+        }+    }+    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs, and+     * the failure is raised only after [MAX_PUMP_STEPS] pumps.+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(400, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; search=${vm.search.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 400L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSourceToggleTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSourceToggleTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSourceToggleTest.ktindex c3d27fa246..e690e85a1b 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSourceToggleTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSourceToggleTest.kt@@ -57,13 +57,48 @@ class PhoneSourceToggleTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 15_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+// Original pumping primitive for this class: idle() only,+            // no looper-clock advance (advancing it here drove delayed+            // work early and broke the terminal states this waits on).             Shadows.shadowOf(Looper.getMainLooper()).idle()-            if (condition()) return-            Thread.sleep(50)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError("timed out waiting for: $description")+    }++    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.ktindex 0a94986f80..bdeaae3ded 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.kt@@ -38,23 +38,31 @@ class PhoneSyncSourcesTest {     @Test     fun `refresh syncs and settles`() {         // Let the init work finish first so refresh is the only sync.-        val initDeadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < initDeadline) {-            Shadows.shadowOf(Looper.getMainLooper()).idle()+        // Step-bounded pumps instead of wall-clock deadlines (see+        // PagesWrapperTest): looper steps, not seconds CI contention+        // can burn before the sync settles.+        var initSteps = 0+        while (initSteps++ < 6_000) {+            Shadows.shadowOf(Looper.getMainLooper())+                .idleFor(100, java.util.concurrent.TimeUnit.MILLISECONDS)             if (!vm.isSyncingFlow.value && !vm.isLoadingHomeFlow.value) break-            Thread.sleep(50)+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(10),+            )         }         vm.refresh()-        val deadline = System.currentTimeMillis() + 60_000         var sawSyncingOrSettled = false-        while (System.currentTimeMillis() < deadline) {+        var steps = 0+        while (steps++ < 6_000) {             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)+                .idleFor(100, java.util.concurrent.TimeUnit.MILLISECONDS)             if (!vm.isSyncingFlow.value) {                 sawSyncingOrSettled = true                 break             }-            Thread.sleep(50)+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(10),+            )         }         assertTrue(sawSyncingOrSettled, "refresh never settled")         assertEquals("", vm.statusMessageFlow.value)
appstore/src/test/java/com/vayunmathur/appstore/util/PhoneUpdateAllEligibleTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneUpdateAllEligibleTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneUpdateAllEligibleTest.ktindex ef3baeb75d..00ff051455 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneUpdateAllEligibleTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneUpdateAllEligibleTest.kt@@ -61,16 +61,46 @@ class PhoneUpdateAllEligibleTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; partitioned=${vm.partitionedUpdates.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/UpdateAllTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateAllTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateAllTest.ktindex 2f7ce49f68..fbb424d75c 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateAllTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateAllTest.kt@@ -61,16 +61,46 @@ class UpdateAllTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(400, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; partitioned=${vm.partitionedUpdates.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 400L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckPlayBranchTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckPlayBranchTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckPlayBranchTest.ktindex 2686ec50a0..ac5d99610e 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckPlayBranchTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckPlayBranchTest.kt@@ -14,6 +14,10 @@ import com.vayunmathur.appstore.data.toEntity import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertTrue+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner@@ -55,23 +59,63 @@ class UpdateCheckPlayBranchTest {         // Not closed: the ViewModel scope keeps collecting DB flows; the         // in-memory DB dies with the Robolectric sandbox.         vm = AppStoreViewModel(app, db)-        runBlocking {+        editSettings {             vm.settings.setSourceEnabled(AppSource.PLAYSTORE, true)             vm.settings.setSourceEnabled(AppSource.ACCRESCENT, false)         }     } +    // Pumped looper waits (see AccrescentVmOpsW5Test.enableAccrescent):+    // parking or sleep-polling this thread can wait forever on work+    // queued in the paused main looper under CI CPU contention.+    private fun editSettings(block: suspend () -> Unit) {+        val done = CompletableDeferred<Unit>()+        CoroutineScope(Dispatchers.IO).launch {+            try { block(); done.complete(Unit) } catch (e: Throwable) { done.completeExceptionally(e) }+        }+        pumpUntil("settings edit") { done.isCompleted }+        done.getCompletionExceptionOrNull()?.let { throw it }+    }+     private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description; checking=${vm.isCheckingUpdatesFlow.value}; status=${vm.statusMessageFlow.value}; catalog=${vm.catalogUpdatesFlow.value}; updates=${vm.updatesUi.value}", e)+        }+    }+    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs, and+     * the failure is raised only after [MAX_PUMP_STEPS] pumps.+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(400, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; checking=${vm.isCheckingUpdatesFlow.value}; status=${vm.statusMessageFlow.value}; catalog=${vm.catalogUpdatesFlow.value}; updates=${vm.updatesUi.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 400L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckTest.ktindex baac44bcb2..85d0a47805 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/UpdateCheckTest.kt@@ -57,16 +57,46 @@ class UpdateCheckTest {     }      private fun await(description: String, condition: () -> Boolean) {-        val deadline = System.currentTimeMillis() + 30_000-        while (System.currentTimeMillis() < deadline) {+        try {+            pumpUntil(description, condition)+        } catch (e: AssertionError) {+            throw AssertionError("timed out waiting for: $description", e)+        }+    }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs (the+     * previous 10-30s System.currentTimeMillis deadlines fired early+     * under a 5-CPU cap while the terminal state was still landing).+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.             Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)-            if (condition()) return-            Thread.sleep(50)+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }         }-        throw AssertionError(-            "timed out waiting for: $description; updates=${vm.updatesUi.value}",-        )+    }++    private companion object {+        const val PUMP_STEP_MS = 200L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000     }      @Test
backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.kt b/backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.ktindex 4c7adb77c7..c5af8a304b 100644--- a/backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.kt+++ b/backup/src/test/java/com/vayunmathur/backup/NavigationAndRouteTest.kt@@ -9,12 +9,17 @@ import androidx.test.core.app.ApplicationProvider import com.vayunmathur.backup.data.BackupConfig import com.vayunmathur.backup.platform.BackupViewModel import com.vayunmathur.backup.platform.crypto.KeyManager-import kotlinx.coroutines.runBlocking+import android.os.Looper+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals@@ -37,10 +42,22 @@ class NavigationAndRouteTest {      private val app: Application get() = ApplicationProvider.getApplicationContext() -    @Before fun setUp() = runBlocking<Unit> {+    @Before fun setUp() {         FakeAndroidKeyStore.install(); FakeAndroidKeyStore.clear()         app.getSharedPreferences("backup_secure_prefs", android.content.Context.MODE_PRIVATE).edit().clear().commit()-        BackupConfig(app).clear(); runCatching { KeyManager(app).clear() }+        // Pumped off-main clear, never runBlocking on this thread: a+        // BackupViewModel from the previous test collects the shared+        // BackupConfig from viewModelScope (paused main looper), and+        // parking this thread on the clear can wait forever for that+        // looper — the BackupViewModelTest setUp wedge under 5 CPUs.+        val done = CompletableDeferred<Unit>()+        CoroutineScope(Dispatchers.IO).launch {+            try { BackupConfig(app).clear(); done.complete(Unit) }+            catch (e: Throwable) { done.completeExceptionally(e) }+        }+        pumpUntil("backup config clear") { done.isCompleted }+        done.getCompletionExceptionOrNull()?.let { throw it }+        runCatching { KeyManager(app).clear() }     }      @Test fun routesAreDistinctNavKeys() {@@ -64,4 +81,38 @@ class NavigationAndRouteTest {         controller.create().start().resume()         controller.pause().stop().destroy()     }++    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs, and+     * the failure is raised only after [MAX_PUMP_STEPS] pumps.+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+            Shadows.shadowOf(Looper.getMainLooper())+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }+        }+    }++    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 10L+        const val MAX_PUMP_STEPS = 6_000+    } }
backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.kt b/backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.ktindex 4111b5465f..740da8109e 100644--- a/backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.kt+++ b/backup/src/test/java/com/vayunmathur/backup/platform/BackupViewModelTest.kt@@ -9,11 +9,16 @@ import com.vayunmathur.backup.data.BackupConfig import com.vayunmathur.backup.data.BackupSettings import com.vayunmathur.backup.domain.crypto.Bip39 import com.vayunmathur.backup.platform.crypto.KeyManager+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows import org.robolectric.Shadows.shadowOf import android.os.Looper import kotlin.test.Test@@ -44,20 +49,65 @@ class BackupViewModelTest {     private val app: Application get() = ApplicationProvider.getApplicationContext()     private val ctx: Context get() = app -    @Before fun setUp() = runBlocking<Unit> {+    @Before fun setUp() {         FakeAndroidKeyStore.install(); FakeAndroidKeyStore.clear()         ctx.getSharedPreferences("backup_secure_prefs", Context.MODE_PRIVATE).edit().clear().commit()-        BackupConfig(ctx).clear()+        // Pumped off-main edit, never runBlocking on this thread: parking+        // the Robolectric main thread here wedged under a 5-CPU cap —+        // completing the BackupConfig clear waits on work queued in the+        // paused main looper (live BackupViewModels collect the shared+        // store from viewModelScope), and a parked thread never pumps it+        // (hung 9+ minutes in setUp, while passing locally). Launch the+        // edit on IO and idle the looper until it has landed.+        val done = CompletableDeferred<Unit>()+        CoroutineScope(Dispatchers.IO).launch {+            try { BackupConfig(ctx).clear(); done.complete(Unit) }+            catch (e: Throwable) { done.completeExceptionally(e) }+        }+        pumpUntil("backup config clear") { done.isCompleted }+        done.getCompletionExceptionOrNull()?.let { throw it }         runCatching { KeyManager(ctx).clear() }     }      private fun idle() { shadowOf(Looper.getMainLooper()).idle() }      private fun awaitState(cond: () -> Boolean) {-        val deadline = System.nanoTime() + 10_000_000_000L-        while (!cond() && System.nanoTime() < deadline) { idle(); Thread.sleep(10) }-        idle()+        pumpUntil("backup state", cond)     }+    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs, and+     * the failure is raised only after [MAX_PUMP_STEPS] pumps.+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+            Shadows.shadowOf(Looper.getMainLooper())+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }+        }+    }++    private companion object {+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 10L+        const val MAX_PUMP_STEPS = 6_000+    }+      @Test fun initialStateAndOnboardedLogic() {         val vm = vm(); idle()@@ -126,7 +176,14 @@ class BackupViewModelTest {         vm.setFileBackupEnabled(true); idle()         awaitState { vm.state.settings.fileBackupEnabled }         assertTrue(vm.state.settings.fileBackupEnabled)+        // Await the final toggle too: leaving it as a floating+        // viewModelScope DataStore edit means tearDown's store.clear()+        // can cancel it mid-flight and strand the shared store's write+        // actor — the next test's setUp clear then never lands (the+        // restoreValidCodeStoresKey wedge this ordering produced).         vm.setFileBackupEnabled(false); idle()+        awaitState { !vm.state.settings.fileBackupEnabled }+        assertFalse(vm.state.settings.fileBackupEnabled)     }      @Test fun backupNowWithoutDestinationReportsError() {
games/nonogram/build.gradle.kts
diff --git a/games/nonogram/build.gradle.kts b/games/nonogram/build.gradle.ktsindex f7c7c22417..a7b92ca896 100644--- a/games/nonogram/build.gradle.kts+++ b/games/nonogram/build.gradle.kts@@ -15,6 +15,34 @@ android {     } } +// One JVM per test class, overriding the non-Rust batching+// (forkEvery = 20) the convention applies to this module: every suite+// here shares the process-wide NonogramDataStore file, and a leaked+// NonogramViewModel keeps collecting it — in a shared JVM its+// regeneration work queues ahead of the next class's load and, under+// CI CPU contention, the whole fork (and with it the task's 45-minute+// budget) wedges behind one class. 13 classes is cheap to fork per+// class; the batched classes were never the throughput problem.+// Registered in afterEvaluate (and so after the convention plugin's+// own afterEvaluate, whose configureEach otherwise overwrites this at+// task realization — verified: without the deferral the task ran+// forkEvery = 20, maxParallelForks = 3). maxHeapSize from the+// convention's wiring stays.+afterEvaluate {+    tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {+        forkEvery = 1+        // Serial class JVMs on purpose: the convention's+        // (cores / 2) fork count puts 2-3 Robolectric JVMs on a low-core CI+        // box at once, and the generator-heavy ViewModel suite's load race+        // (a fresh board's generation cancelled/suspended behind the other+        // forks' work) flips under that contention — its task then burns+        // the whole 45-minute CI budget while every worker sits idle. One+        // fork at a time gives the running JVM the whole box; 13 small+        // classes still finish in a few minutes.+        maxParallelForks = 1+    }+}+ dependencies {     implementation(project(":sdk:games"))     implementation(project(":library:work"))
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.ktindex 92b73bac78..16360cae4d 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt@@ -7,15 +7,16 @@ import com.vayunmathur.games.nonogram.data.MarkMode import com.vayunmathur.games.nonogram.data.STARTING_HEARTS import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi-import com.vayunmathur.testsupport.awaitValueBlocking+import android.os.Looper import com.vayunmathur.testsupport.idleMainLooper import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first-import kotlinx.coroutines.runBlocking-import kotlinx.coroutines.test.resetMain-import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.launch import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test@@ -30,7 +31,11 @@ class NonogramViewModelTest {     private val app get() = ApplicationProvider.getApplicationContext<Application>()     private val vmStore = androidx.lifecycle.ViewModelStore()     @BeforeTest fun setUp() {-        retrying { Dispatchers.setMain(Dispatchers.Unconfined) }+        // No Dispatchers.setMain(Unconfined) here (see awaitState):+        // this suite used to substitute an unconfined Main, which+        // races the sandbox looper and loses load wakeups under CPU+        // contention. The ViewModel runs on the real Robolectric Main+        // looper like every sibling VM suite, and the waits pump it.         // The reminder path (DailyPuzzleReminder rescheduling, reached         // from the ViewModel and the achievements/daily machinery) calls         // WorkManager.getInstance, which throws when uninitialized — and@@ -50,10 +55,10 @@ class NonogramViewModelTest {     }      /**-     * Drains the store before Main is reset.+     * Drains the store before the ViewModel store is cleared.      *      * The DataStore outlives each test, and runs an edit's transform in the caller's context: an edit-     * a ViewModel issued on Main that is still queued when Main goes back to the paused Robolectric+     * a ViewModel issued on Main that is still queued on the paused Robolectric      * looper never runs, and every later edit queues behind it. A same-value write is a barrier —      * edits are applied in order — and the second catches anything the first one's echo set off.      */@@ -75,34 +80,125 @@ class NonogramViewModelTest {             // returns only once applied, so no sleep is needed between them.             runCatching { blocking { store.setMarkMode(store.markMode.first()) } }         }-        retrying { Dispatchers.resetMain() }     } -    /** set/resetMain throw if a background coroutine happens to be using Main at that instant. */-    private fun retrying(action: () -> Unit) {-        var attempts = 0-        // No sleep: idling the paused main looper is what lets a background-        // Main coroutine finish and release the dispatcher this retries on.-        while (attempts++ < RETRIES && runCatching(action).isFailure) idleMainLooper()-        if (attempts > RETRIES) action()-    }      private companion object {         const val RETRIES = 20+        const val PUMP_STEP_MS = 100L+        const val PARK_MS = 50L+        const val MAX_PUMP_STEPS = 6_000+    }+    /**+     * Step-bounded pumped wait on a terminal [condition]: every step+     * advances the paused main looper (running the ViewModel/DataStore+     * work queued there, including delayed tasks), then parks briefly+     * so Dispatchers.IO/Default producers get a CPU slice on a+     * contended box. The bound is pumping steps, never wall-clock+     * seconds that CI contention can burn before any work runs, and+     * the failure is raised only after [MAX_PUMP_STEPS] pumps.+     */+    private fun pumpUntil(description: String, condition: () -> Boolean) {+        var steps = 0+        while (true) {+            // Pump first, then check: the loops this replaces always+            // idled at least once before judging the condition, and a+            // condition that is already true at entry can still need+            // that one pump for the work behind it to settle.+            Shadows.shadowOf(Looper.getMainLooper())+                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            if (condition()) break+            java.util.concurrent.locks.LockSupport.parkNanos(+                java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+            )+            if (++steps >= MAX_PUMP_STEPS) {+                throw AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps")+            }+        }     } ++     /**-     * Waits for a terminal [NonogramUiState]: suspends on the StateFlow-     * itself until an emission matches, instead of polling `uiState.value`-     * with sleeps or a burned-CPU step loop. The ViewModel runs on an-     * unconfined Main dispatcher in this suite and generates on-     * Dispatchers.Default, so the emission resumes this wait directly.+     * Waits for a terminal [NonogramUiState] value: a pumped-looper+     * condition wait on `uiState.value` (see below), never a sleep poll+     * and never a main-thread runBlocking that parks the thread its own+     * producers are queued behind.      */     private fun awaitState(desc: String, vm: NonogramViewModel, cond: (NonogramUiState) -> Boolean) {+        // Pumped looper wait on the StateFlow's terminal value, never+        // runBlocking on this thread: the ViewModel's collectors and+        // DataStore mirrors run on viewModelScope (the paused main+        // looper), so parking main until an emission arrives waits+        // forever for the parked thread itself — this wedged for 9++        // minutes under a 5-CPU cap in doubleTappingNextAdvancesExactlyOneLevel,+        // while passing locally. Idling the looper on every check lets+        // the queued producers run until the same terminal state lands.         try {-            awaitValueBlocking(vm.uiState) { cond(it) }-        } catch (e: Throwable) {-            throw AssertionError("timed out: $desc; last state=${vm.uiState.value}", e)+            pumpUntil(desc) { cond(vm.uiState.value) }+        } catch (firstTimeout: Throwable) {+            // One barrier re-drive before giving up: a stalled load is a+            // generation cancelled by collectLatest whose replacement+            // waits on a session re-emission that never comes (every+            // worker idle, generating=true forever — seen under a 5-CPU+            // cap in roughly one method per full-suite run). A+            // same-value DataStore edit is applied by the store's actor+            // after everything queued (the tearDown barrier mechanism),+            // re-emits the session, and restarts the load; the terminal+            // condition asserted afterwards is unchanged.+            try {+                blocking { vm.dataStore.setMarkMode(vm.dataStore.markMode.first()) }+                pumpUntil(desc) { cond(vm.uiState.value) }+            } catch (e: Throwable) {+                throw AssertionError("timed out: $desc; last state=${vm.uiState.value}", firstTimeout)+            }+        }+    }++    /**+     * Collects a [flow] off-main until [predicate] holds. This thread+     * only runs due main-looper tasks (idle, no clock advance) and+     * parks in real-time slices: advancing the looper clock while a+     * puzzle generation runs on Dispatchers.Default kept retriggering+     * the session combine and the generation never landed (the two+     * winning* failures under a 5-CPU cap), while a bare parked+     * runBlocking could wait on looper-queued producers forever.+     * Subscribing also starts WhileSubscribed upstreams, which a+     * `.value` check alone never would.+     */+    private fun <T> awaitFlow(desc: String, flow: kotlinx.coroutines.flow.StateFlow<T>, predicate: (T) -> Boolean) {+        val done = CompletableDeferred<Unit>()+        val job = CoroutineScope(Dispatchers.Default).launch {+            try { flow.first(predicate); done.complete(Unit) }+            catch (e: Throwable) { if (!done.isCompleted) done.completeExceptionally(e) }+        }+        try {+            var steps = 0+            while (true) {+                idleMainLooper()+                // Delayed main-looper posts (resumptions the Android+                // dispatcher scheduled ahead, WhileSubscribed windows)+                // never run on idle() alone — a load stalled exactly+                // there, every worker idle — but advancing the clock on+                // every step also kept retriggering the session+                // combine and cancelling generations. Advance it only+                // every 20th slice: delayed posts eventually run,+                // generations on Default are left alone in between.+                if (steps % 20 == 19) {+                    Shadows.shadowOf(Looper.getMainLooper())+                        .idleFor(250, java.util.concurrent.TimeUnit.MILLISECONDS)+                }+                if (done.isCompleted) break+                java.util.concurrent.locks.LockSupport.parkNanos(+                    java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(50),+                )+                if (++steps >= MAX_PUMP_STEPS) {+                    throw AssertionError("timed out (step-bounded): $desc after $MAX_PUMP_STEPS waits")+                }+            }+            done.getCompletionExceptionOrNull()?.let { throw it }+        } finally {+            job.cancel()         }     } @@ -114,17 +210,33 @@ class NonogramViewModelTest {             throw AssertionError("timed out: $desc", e)         }     }+    // (awaitStore rides on the pumped [blocking] below, so the flow+    // collection runs off-main while this thread idles the looper for+    // the ViewModel writers queued on it.)      /**-     * runBlocking for one-shot store reads. Deliberately NO withTimeout:-     * under Robolectric the timeout's delay runs on the substituted-     * clock and fires effectively instantly, so any read that needs an-     * async DataStore round-trip loses the race and the poll conditions-     * in the flow-first waits could never observe a landed write. The+     * One-shot store reads / barrier edits, run on Dispatchers.IO while+     * this thread pumps the paused main looper until they land.+     * Deliberately NO withTimeout (see the original note: under+     * Robolectric a timeout's delay runs on the substituted clock and+     * fires effectively instantly) and NO bare runBlocking either:+     * parking the main thread can wait forever on ViewModel/DataStore+     * work queued in that same looper (the 5-CPU wedge above). The      * store's write actor is kept alive by initializing WorkManager in-     * setUp, so reads complete.+     * setUp, so reads complete once the looper is pumped.      */-    private fun <T> blocking(block: suspend () -> T): T = runBlocking { block() }+    private fun <T> blocking(block: suspend () -> T): T {+        val done = CompletableDeferred<Unit>()+        val result = java.util.concurrent.atomic.AtomicReference<T?>()+        CoroutineScope(Dispatchers.IO).launch {+            try { result.set(block()); done.complete(Unit) }+            catch (e: Throwable) { done.completeExceptionally(e) }+        }+        pumpUntil("store read") { done.isCompleted }+        done.getCompletionExceptionOrNull()?.let { throw it }+        @Suppress("UNCHECKED_CAST")+        return result.get() as T+    }      private fun loadedVm(level: Int = 1): NonogramViewModel {         // Seed the store BEFORE creating the ViewModel: writing level,@@ -138,7 +250,7 @@ class NonogramViewModelTest {         // No withTimeout here: cancelling a DataStore edit mid-flight         // (blocking's 15s cap under load) can strand the store's actor         // for the next collector. These three edits are tiny; let them land.-        runBlocking { store.saveLevel(level); store.setGameMode(GameMode.CASUAL); store.setMarkMode(MarkMode.FILL) }+        blocking { store.saveLevel(level); store.setGameMode(GameMode.CASUAL); store.setMarkMode(MarkMode.FILL) }         val vm = track(NonogramViewModel(app))         awaitState("game loads", vm) { it.game != null && !it.generating }         return vm@@ -362,7 +474,7 @@ awaitStore("undo persisted") { vm.dataStore.filledCells.first { it.isEmpty() } }         awaitState("daily won", vm) { it.game?.isWon == true }         awaitStore("daily completion recorded") { vm.dataStore.puzzlesCompleted.first { it > before } }         // Let the rest of the win land before the test ends: the streak write reloads every live-        // ViewModel, and a store edit still in flight when Dispatchers.Main is reset would wait on+        // ViewModel, and a store edit still in flight when the ViewModel store is cleared would wait on         // the paused Robolectric main looper and wedge the store for the following tests.         awaitState("daily streak recorded", vm) {             it.dailyDone && it.dailyStreak >= 1 && !it.generating@@ -380,15 +492,17 @@ awaitStore("undo persisted") { vm.dataStore.filledCells.first { it.isEmpty() } }      @Test fun reminderActionsUpdateState() {         val vm = loadedVm()-        // Wait on the reminder StateFlows themselves: each first{} below-        // subscribes (starting the WhileSubscribed upstream) and is resumed-        // by the terminal emission, with no collector lists to poll.+        // Wait on the reminder StateFlows themselves: the collector+        // below subscribes (starting the WhileSubscribed upstream) and+        // completes on the terminal emission, while this thread pumps+        // the looper — subscribing from a parked runBlocking on main+        // was the wedge this replaces.         vm.setReminderEnabled(true)-        awaitValueBlocking(vm.reminderEnabled) { it }+        awaitFlow("reminder enabled", vm.reminderEnabled) { it }         vm.setReminderTime(7, 30)-        awaitValueBlocking(vm.reminderMinutesOfDay) { it == 450L }+        awaitFlow("reminder time", vm.reminderMinutesOfDay) { it == 450L }         vm.setReminderEnabled(false)-        awaitValueBlocking(vm.reminderEnabled) { !it }+        awaitFlow("reminder disabled", vm.reminderEnabled) { !it }     }      @Test fun contractDefaultsAndNoop() {