Modern Apps git

← Modern-Apps.git

health: full suite completes - cursor-blink stall, today-page crash, recipe flake

Commit
01983a0776e634648d26be8bf454f55242e69b07
Author
Vayun Mathur <[email protected]>
When
2026-11-21 20:35 UTC (14 days ago)
Parents
284f2ff
Three unrelated suite killers. (1) The shared
DeterministicAwait ended with advanceUntilIdle(), which can
never return when the composition hosts an infinitely
rescheduling task - a focused field's cursor blink spun a
fork at 109% CPU forever, wedging its whole 20-class batch
(the 2h 'stall'); the settle now steps the same bounded
virtual window as the wait. (2) HealthTodayW6Test NPE'd:
production chart/vitals paths reached for the HealthAPI
singleton instead of the injected repository - they use the
repository now (singleton access fails with an actionable
message, not an NPE). (3) RecipeEditorFlowTest awaited an IO
hop with a 1s wall-clock sleep-poll, starved in bulk; it now
awaits terminal semantics signals.

Verified: full health suite 631 tests, 0 failures, completes
(was: never finished); the catalog-picker class runs in
seconds instead of spinning.

Diff

build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt
diff --git a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.ktindex 6e447dae24..4cd1798aab 100644--- a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt+++ b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt@@ -104,7 +104,14 @@ fun ComposeContentTestRule.awaitSemantics(description: String, condition: () ->         condition()     }     idleMainLooper()-    mainClock.scheduler.advanceUntilIdle()+    // Bounded settle, never advanceUntilIdle(): a composition can host an+    // infinitely self-rescheduling scheduler task (a focused text field's+    // cursor blink, an infinite animation), and advancing until idle then+    // never returns — the test JVM spins at 100% CPU and its whole+    // forkEvery batch (and the Gradle task) never completes. Stepping the+    // same bounded window as the wait above runs every timer that could+    // still be queued without betting on the scheduler ever going idle.+    mainClock.scheduler.advanceTimeBy(SCHEDULER_ADVANCE_SECONDS.seconds)     idleMainLooper()     check(condition()) { "terminal semantics state not reached: $description" } }
health/src/main/java/com/vayunmathur/health/data/HealthAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthAPI.kt b/health/src/main/java/com/vayunmathur/health/data/HealthAPI.ktindex a8c9dc175a..786f03c425 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthAPI.kt@@ -40,7 +40,7 @@ object HealthAPI {     private var repository: HealthRepository? = null      /** Backward-compatible accessor — callers that read `HealthAPI.db` still compile. */-    val db get() = repository!!.database+    val db get() = repo().database      fun init(healthConnectClient: HealthConnectClient, context: Context, repository: HealthRepository) {         this.healthConnectClient = healthConnectClient@@ -59,7 +59,10 @@ object HealthAPI {         preferences = context.getSharedPreferences("sync", Context.MODE_PRIVATE)     } -    private fun repo(): HealthRepository = repository!!+    private fun repo(): HealthRepository = checkNotNull(repository) {+        "HealthAPI used before init: the host must call init/initLocal first " ++            "(MainActivity does this in onCreateBeforeContent)."+    }      suspend fun lastRecord(recordType: RecordType): Record? {         return repo().getLastRecord(recordType)@@ -330,22 +333,45 @@ object HealthAPI {             startTime: Instant,             endTime: Instant,             period: PeriodType+    ): List<Tuple3<Long, Double, Double>> =+        getListOfAverages(repo(), recordType, startTime, endTime, period)++    suspend fun getListOfSums(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant,+            period: PeriodType+    ): List<Tuple3<Long, Double, Double>> =+        getListOfSums(repo(), recordType, startTime, endTime, period)++    /**+     * Repository-taking forms: pure Room reads, so callers that already hold+     * a [HealthRepository] (the ViewModel, chart math) use theirs instead of+     * requiring this singleton to be initialised first.+     */+    internal suspend fun getListOfAverages(+            repository: HealthRepository,+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant,+            period: PeriodType     ): List<Tuple3<Long, Double, Double>> = aggregateByPeriod(         recordType, startTime, endTime, period,-        dailyQuery = { t, s, e -> repo().getDailyAvgs(t, s, e) },-        hourlyQuery = { t, s, e -> repo().getHourlyAvgs(t, s, e) },+        dailyQuery = { t, s, e -> repository.getDailyAvgs(t, s, e) },+        hourlyQuery = { t, s, e -> repository.getHourlyAvgs(t, s, e) },         combine = ::combineForAverages,     ) -    suspend fun getListOfSums(+    internal suspend fun getListOfSums(+            repository: HealthRepository,             recordType: RecordType,             startTime: Instant,             endTime: Instant,             period: PeriodType     ): List<Tuple3<Long, Double, Double>> = aggregateByPeriod(         recordType, startTime, endTime, period,-        dailyQuery = { t, s, e -> repo().getDailySums(t, s, e) },-        hourlyQuery = { t, s, e -> repo().getHourlySums(t, s, e) },+        dailyQuery = { t, s, e -> repository.getDailySums(t, s, e) },+        hourlyQuery = { t, s, e -> repository.getHourlySums(t, s, e) },         // Weekly/monthly buckets of daily sums must be summed, not averaged:         // averaging reported e.g. mean daily steps as the month total.         combine = ::combineForSums,
health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt b/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.ktindex 672ea2cc24..1055f897a3 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt@@ -88,20 +88,21 @@ internal object HealthChartData {      internal suspend fun queryChartPairs(         config: HealthMetricConfig,+        repository: HealthRepository,         startTime: kotlin.time.Instant,         endTimeNow: kotlin.time.Instant,         periodType: HealthAPI.PeriodType,         periodType2: HealthAPI.PeriodType,     ): Pair<List<Tuple3<Long, Double, Double>>, List<Tuple3<Long, Double, Double>>> {         val rawPairs = if (config.isLineChart) {-            HealthAPI.getListOfAverages(config.recordType, startTime, endTimeNow, periodType)+            HealthAPI.getListOfAverages(repository, config.recordType, startTime, endTimeNow, periodType)         } else {-            HealthAPI.getListOfSums(config.recordType, startTime, endTimeNow, periodType)+            HealthAPI.getListOfSums(repository, config.recordType, startTime, endTimeNow, periodType)         }         val rawPairsHistory = if (config.isLineChart) {-            HealthAPI.getListOfAverages(config.recordType, startTime, endTimeNow, periodType2)+            HealthAPI.getListOfAverages(repository, config.recordType, startTime, endTimeNow, periodType2)         } else {-            HealthAPI.getListOfSums(config.recordType, startTime, endTimeNow, periodType2)+            HealthAPI.getListOfSums(repository, config.recordType, startTime, endTimeNow, periodType2)         }         // Height is stored in meters but its config/goal/unit are centimeters         // (175 cm); every other metric stores in its display unit already.@@ -301,10 +302,11 @@ internal object HealthChartData {      /** Last night's sleep in minutes, or null when the latest record is older than that. */     internal suspend fun lastNightSleepMinutes(+        repository: HealthRepository,         lookback: java.time.Duration,         hoursToMinutes: Long,     ): Long? =-        HealthAPI.lastRecord(RecordType.Sleep)?.let { record ->+        repository.getLastRecord(RecordType.Sleep)?.let { record ->             val todayStart = java.time.LocalDate.now()                 .atStartOfDay(java.time.ZoneId.systemDefault()).toInstant()             if (record.endTime.isAfter(todayStart.minus(lookback))) {
health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt b/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.ktindex 0ef53d0416..071c1ab8dc 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt@@ -173,39 +173,39 @@ class HealthViewModel(     /** Dashboard vitals: the four Today shows plus the other point-in-time vitals. */     private suspend fun CoroutineScope.loadVitalsMetrics() {         launch {-            val v = HealthAPI.lastRecord(RecordType.OxygenSaturation)?.value+            val v = repository.getLastRecord(RecordType.OxygenSaturation)?.value             _mainPageMetrics.update { it.copy(spo2 = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.RespiratoryRate)?.value+            val v = repository.getLastRecord(RecordType.RespiratoryRate)?.value             _mainPageMetrics.update { it.copy(br = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.HeartRateVariabilityRmssd)?.value+            val v = repository.getLastRecord(RecordType.HeartRateVariabilityRmssd)?.value             _mainPageMetrics.update { it.copy(hrv = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.RestingHeartRate)?.value?.toLong()+            val v = repository.getLastRecord(RecordType.RestingHeartRate)?.value?.toLong()             _mainPageMetrics.update { it.copy(rhr = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.SkinTemperature)?.value+            val v = repository.getLastRecord(RecordType.SkinTemperature)?.value             _mainPageMetrics.update { it.copy(skinTemp = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.Vo2Max)?.value+            val v = repository.getLastRecord(RecordType.Vo2Max)?.value             _mainPageMetrics.update { it.copy(vo2Max = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.BloodGlucose)?.value+            val v = repository.getLastRecord(RecordType.BloodGlucose)?.value             _mainPageMetrics.update { it.copy(bloodGlucose = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.BloodPressure)?.let { it.value to it.secondaryValue }+            val v = repository.getLastRecord(RecordType.BloodPressure)?.let { it.value to it.secondaryValue }             _mainPageMetrics.update { it.copy(bloodPressure = v) }         }         launch {-            val v = HealthChartData.lastNightSleepMinutes(SLEEP_LOOKBACK, MINUTES_PER_HOUR)+            val v = HealthChartData.lastNightSleepMinutes(repository, SLEEP_LOOKBACK, MINUTES_PER_HOUR)             _mainPageMetrics.update { it.copy(sleepMinutes = v) }         }     }@@ -213,27 +213,27 @@ class HealthViewModel(     /** Body page point-in-time metrics: height, weight and body composition. */     private suspend fun CoroutineScope.loadBodyMetrics() {         launch {-            val v = HealthAPI.lastRecord(RecordType.Height)?.value+            val v = repository.getLastRecord(RecordType.Height)?.value             _mainPageMetrics.update { it.copy(height = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.Weight)?.value+            val v = repository.getLastRecord(RecordType.Weight)?.value             _mainPageMetrics.update { it.copy(weight = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.BodyFat)?.value+            val v = repository.getLastRecord(RecordType.BodyFat)?.value             _mainPageMetrics.update { it.copy(bodyFat = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.BoneMass)?.value+            val v = repository.getLastRecord(RecordType.BoneMass)?.value             _mainPageMetrics.update { it.copy(boneMass = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.LeanBodyMass)?.value+            val v = repository.getLastRecord(RecordType.LeanBodyMass)?.value             _mainPageMetrics.update { it.copy(leanBodyMass = v) }         }         launch {-            val v = HealthAPI.lastRecord(RecordType.BodyWaterMass)?.value+            val v = repository.getLastRecord(RecordType.BodyWaterMass)?.value             _mainPageMetrics.update { it.copy(bodyWaterMass = v) }         }     }@@ -261,7 +261,7 @@ class HealthViewModel(             val endTimeNow = if (Clock.System.now() < endTime) Clock.System.now() else endTime              val (rawPairs, rawPairsHistory) = HealthChartData.queryChartPairs(-                config, startTime, endTimeNow, periodType, periodType2,+                config, repository, startTime, endTimeNow, periodType, periodType2,             )             val (mappedChart, mappedSecondaryChart) = HealthChartData.mapChartSeries(                 config, selectedTab, startDate, rawPairs, is24Hour(getApplication()),
health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.kt b/health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.ktindex 42ec7945cc..2b54c97547 100644--- a/health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.kt+++ b/health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.kt@@ -3,6 +3,7 @@ package com.vayunmathur.health.ui import android.app.Application import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextInput@@ -21,10 +22,10 @@ import com.vayunmathur.health.data.HealthAPI import com.vayunmathur.health.platform.HealthViewModel import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.databases+import com.vayunmathur.testsupport.awaitSemantics import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals-import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking import org.junit.Rule import org.junit.runner.RunWith@@ -71,21 +72,21 @@ class RecipeEditorFlowTest {         seedRecipe()         val backStack = NavBackStack<Route>(arrayOf(Route.Today, Route.RecipeEditor("flow-recipe-1")))         rule.setContent { RecipeEditorPage(backStack, vm(), "flow-recipe-1") }-        rule.waitForIdle()+        // The editor loads on Dispatchers.IO and publishes on Main; wait on+        // the terminal semantics state, not on idle (idle can fire while the+        // IO load is still in flight, and a sleep-poll spends a wall-clock+        // budget that a loaded batched JVM cannot meet).+        rule.awaitSemantics("recipe ingredients loaded") {+            rule.onAllNodesWithText("Flow Rice", substring = true).fetchSemanticsNodes().isNotEmpty()+        }         rule.onNodeWithText("Flow Rice", substring = true).assertIsDisplayed()         // Rename through the name field (loaded name is the field value).         rule.onNodeWithText("Flow Bowl").performTextInput("Flow Bowl v2")         rule.waitForIdle()         rule.onNodeWithText("Save Recipe", substring = true).performClick()-        rule.waitForIdle()-        // Save completes asynchronously and pops to Today.-        var popped = false-        repeat(100) {-            if (backStack.last() == Route.Today) { popped = true; return@repeat }-            Thread.sleep(10)-            rule.waitForIdle()-        }-        assertTrue(popped)+        // Save completes asynchronously (Room writes, then a Main hop) and+        // pops to Today: that pop is the terminal signal.+        rule.awaitSemantics("save pops to Today") { backStack.last() == Route.Today }         assertEquals(Route.Today, backStack.last())     } @@ -94,7 +95,9 @@ class RecipeEditorFlowTest {         seedRecipe("2")         val backStack = NavBackStack<Route>(arrayOf(Route.Today, Route.RecipeEditor("flow-recipe-2")))         rule.setContent { RecipeEditorPage(backStack, vm(), "flow-recipe-2") }-        rule.waitForIdle()+        rule.awaitSemantics("recipe ingredients loaded") {+            rule.onAllNodesWithText("Flow Rice", substring = true).fetchSemanticsNodes().isNotEmpty()+        }         rule.onNodeWithText("Flow Rice", substring = true).performClick()         rule.waitForIdle()         rule.onNodeWithText("Set Quantity for Flow Rice").assertExists()
health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.kt b/health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.ktindex 4f544c053b..b4d2d66cc3 100644--- a/health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.kt+++ b/health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.kt@@ -64,11 +64,11 @@ class HealthChartData2Test {         ))         val start = kotlin.time.Instant.fromEpochMilliseconds(at.toEpochMilli() - 86_400_000)         val end = kotlin.time.Instant.fromEpochMilliseconds(at.toEpochMilli() + 86_400_000)-        val (barPairs, _) = HealthChartData.queryChartPairs(HealthMetricConfig.STEPS, start, end, HealthAPI.PeriodType.Daily, HealthAPI.PeriodType.Daily)+        val (barPairs, _) = HealthChartData.queryChartPairs(HealthMetricConfig.STEPS, repo(), start, end, HealthAPI.PeriodType.Daily, HealthAPI.PeriodType.Daily)         assertTrue(barPairs.any { it.second == 1200.0 })-        val (linePairs, _) = HealthChartData.queryChartPairs(HealthMetricConfig.HEART_RATE, start, end, HealthAPI.PeriodType.Daily, HealthAPI.PeriodType.Daily)+        val (linePairs, _) = HealthChartData.queryChartPairs(HealthMetricConfig.HEART_RATE, repo(), start, end, HealthAPI.PeriodType.Daily, HealthAPI.PeriodType.Daily)         assertTrue(linePairs.any { it.second == 72.0 })-        val (bpPairs, _) = HealthChartData.queryChartPairs(HealthMetricConfig.BLOOD_PRESSURE, start, end, HealthAPI.PeriodType.Daily, HealthAPI.PeriodType.Daily)+        val (bpPairs, _) = HealthChartData.queryChartPairs(HealthMetricConfig.BLOOD_PRESSURE, repo(), start, end, HealthAPI.PeriodType.Daily, HealthAPI.PeriodType.Daily)         assertTrue(bpPairs.isEmpty() || bpPairs.all { it.second >= 0.0 })     } 
health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt b/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.ktindex 064a986dee..1bd96673f6 100644--- a/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt+++ b/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt@@ -215,7 +215,7 @@ class HealthChartDataTest {         val repo = repository()         HealthAPI.initLocal(context, repo)         repo.deleteByIds(listOf("sleep-chart-1", "sleep-chart-old"))-        assertNull(HealthChartData.lastNightSleepMinutes(java.time.Duration.ofHours(12), 60L))+        assertNull(HealthChartData.lastNightSleepMinutes(repo, java.time.Duration.ofHours(12), 60L))     }      @Test@@ -232,7 +232,7 @@ class HealthChartDataTest {                 )             )         )-        assertEquals(450L, HealthChartData.lastNightSleepMinutes(java.time.Duration.ofHours(24), 60L))+        assertEquals(450L, HealthChartData.lastNightSleepMinutes(repo, java.time.Duration.ofHours(24), 60L))     }      @Test@@ -249,7 +249,7 @@ class HealthChartDataTest {                 )             )         )-        assertNull(HealthChartData.lastNightSleepMinutes(java.time.Duration.ofHours(12), 60L))+        assertNull(HealthChartData.lastNightSleepMinutes(repo, java.time.Duration.ofHours(12), 60L))     }      @Test