From 53a7baa000f48a46bc32d0b4ef152ca89df2145d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 3 Aug 2026 11:27:37 +0200 Subject: [PATCH] Start the read window where the metric's day starts --- .../health/providers/health_sync.dart | 31 +++++++--- .../health/providers/health_sync_test.dart | 59 ++++++++++++++----- 2 files changed, 69 insertions(+), 21 deletions(-) diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index bdd22f02b..d05ac838a 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -251,9 +251,8 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { // only syncs days after the measurement), so the read window reaches // back beyond the watermark; re-reads are deduplicated via externalId. final lastSyncStr = await prefs.getLastHealthSyncTimestamp(); - // Metrics whose full history the platform had nothing for. They never - // get a category, so counting them as missing would send every sync back - // to the full window, for every metric + // Metrics the platform has nothing for never get a category, so counting + // them as missing would ask for the full window on every sync final knownEmpty = {...?await prefs.getHealthSyncEmptyMetrics()}; final withoutCategory = _missingCategories( metrics, @@ -285,7 +284,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { // [HealthMetric.readWindow] final readings = await _health.read( types: metric.dataTypes, - start: startTime, + start: _windowStartFor(startTime, metric), end: endTime, window: metric.readWindow, ); @@ -597,6 +596,25 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { return total.inMicroseconds / Duration.microsecondsPerMinute; } + /// Where the read window starts for [metric]. + /// + /// A daily aggregate is recomputed from what the window returns, so a start + /// inside a day would overwrite it with a fraction of it. + DateTime _windowStartFor(DateTime start, HealthMetric metric) { + if (metric.dailyAggregation == null) { + return start; + } + + final rollover = metric.dayRollsOverAtHour; + if (rollover == null) { + return DateTime(start.year, start.month, start.day); + } + + // Before the rollover hour the current day began on the previous one + final dayBegan = start.hour >= rollover ? start.day : start.day - 1; + return DateTime(start.year, start.month, dayBegan, rollover); + } + /// The day a sample is attributed to. Plain calendar day, unless the metric /// rolls over: samples at or after [HealthMetric.dayRollsOverAtHour] then /// count towards the next day, so a night of sleep lands on the day the user @@ -725,9 +743,8 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { /// afterwards, the next sync is back on the watermark, and the entries the /// other metrics re-read are deduplicated via their external ids. /// - /// The caller excludes the metrics the platform has nothing for: a category - /// is only created for one that delivers, so those would never stop asking - /// for the full window (see setHealthSyncEmptyMetrics). + /// The caller excludes the metrics the platform has nothing for, see + /// setHealthSyncEmptyMetrics. List _missingCategories( List metrics, List categories, diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index bf2dfc4f9..7653916f2 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -158,21 +158,34 @@ void main() { return categories; } - /// The start of the window the sync asked the platform for. Every metric is - /// read separately, but all of them over the same range - DateTime capturedReadStart() { - final starts = verify( + /// The start of the window the sync asked the platform for, per data type. + /// + /// Every metric is read separately and a metric that aggregates per day + /// starts at the beginning of its own day, so the starts differ. + Map capturedReadStarts() { + final captured = verify( health.read( - types: anyNamed('types'), + types: captureAnyNamed('types'), start: captureAnyNamed('start'), end: anyNamed('end'), window: anyNamed('window'), ), - ).captured.cast(); - expect(starts.toSet(), hasLength(1), reason: 'Every metric reads the same range'); - return starts.first; + ).captured; + + final starts = {}; + for (var i = 0; i < captured.length; i += 2) { + for (final type in captured[i] as List) { + starts[type] = captured[i + 1] as DateTime; + } + } + return starts; } + /// The start of the window for the metric reading [type], body weight by + /// default: a plain sample metric, which reads from the unrounded start + DateTime capturedReadStart([HealthDataType type = HealthDataType.WEIGHT]) => + capturedReadStarts()[type]!; + /// Every health data type the sync asked the platform for List capturedReadTypes() => verify( health.read( @@ -1423,9 +1436,8 @@ void main() { // for the full window: it would do so on every sync, for every metric await PreferenceHelper.instance.setLastHealthSyncTimestamp('2026-06-01T12:00:00.000'); when(measurements.getAllOnce()).thenAnswer( - (_) async => categoriesForEveryMetric() - .where((c) => c.metricType != MetricType.bodyFat) - .toList(), + (_) async => + categoriesForEveryMetric().where((c) => c.metricType != MetricType.bodyFat).toList(), ); stubReadings([]); @@ -1447,15 +1459,34 @@ void main() { expect(capturedReadStart(), DateTime(2026, 5, 2, 12)); when(measurements.getAllOnce()).thenAnswer( - (_) async => categoriesForEveryMetric() - .where((c) => c.metricType != MetricType.bodyFat) - .toList(), + (_) async => + categoriesForEveryMetric().where((c) => c.metricType != MetricType.bodyFat).toList(), ); await createNotifier().sync(); expect(capturedReadStart(), DateTime(2020)); }); + test('an aggregating metric reads from the start of its own day', () async { + // The overlap start is a time of day, and a daily aggregate is + // recomputed from what the window returns: cutting into the day would + // overwrite that day's stored value with the part that was read + await PreferenceHelper.instance.setLastHealthSyncTimestamp('2026-06-01T12:00:00.000'); + when(measurements.getAllOnce()).thenAnswer((_) async => categoriesForEveryMetric()); + stubReadings([]); + + await createNotifier().sync(); + + final starts = capturedReadStarts(); + // A sample metric has no aggregate to protect and reads from the + // watermark minus the overlap + expect(starts[HealthDataType.WEIGHT], DateTime(2026, 5, 2, 12)); + // Heart rate is stored as one aggregate per calendar day + expect(starts[HealthDataType.HEART_RATE], DateTime(2026, 5, 2)); + // The sleep day of 2 May began at 18:00 on 1 May + expect(starts[HealthDataType.SLEEP_ASLEEP], DateTime(2026, 5, 1, 18)); + }); + test('reads the full history when a category was deleted', () async { // Deleting a category takes its entries with it, and the watermark says // nothing about a metric that has no history left: reading from it would