Modern Apps git

← Modern-Apps.git

health: shrunken Health Connect records no longer leave phantom samples

Commit
773768a9716dd50fa6c8638de3b85aa9b4b71fde
Author
Vayun Mathur <[email protected]>
When
2026-12-01 02:58 UTC (5 days ago)
Parents
821988a
A multi-sample record's identity is its id and its sample
list is the complete current state, but the DAO upsert was
per-row REPLACE keyed by id-index: when an upstream record
shrank (heart-rate samples 60/90/120 -> 70), only the
present indices were replaced and the deleted samples
survived forever, still feeding averages, min/max and
charts. Full deletions were handled by-id; shrinking
updates were not.

upsert now goes through HealthDao.replaceRecords: delete all
rows for the carried ids, then insert, in one transaction so
observers never see the record vanish. Every caller already
supplies a record's whole sample list. No schema change;
existing phantom rows heal on each record's next update. Two
regression tests (DAO transaction + repository/sync level)
failed pre-fix. Recent aggregation/nutrition fixes were not
re-touched. Verified: :health:testDevUnitTest 650 tests pass;
lint errors are pre-existing on untouched files (the fix was
kept under the 800-line FileLength limit Record.kt sits at).

Diff

health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.ktindex fa1b75cbee..bae2ef7ae5 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -76,7 +76,12 @@ class HealthRepository private constructor(context: Context) :         endTime: Long,     ): List<HealthDao.HourlySum> = dao.getHourlyAvgs(type, startTime, endTime) -    suspend fun upsert(records: List<Record>) = dao.upsert(records)+    /**+     * Full replacement per record id (see [HealthDao.replaceRecords]): an+     * updated multi-sample record with fewer samples must not leave its+     * removed samples behind. All record writes go through here.+     */+    suspend fun upsert(records: List<Record>) = dao.replaceRecords(records)     suspend fun deleteByIds(ids: List<String>) = dao.deleteByIds(ids)      // ------------------------------------------------------------------
health/src/main/java/com/vayunmathur/health/data/Record.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/Record.kt b/health/src/main/java/com/vayunmathur/health/data/Record.ktindex 5dc4133852..2de3424e99 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -11,6 +11,7 @@ import androidx.room3.OnConflictStrategy import androidx.room3.PrimaryKey import androidx.room3.Query import androidx.room3.RoomDatabase+import androidx.room3.Transaction import androidx.room3.Update import androidx.room3.Delete import androidx.room3.migration.Migration@@ -150,6 +151,17 @@ interface HealthDao {     @Query("DELETE FROM Record WHERE id IN (:ids)")     suspend fun deleteByIds(ids: List<String>) +    // Full replacement per id, in one transaction: a plain upsert only replaces+    // `"$id-$index"` rows present in the batch, so samples removed upstream from a+    // multi-sample record (heart-rate, skin-temperature) would survive as phantoms.+    // Every caller supplies a record's whole sample list, never a partial index.+    @Transaction+    suspend fun replaceRecords(records: List<Record>) {+        if (records.isEmpty()) return+        deleteByIds(records.map { it.id }.distinct())+        upsert(records)+    }+     @Query("SELECT * FROM Record WHERE type = :type ORDER BY startTime DESC")     fun getRecordsFlow(type: RecordType): Flow<List<Record>> 
health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.kt b/health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.ktindex 7282fbeacf..bf6e227429 100644--- a/health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.kt+++ b/health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.kt@@ -71,6 +71,29 @@ class HealthDaoTest {         assertEquals(0.0, dao.sumInRange(RecordType.Steps, start, end).first())     } +    @Test+    fun `replaceRecords drops samples removed from a multi-sample record`() = runTest {+        fun sample(id: String, index: Int, value: Double, type: RecordType = RecordType.HeartRate) =+            record(id, type = type, value = value)+                .copy(index = index, primaryKey = "$id-$index")+        dao.replaceRecords(+            listOf(sample("hr", 0, 60.0), sample("hr", 1, 90.0), sample("hr", 2, 120.0))+        )+        // Same record updated upstream down to one sample, plus an unrelated record.+        dao.replaceRecords(+            listOf(sample("hr", 0, 70.0), sample("steps", 0, 500.0, RecordType.Steps))+        )+        val (start, end) = range()+        assertEquals(+            listOf(70.0),+            dao.getAllInRange(RecordType.HeartRate, start, end).first().map { it.value },+        )+        assertEquals(+            listOf(500.0),+            dao.getAllInRange(RecordType.Steps, start, end).first().map { it.value },+        )+    }+     @Test     fun `getLastRecord returns the latest by start time`() = runTest {         dao.upsert(listOf(record("old", startMillis = 1_000L), record("new", startMillis = 5_000L)))
health/src/test/java/com/vayunmathur/health/data/RepositoryPassthroughTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/data/RepositoryPassthroughTest.kt b/health/src/test/java/com/vayunmathur/health/data/RepositoryPassthroughTest.ktindex 5a6f966932..118dc0e54a 100644--- a/health/src/test/java/com/vayunmathur/health/data/RepositoryPassthroughTest.kt+++ b/health/src/test/java/com/vayunmathur/health/data/RepositoryPassthroughTest.kt@@ -151,6 +151,42 @@ class RepositoryPassthroughTest {         assertTrue(repo.getPendingMirrors().none { it.rowId == "repo-med-1" })     } +    @Test+    fun `record upsert fully replaces a shrunken multi-sample record`() = runTest {+        val repo = repo()+        fun sample(id: String, index: Int, value: Double) = Record(+            id = id,+            index = index,+            type = RecordType.HeartRate,+            startTime = at.plusSeconds(index * 60L),+            endTime = at.plusSeconds(index * 60L),+            value = value,+        )+        // A Health Connect heart-rate record first syncs with three samples.+        repo.upsert(+            listOf(+                sample("repo-hr-shrink", 0, 60.0),+                sample("repo-hr-shrink", 1, 90.0),+                sample("repo-hr-shrink", 2, 120.0),+                sample("repo-hr-other", 0, 55.0),+            )+        )+        // The same record is then updated upstream to a single sample: the+        // two removed samples must not survive as phantom heart rates.+        repo.upsert(listOf(sample("repo-hr-shrink", 0, 70.0)))+        val rows = repo.getRecordsFlow(RecordType.HeartRate).first()+        assertEquals(+            listOf(70.0),+            rows.filter { it.id == "repo-hr-shrink" }.map { it.value },+        )+        // Other records are untouched by the replacement.+        assertEquals(+            listOf(55.0),+            rows.filter { it.id == "repo-hr-other" }.map { it.value },+        )+        repo.deleteByIds(listOf("repo-hr-shrink", "repo-hr-other"))+    }+     @Test     fun `ingredient recipe and serving unit passthroughs`() = runTest {         val repo = repo()