health: month/year charts average over days, not buckets
- Commit
00be8a5cf2b28aeef01b000e4fb56bd4f46be0f1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 19:35 UTC (5 days ago)
- Parents
b883c96
The month and year chart tabs changed bucket granularity without the aggregation noticing: month history is weekly sums and year history is monthly sums, but the header averaged the buckets and labelled it 'per day' (300,000 steps across 5 week-buckets showed 60,000 steps/day; the truth is 10,000/day), and history items compared weekly/monthly sums against the daily goal (a 60,000-step week was flagged goal-met against a 70,000-step weekly target). Bar metrics on those tabs now divide the period total by calendar days (leap-aware), and history goals scale by the days the bucket covers — partial first/last weeks intersecting the displayed month included. Line metrics are unaffected (their buckets are averages) and pinned so by a blood-pressure test. Six new regression tests cover month/year averages and goal scaling. Health Connect import, record editing, dose scheduling and sleep mapping were audited and cleared. Verified: :health:testDevUnitTest BUILD SUCCESSFUL; lint errors are pre-existing on untouched files.
Diff
health/AGENTS.md
diff --git a/health/AGENTS.md b/health/AGENTS.mdindex f713f4f174..e8c9032ee7 100644--- a/health/AGENTS.md+++ b/health/AGENTS.md@@ -19,7 +19,7 @@ _Install: ./install health (dev by default)._ **Architecture / data-flow:** `ui/` Today + record pages → `platform/MedicalViewModel` (+ per-area `Medical*Ops`) → `data/HealthRepository` over Room (`Record`, `MedicationSchedule`, `MedicalRecords`) synced with Health Connect; `domain/` holds pure FHIR (Observations, Medication, Immunization, Allergy/Condition) + `DoseSchedule`; reminders flow `DoseScheduler` → receivers → `DoseReminderActivity` + `service/DoseSoundService`. **Entry points + reading order:** `MainActivity.kt` → `ui/TodayPage.kt` → `platform/MedicalViewModel.kt` → `data/HealthRepository.kt` → `domain/FhirRecords.kt` → `platform/DoseScheduler.kt`. **Gotchas:**-- Day views use half-open local-calendar ranges (`HealthChartData.dayRange`, DAO `startTime in [start, end)`, bucketed by start): DST days are 23/25h, midnight point records belong to the new day, and intervals crossing midnight count on their start day. Day-tab line metrics average their hourly averages; bar metrics sum their hourly sums; basal metabolic rate (stored kcal/day) is an averaged line metric, while Today hydration converts stored litres to ml.+- Day views use half-open local-calendar ranges (`HealthChartData.dayRange`, DAO `startTime in [start, end)`, bucketed by start): DST days are 23/25h, midnight point records belong to the new day, and intervals crossing midnight count on their start day. Day-tab line metrics average their hourly averages; bar metrics sum their hourly sums; basal metabolic rate (stored kcal/day) is an averaged line metric, while Today hydration converts stored litres to ml. Month/year tabs bucket bar metrics into weekly/monthly sums: their per-day average divides the period total by the calendar days in the month/year, and a history row's goal is the daily goal scaled by the days its bucket covers (line metrics keep averaging and comparing bucket averages directly). - `util/` is NOT a closed package root — don't add more files there - Medical data is dual-homed (Room + Health Connect) — writes must update both or they diverge - Dose reminders need the boot path re-armed like clock alarms; sound runs through a foreground service
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 86fec5f5ad..1f5faef290 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt@@ -215,7 +215,7 @@ internal object HealthChartData { value = triple.second, secondaryValue = if (config.isDualSeries) triple.third else null, unit = config.unit,- isGoalMet = triple.second >= config.dailyGoal,+ isGoalMet = triple.second >= historyGoal(config, selectedTab, startDate, triple.first), useDecimals = config.useDecimals, ) }.reversed()@@ -224,6 +224,57 @@ internal object HealthChartData { } } + /**+ * The goal a history row must reach. Daily rows (week tab) and line-chart rows+ * (bucket averages on every tab) compare against the daily goal directly. Bar-chart+ * rows on the month/year tabs are weekly/monthly *sums*, so their goal is the daily+ * goal scaled by the number of days the bucket covers: a 60,000-step week has not+ * met a 10,000-steps-a-day goal, even though 60,000 >= 10,000.+ */+ private fun historyGoal(+ config: HealthMetricConfig,+ selectedTab: Int,+ startDate: LocalDate,+ bucketKey: Long,+ ): Double {+ if (config.isLineChart) return config.dailyGoal+ return when (selectedTab) {+ 2 -> {+ // Weekly bucket intersected with the displayed month: the first and+ // last weeks of a month are usually partial (e.g. only Jun 30 falls+ // in the week starting Jun 30), so they carry proportionally fewer days.+ val bucketStart = bucketDate(bucketKey).toEpochDays()+ val monthStart = LocalDate(startDate.year, startDate.month, 1)+ val from = maxOf(bucketStart, monthStart.toEpochDays())+ val to = minOf(+ bucketStart + DAYS_PER_WEEK,+ monthStart.plus(1, DateTimeUnit.MONTH).toEpochDays(),+ )+ config.dailyGoal * (to - from).coerceAtLeast(1)+ }+ 3 -> {+ val bucketStart = bucketDate(bucketKey)+ val monthStart = LocalDate(bucketStart.year, bucketStart.month, 1)+ val days = monthStart.plus(1, DateTimeUnit.MONTH).toEpochDays() -+ monthStart.toEpochDays()+ config.dailyGoal * days+ }+ else -> config.dailyGoal+ }+ }++ /** Days in the calendar month containing [date]. */+ private fun daysInMonth(date: LocalDate): Int {+ val monthStart = LocalDate(date.year, date.month, 1)+ return (monthStart.plus(1, DateTimeUnit.MONTH).toEpochDays() - monthStart.toEpochDays()).toInt()+ }++ /** Days in the calendar year containing [date] (366 in a leap year). */+ private fun daysInYear(date: LocalDate): Int {+ val yearStart = LocalDate(date.year, 1, 1)+ return (yearStart.plus(1, DateTimeUnit.YEAR).toEpochDays() - yearStart.toEpochDays()).toInt()+ }+ /** The calendar date a bucket key names (pure; label rendering needs Resources). */ internal fun bucketDate(epochDay: Long): LocalDate = LocalDate.fromEpochDays(epochDay.toInt()) @@ -251,6 +302,17 @@ internal object HealthChartData { mappedChart: List<Pair<String, Double?>>, mappedSecondaryChart: List<Pair<String, Double?>>?, history: List<HistoryItem>,+ ): MetricDashboardData =+ buildDashboardData(config, selectedTab, null, rawPairs, mappedChart, mappedSecondaryChart, history)++ internal fun buildDashboardData(+ config: HealthMetricConfig,+ selectedTab: Int,+ startDate: LocalDate?,+ rawPairs: List<Tuple3<Long, Double, Double>>,+ mappedChart: List<Pair<String, Double?>>,+ mappedSecondaryChart: List<Pair<String, Double?>>?,+ history: List<HistoryItem>, ): MetricDashboardData { val nonNullPrimary = if (selectedTab == 0) rawPairs.map { it.second } else history.map { it.value }@@ -273,10 +335,27 @@ internal object HealthChartData { config.isLineChart -> nonNullSecondary.average() else -> nonNullSecondary.sum() }+ // Month/year tabs: history buckets are weekly (tab 2) / monthly (tab 3) sums+ // for bar metrics, so averaging the buckets gives a per-week/per-month figure,+ // not the per-day average the header labels it as (a 300,000-step June showed+ // ~60,000 steps per day). Divide the period total by its calendar days+ // instead, matching the week tab, whose filled 7 daily rows (missing = 0)+ // already average over the whole week. Line metrics keep averaging their+ // bucket averages, as on the day tab (#947).+ val periodDays = when {+ config.isLineChart || startDate == null -> null+ selectedTab == 2 -> daysInMonth(startDate)+ selectedTab == 3 -> daysInYear(startDate)+ else -> null+ } return MetricDashboardData( totalValue = if (selectedTab == 0) dayPrimary else nonNullPrimary.sum(),- dailyAverage = if (nonNullPrimary.isEmpty()) 0.0- else (if (selectedTab == 0) dayPrimary else nonNullPrimary.average()),+ dailyAverage = when {+ nonNullPrimary.isEmpty() -> 0.0+ selectedTab == 0 -> dayPrimary+ periodDays != null -> nonNullPrimary.sum() / periodDays+ else -> nonNullPrimary.average()+ }, secondaryAverage = if (selectedTab == 0) daySecondary else if (nonNullSecondary.isEmpty()) null else nonNullSecondary.average(), chartData = mappedChart,
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 9f86245a3a..0401798a0d 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt@@ -286,7 +286,7 @@ class HealthViewModel( ) _barChartData.value = HealthChartData.buildDashboardData(- config, selectedTab, rawPairs, mappedChart, mappedSecondaryChart, history,+ config, selectedTab, startDate, rawPairs, mappedChart, mappedSecondaryChart, history, ) _hasLoadedBarChart.value = true }
health/src/test/java/com/vayunmathur/health/util/MonthYearAggregationTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/MonthYearAggregationTest.kt b/health/src/test/java/com/vayunmathur/health/util/MonthYearAggregationTest.ktnew file mode 100644index 0000000000..27ef6dabcc--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/util/MonthYearAggregationTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.health.util++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.health.platform.HealthChartData+import com.vayunmathur.health.ui.HealthMetricConfig+import com.vayunmathur.health.ui.HistoryItem+import com.vayunmathur.library.util.Tuple3+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.datetime.LocalDate+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Regression tests for the month/year chart tabs treating weekly/monthly+ * history buckets as if they were daily buckets.+ *+ * On those tabs a bar metric's history rows are weekly sums (month tab) or+ * monthly sums (year tab), but [HealthChartData] averaged them for the+ * "per day (avg)" header and compared them against the *daily* goal:+ * a 300,000-step June (10,000/day) showed ~60,000 steps per day, and a+ * 60,000-step week was flagged goal-met against a 10,000-steps-a-day goal.+ * Line metrics are unaffected: their buckets are averages, so averaging+ * them and comparing them to the daily goal stays correct.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MonthYearAggregationTest {++ private val context = ApplicationProvider.getApplicationContext<Application>()++ private fun historyOf(vararg values: Double): List<HistoryItem> =+ values.map { HistoryItem("bucket", it, null, "steps", false, false) }++ @Test+ fun `month tab daily average divides the monthly total by the days in the month`() {+ // June 2024 has 30 days; weekly sums totalling 300,000 steps are 10,000/day,+ // not the ~60,000/day that averaging the five weekly buckets produced.+ val data = HealthChartData.buildDashboardData(+ HealthMetricConfig.STEPS, 2, LocalDate(2024, 6, 1),+ emptyList(), emptyList(), null,+ historyOf(70_000.0, 70_000.0, 70_000.0, 70_000.0, 20_000.0),+ )+ assertEquals(300_000.0, data.totalValue)+ assertEquals(10_000.0, data.dailyAverage)+ }++ @Test+ fun `year tab daily average divides the yearly total by the days in the year`() {+ // 2024 is a leap year (366 days); twelve monthly sums of 305,000 steps+ // are 10,000/day, not 305,000/day.+ val data = HealthChartData.buildDashboardData(+ HealthMetricConfig.STEPS, 3, LocalDate(2024, 1, 1),+ emptyList(), emptyList(), null,+ historyOf(*DoubleArray(12) { 305_000.0 }),+ )+ assertEquals(3_660_000.0, data.totalValue)+ assertEquals(10_000.0, data.dailyAverage)+ }++ @Test+ fun `month tab daily average for a line metric still averages the bucket averages`() {+ val data = HealthChartData.buildDashboardData(+ HealthMetricConfig.WEIGHT, 2, LocalDate(2024, 6, 1),+ emptyList(), emptyList(), null,+ historyOf(70.0, 72.0),+ )+ assertEquals(71.0, data.dailyAverage)+ }++ @Test+ fun `month history goal scales by the days in each weekly bucket`() {+ // Weeks starting Sun Jun 2 (full 7 days in June) and Sun Jun 30 (only+ // Jun 30 in June). Steps' daily goal is 10,000.+ val pairs = listOf(+ Tuple3(LocalDate(2024, 6, 2).toEpochDays(), 60_000.0, 0.0),+ Tuple3(LocalDate(2024, 6, 30).toEpochDays(), 12_000.0, 0.0),+ )+ val history = HealthChartData.buildHistoryItems(+ HealthMetricConfig.STEPS, 2, LocalDate(2024, 6, 1), context.resources, pairs,+ )+ // 60,000 in a full week is under 7 x 10,000: not goal-met (was met before).+ assertFalse(history.first { it.value == 60_000.0 }.isGoalMet)+ // 12,000 on the single June day of the last week is over 1 x 10,000: met.+ assertTrue(history.first { it.value == 12_000.0 }.isGoalMet)+ }++ @Test+ fun `year history goal scales by the days in each month`() {+ // Jan 2024 has 31 days (goal 310,000 steps); Feb 2024 has 29 (goal 290,000).+ val pairs = listOf(+ Tuple3(LocalDate(2024, 1, 1).toEpochDays(), 200_000.0, 0.0),+ Tuple3(LocalDate(2024, 2, 1).toEpochDays(), 300_000.0, 0.0),+ )+ val history = HealthChartData.buildHistoryItems(+ HealthMetricConfig.STEPS, 3, LocalDate(2024, 1, 1), context.resources, pairs,+ )+ assertFalse(history.first { it.value == 200_000.0 }.isGoalMet)+ assertTrue(history.first { it.value == 300_000.0 }.isGoalMet)+ }++ @Test+ fun `month history goal for a line metric still compares the average to the daily goal`() {+ // Blood pressure's daily goal is 120 mmHg; a weekly average of 125 meets it+ // and must not be scaled up to a weekly target.+ val pairs = listOf(+ Tuple3(LocalDate(2024, 6, 2).toEpochDays(), 125.0, 80.0),+ )+ val history = HealthChartData.buildHistoryItems(+ HealthMetricConfig.BLOOD_PRESSURE, 2, LocalDate(2024, 6, 1), context.resources, pairs,+ )+ assertTrue(history.single().isGoalMet)+ }+}