phone: extract pure exercise record-kind decision and add no-double-count unit tests
- Commit
4485edd024907cbbee45f3d5a8529317e3b456c0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-06 17:40 UTC (5 months ago)
- Parents
dfd66a2
Diff
watch/phone/build.gradle.kts
diff --git a/watch/phone/build.gradle.kts b/watch/phone/build.gradle.ktsindex d4e141930b..e66b7bb0fc 100644--- a/watch/phone/build.gradle.kts+++ b/watch/phone/build.gradle.kts@@ -15,4 +15,5 @@ dependencies { implementation(libs.androidx.connect.client) implementation(libs.androidx.work.runtime.ktx) implementRoom(libs)+ testImplementation("junit:junit:4.13.2") }
watch/phone/src/main/java/com/vayunmathur/watch/phone/health/ExerciseSessionMapping.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/ExerciseSessionMapping.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/ExerciseSessionMapping.ktnew file mode 100644index 0000000000..c13a723db6--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/ExerciseSessionMapping.kt@@ -0,0 +1,66 @@+package com.vayunmathur.watch.phone.health++import androidx.health.connect.client.records.ExerciseSessionRecord+import com.vayunmathur.watch.shared.data.ExerciseSessionSummary++/**+ * Pure, Android-framework-free decisions for turning an [ExerciseSessionSummary]+ * into Health Connect records. Kept separate from [HealthConnectManager] so they+ * can be unit-tested on the JVM without Robolectric, and so the "no double-count"+ * invariant lives in one auditable place.+ */++/** The kinds of records an exercise session may materialize. */+enum class ExerciseRecordKind {+ ExerciseSession,+ Route,+ Segments,+ Laps,+ Speed,+ StepsCadence,+ Vo2Max,+}++/**+ * The complete set of record kinds a session is ever allowed to write. Anything+ * outside this set (Distance, Floors, Elevation, TotalCalories, Steps, HeartRate)+ * already flows through the passive/per-sample pipelines and would double-count.+ */+val ALLOWED_EXERCISE_RECORD_KINDS: Set<ExerciseRecordKind> = ExerciseRecordKind.entries.toSet()++/**+ * Record kinds that must NEVER be produced by a session, because they duplicate+ * data already written elsewhere. Held by name so the guard is explicit in tests.+ */+val FORBIDDEN_EXERCISE_RECORD_NAMES: Set<String> =+ setOf("Distance", "Floors", "Elevation", "TotalCalories", "Steps", "HeartRate")++/**+ * Decides which record kinds [summary] will materialize. [ExerciseRecordKind.ExerciseSession]+ * is always present; the rest are gated on the corresponding session-unique data+ * actually being reported. [ExerciseRecordKind.Speed] covers both the real+ * time-series and the avg/max fallback.+ */+fun exerciseRecordKinds(summary: ExerciseSessionSummary): Set<ExerciseRecordKind> = buildSet {+ add(ExerciseRecordKind.ExerciseSession)+ if (!summary.route.isNullOrEmpty()) add(ExerciseRecordKind.Route)+ if (!summary.segments.isNullOrEmpty()) add(ExerciseRecordKind.Segments)+ if (!summary.laps.isNullOrEmpty()) add(ExerciseRecordKind.Laps)+ if (!summary.speedSamples.isNullOrEmpty() || summary.avgSpeedMps != null) add(ExerciseRecordKind.Speed)+ if (summary.avgCadenceSpm != null) add(ExerciseRecordKind.StepsCadence)+ if (summary.vo2Max != null) add(ExerciseRecordKind.Vo2Max)+}++/**+ * Maps a Health Services ExerciseType.name to the Health Connect EXERCISE_TYPE_*+ * int. The two enum systems differ, so the mapping is explicit.+ */+fun healthConnectExerciseType(hsName: String): Int = when (hsName) {+ "WALKING" -> ExerciseSessionRecord.EXERCISE_TYPE_WALKING+ "RUNNING" -> ExerciseSessionRecord.EXERCISE_TYPE_RUNNING+ "BIKING" -> ExerciseSessionRecord.EXERCISE_TYPE_BIKING+ "HIKING" -> ExerciseSessionRecord.EXERCISE_TYPE_HIKING+ "SWIMMING_POOL" -> ExerciseSessionRecord.EXERCISE_TYPE_SWIMMING_POOL+ "STRENGTH_TRAINING" -> ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING+ else -> ExerciseSessionRecord.EXERCISE_TYPE_OTHER_WORKOUT+}
watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.ktindex 291630b7fe..810d60165e 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/health/HealthConnectManager.kt@@ -199,12 +199,13 @@ class HealthConnectManager(private val context: Context) { val startOffset = zone.rules.getOffset(start) val endOffset = zone.rules.getOffset(end) val key = summary.startTime+ val kinds = exerciseRecordKinds(summary) val toInsert = mutableListOf<Record>() - val route = summary.route?.takeIf { it.isNotEmpty() }?.let { points ->+ val route = if (ExerciseRecordKind.Route in kinds) { ExerciseRoute(- points.map { p ->+ summary.route.orEmpty().map { p -> ExerciseRoute.Location( time = Instant.ofEpochMilli(p.time), latitude = p.lat,@@ -213,26 +214,36 @@ class HealthConnectManager(private val context: Context) { ) }, )+ } else {+ null } - val segments = summary.segments.orEmpty().map { seg ->- ExerciseSegment(- startTime = Instant.ofEpochMilli(seg.start),- endTime = Instant.ofEpochMilli(seg.end).let {- if (it.isAfter(Instant.ofEpochMilli(seg.start))) it- else Instant.ofEpochMilli(seg.start).plusSeconds(1)- },- segmentType = seg.type,- repetitions = seg.reps.toInt(),- )+ val segments = if (ExerciseRecordKind.Segments in kinds) {+ summary.segments.orEmpty().map { seg ->+ ExerciseSegment(+ startTime = Instant.ofEpochMilli(seg.start),+ endTime = Instant.ofEpochMilli(seg.end).let {+ if (it.isAfter(Instant.ofEpochMilli(seg.start))) it+ else Instant.ofEpochMilli(seg.start).plusSeconds(1)+ },+ segmentType = seg.type,+ repetitions = seg.reps.toInt(),+ )+ }+ } else {+ emptyList() } - val laps = summary.laps.orEmpty().map { lap ->- val lapStart = Instant.ofEpochMilli(lap.start)- val lapEnd = Instant.ofEpochMilli(lap.end).let {- if (it.isAfter(lapStart)) it else lapStart.plusSeconds(1)+ val laps = if (ExerciseRecordKind.Laps in kinds) {+ summary.laps.orEmpty().map { lap ->+ val lapStart = Instant.ofEpochMilli(lap.start)+ val lapEnd = Instant.ofEpochMilli(lap.end).let {+ if (it.isAfter(lapStart)) it else lapStart.plusSeconds(1)+ }+ ExerciseLap(startTime = lapStart, endTime = lapEnd) }- ExerciseLap(startTime = lapStart, endTime = lapEnd)+ } else {+ emptyList() } toInsert += ExerciseSessionRecord(@@ -250,26 +261,23 @@ class HealthConnectManager(private val context: Context) { // Speed: prefer the real captured time-series; fall back to the avg@start / // max@end approximation only when no series was reported.- val speedSamples = summary.speedSamples.orEmpty()- .map { SpeedRecord.Sample(time = Instant.ofEpochMilli(it.timeMs), speed = Velocity.metersPerSecond(it.mps)) }- .filter { !it.time.isBefore(start) && !it.time.isAfter(end) }- if (speedSamples.isNotEmpty()) {- toInsert += SpeedRecord(- startTime = start,- startZoneOffset = startOffset,- endTime = end,- endZoneOffset = endOffset,- samples = speedSamples,- metadata = Metadata.manualEntry(clientRecordId = "exercise-speed-$key"),- )- } else {- summary.avgSpeedMps?.let { avg ->- val samples = buildList {- add(SpeedRecord.Sample(time = start, speed = Velocity.metersPerSecond(avg)))+ if (ExerciseRecordKind.Speed in kinds) {+ val speedSamples = summary.speedSamples.orEmpty()+ .map { SpeedRecord.Sample(time = Instant.ofEpochMilli(it.timeMs), speed = Velocity.metersPerSecond(it.mps)) }+ .filter { !it.time.isBefore(start) && !it.time.isAfter(end) }+ val samples = if (speedSamples.isNotEmpty()) {+ speedSamples+ } else {+ buildList {+ summary.avgSpeedMps?.let {+ add(SpeedRecord.Sample(time = start, speed = Velocity.metersPerSecond(it)))+ } summary.maxSpeedMps?.let { add(SpeedRecord.Sample(time = end, speed = Velocity.metersPerSecond(it))) } }+ }+ if (samples.isNotEmpty()) { toInsert += SpeedRecord( startTime = start, startZoneOffset = startOffset,@@ -281,25 +289,29 @@ class HealthConnectManager(private val context: Context) { } } - summary.avgCadenceSpm?.let { cadence ->- toInsert += StepsCadenceRecord(- startTime = start,- startZoneOffset = startOffset,- endTime = end,- endZoneOffset = endOffset,- samples = listOf(StepsCadenceRecord.Sample(time = start, rate = cadence)),- metadata = Metadata.manualEntry(clientRecordId = "exercise-cadence-$key"),- )+ if (ExerciseRecordKind.StepsCadence in kinds) {+ summary.avgCadenceSpm?.let { cadence ->+ toInsert += StepsCadenceRecord(+ startTime = start,+ startZoneOffset = startOffset,+ endTime = end,+ endZoneOffset = endOffset,+ samples = listOf(StepsCadenceRecord.Sample(time = start, rate = cadence)),+ metadata = Metadata.manualEntry(clientRecordId = "exercise-cadence-$key"),+ )+ } } - summary.vo2Max?.let { vo2 ->- toInsert += Vo2MaxRecord(- time = end,- zoneOffset = endOffset,- vo2MillilitersPerMinuteKilogram = vo2,- measurementMethod = Vo2MaxRecord.MEASUREMENT_METHOD_OTHER,- metadata = Metadata.manualEntry(clientRecordId = "exercise-vo2-$key"),- )+ if (ExerciseRecordKind.Vo2Max in kinds) {+ summary.vo2Max?.let { vo2 ->+ toInsert += Vo2MaxRecord(+ time = end,+ zoneOffset = endOffset,+ vo2MillilitersPerMinuteKilogram = vo2,+ measurementMethod = Vo2MaxRecord.MEASUREMENT_METHOD_OTHER,+ metadata = Metadata.manualEntry(clientRecordId = "exercise-vo2-$key"),+ )+ } } try {@@ -309,18 +321,6 @@ class HealthConnectManager(private val context: Context) { } } - // Health Services ExerciseType.name -> Health Connect EXERCISE_TYPE_* int.- // The two enum systems differ, so the mapping is explicit.- private fun healthConnectExerciseType(hsName: String): Int = when (hsName) {- "WALKING" -> ExerciseSessionRecord.EXERCISE_TYPE_WALKING- "RUNNING" -> ExerciseSessionRecord.EXERCISE_TYPE_RUNNING- "BIKING" -> ExerciseSessionRecord.EXERCISE_TYPE_BIKING- "HIKING" -> ExerciseSessionRecord.EXERCISE_TYPE_HIKING- "SWIMMING_POOL" -> ExerciseSessionRecord.EXERCISE_TYPE_SWIMMING_POOL- "STRENGTH_TRAINING" -> ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING- else -> ExerciseSessionRecord.EXERCISE_TYPE_OTHER_WORKOUT- }- /** Batch-inserts derivation output; clientRecordIds make this idempotent. */ suspend fun insertDerived(records: List<Record>) { if (records.isEmpty()) return
watch/phone/src/test/java/com/vayunmathur/watch/phone/health/ExerciseRecordKindsTest.kt
diff --git a/watch/phone/src/test/java/com/vayunmathur/watch/phone/health/ExerciseRecordKindsTest.kt b/watch/phone/src/test/java/com/vayunmathur/watch/phone/health/ExerciseRecordKindsTest.ktnew file mode 100644index 0000000000..f904af6756--- /dev/null+++ b/watch/phone/src/test/java/com/vayunmathur/watch/phone/health/ExerciseRecordKindsTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.watch.phone.health++import com.vayunmathur.watch.shared.data.ExerciseSessionSummary+import com.vayunmathur.watch.shared.data.LapMarker+import com.vayunmathur.watch.shared.data.RepSegment+import com.vayunmathur.watch.shared.data.RoutePoint+import com.vayunmathur.watch.shared.data.SpeedSample+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Locks in the core invariant: an exercise session may only ever materialize+ * session-unique record kinds. Distance/Floors/Elevation/TotalCalories/Steps/+ * HeartRate already flow through the passive + per-sample pipelines, so writing+ * session-scoped copies would double-count in Health Connect.+ */+class ExerciseRecordKindsTest {++ private fun fullSummary() = ExerciseSessionSummary(+ exerciseType = "RUNNING",+ startTime = 1_000L,+ endTime = 2_000L,+ activeDurationMs = 1_000L,+ avgSpeedMps = 3.0,+ maxSpeedMps = 5.0,+ avgCadenceSpm = 170.0,+ vo2Max = 42.0,+ route = listOf(RoutePoint(1.0, 2.0, 3.0, 1_500L)),+ lapCount = 4L,+ laps = listOf(LapMarker(1_000L, 1_500L)),+ speedSamples = listOf(SpeedSample(1_200L, 3.2)),+ segments = listOf(RepSegment(0, 10, 1_000L, 2_000L)),+ endReason = "Ended by user",+ distanceMeters = 500.0,+ totalCalories = 80.0,+ avgHr = 150.0,+ )++ @Test fun fullSummaryNeverProducesForbiddenKinds() {+ val kinds = exerciseRecordKinds(fullSummary())+ assertTrue(+ "produced kinds must be within the allowed set",+ ALLOWED_EXERCISE_RECORD_KINDS.containsAll(kinds),+ )+ val producedNames = kinds.map { it.name }.toSet()+ assertTrue(+ "produced kinds must never include a double-counted type",+ producedNames.intersect(FORBIDDEN_EXERCISE_RECORD_NAMES).isEmpty(),+ )+ }++ @Test fun fullSummaryProducesEverySessionUniqueKind() {+ assertEquals(ALLOWED_EXERCISE_RECORD_KINDS, exerciseRecordKinds(fullSummary()))+ }++ @Test fun minimalSummaryStillWritesTheSession() {+ val minimal = ExerciseSessionSummary(+ exerciseType = "WORKOUT",+ startTime = 1_000L,+ endTime = 2_000L,+ activeDurationMs = 1_000L,+ )+ val kinds = exerciseRecordKinds(minimal)+ assertEquals(setOf(ExerciseRecordKind.ExerciseSession), kinds)+ }++ @Test fun displayOnlyAggregatesDoNotAddKinds() {+ // distanceMeters / totalCalories / avgHr / lapCount are display-only and+ // must not, on their own, cause any record to be written.+ val displayOnly = ExerciseSessionSummary(+ exerciseType = "WALKING",+ startTime = 1_000L,+ endTime = 2_000L,+ activeDurationMs = 1_000L,+ lapCount = 3L,+ distanceMeters = 400.0,+ totalCalories = 50.0,+ avgHr = 120.0,+ )+ assertEquals(setOf(ExerciseRecordKind.ExerciseSession), exerciseRecordKinds(displayOnly))+ }+}
watch/phone/src/test/java/com/vayunmathur/watch/phone/health/ExerciseTypeMappingTest.kt
diff --git a/watch/phone/src/test/java/com/vayunmathur/watch/phone/health/ExerciseTypeMappingTest.kt b/watch/phone/src/test/java/com/vayunmathur/watch/phone/health/ExerciseTypeMappingTest.ktnew file mode 100644index 0000000000..f818007682--- /dev/null+++ b/watch/phone/src/test/java/com/vayunmathur/watch/phone/health/ExerciseTypeMappingTest.kt@@ -0,0 +1,39 @@+package com.vayunmathur.watch.phone.health++import androidx.health.connect.client.records.ExerciseSessionRecord+import org.junit.Assert.assertEquals+import org.junit.Test++/**+ * Guards the two-enum mapping from Health Services ExerciseType names to Health+ * Connect EXERCISE_TYPE_* ints. The two systems share neither names nor ids, so a+ * silent drift here would mislabel every synced workout.+ */+class ExerciseTypeMappingTest {++ @Test fun mapsKnownTypes() {+ assertEquals(ExerciseSessionRecord.EXERCISE_TYPE_WALKING, healthConnectExerciseType("WALKING"))+ assertEquals(ExerciseSessionRecord.EXERCISE_TYPE_RUNNING, healthConnectExerciseType("RUNNING"))+ assertEquals(ExerciseSessionRecord.EXERCISE_TYPE_BIKING, healthConnectExerciseType("BIKING"))+ assertEquals(ExerciseSessionRecord.EXERCISE_TYPE_HIKING, healthConnectExerciseType("HIKING"))+ assertEquals(+ ExerciseSessionRecord.EXERCISE_TYPE_SWIMMING_POOL,+ healthConnectExerciseType("SWIMMING_POOL"),+ )+ assertEquals(+ ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING,+ healthConnectExerciseType("STRENGTH_TRAINING"),+ )+ assertEquals(+ ExerciseSessionRecord.EXERCISE_TYPE_OTHER_WORKOUT,+ healthConnectExerciseType("WORKOUT"),+ )+ }++ @Test fun unknownFallsBackToOtherWorkout() {+ assertEquals(+ ExerciseSessionRecord.EXERCISE_TYPE_OTHER_WORKOUT,+ healthConnectExerciseType("SOMETHING_ELSE"),+ )+ }+}