From c46a6a5554b7fe96cd5f1133af028bd94fbfa713 Mon Sep 17 00:00:00 2001 From: Mike Smith <194665430+strobeskinzzz@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:26:05 +1000 Subject: [PATCH 1/3] Use Health Connect's daily totals for steps, distance and active energy --- .../health/providers/health_entry_writer.dart | 18 ++++- .../health/providers/health_importer.dart | 2 +- .../health/providers/health_repository.dart | 38 +++++++++++ .../providers/health_importer_test.dart | 67 +++++++++++++++++++ .../providers/health_importer_test.mocks.dart | 13 ++++ .../providers/health_sync_test.mocks.dart | 13 ++++ 6 files changed, 148 insertions(+), 3 deletions(-) diff --git a/lib/features/health/providers/health_entry_writer.dart b/lib/features/health/providers/health_entry_writer.dart index 335322c7b..d0b69784e 100644 --- a/lib/features/health/providers/health_entry_writer.dart +++ b/lib/features/health/providers/health_entry_writer.dart @@ -24,6 +24,7 @@ import 'package:wger/features/health/models/daily_windows.dart'; import 'package:wger/features/health/models/health_metric.dart'; import 'package:wger/features/health/models/health_reading.dart'; import 'package:wger/features/health/providers/health_importer.dart'; +import 'package:wger/features/health/providers/health_repository.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; import 'package:wger/features/measurements/models/measurement_entry.dart'; import 'package:wger/features/measurements/models/unit_conversion.dart'; @@ -38,10 +39,13 @@ final _uuidPattern = RegExp(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[ /// two counters a run reports at the end. Created per run, since both are /// about that run. class HealthEntryWriter { - HealthEntryWriter(this._measurements, this._source); + HealthEntryWriter(this._measurements, this._source, this._health); final MeasurementRepository _measurements; + /// Used for the platform's own daily totals, see [_writeDailyAggregate] + final HealthRepository _health; + /// The measurement `source` of this platform (`apple`, `google`) final String _source; @@ -167,11 +171,21 @@ class HealthEntryWriter { ) async { final category = target.category; final values = samples.map((r) => metric.toCategoryValue(r.value)).toList(); - final aggregate = switch (metric.dailyAggregation!) { + var aggregate = switch (metric.dailyAggregation!) { DailyAggregation.average => values.average, DailyAggregation.sum => values.sum, DailyAggregation.mergedDuration => mergedDurationMinutes(samples), }; + // Cumulative metrics: take the platform's deduplicated day total instead + // of the raw sum, which double counts overlapping records. Falls back to + // the raw sum when the platform total is unavailable. + final type = metric.dataType; + if (metric.dailyAggregation == DailyAggregation.sum && type != null) { + final total = await _health.platformTotal(type, day, dayEnd(day, metric)); + if (total != null) { + aggregate = metric.toCategoryValue(total); + } + } // Round like the raw import: the server stores Decimal with 2 places final value = (aggregate * 100).roundToDouble() / 100; final extraData = { diff --git a/lib/features/health/providers/health_importer.dart b/lib/features/health/providers/health_importer.dart index cc4aa10f5..e689f35c6 100644 --- a/lib/features/health/providers/health_importer.dart +++ b/lib/features/health/providers/health_importer.dart @@ -159,7 +159,7 @@ class HealthImporter { return (imported: 0, issue: HealthSyncIssue.failed, completed: false); } - _writer = HealthEntryWriter(_measurements, _health.sourceName); + _writer = HealthEntryWriter(_measurements, _health.sourceName, _health); final run = await _prepare(metrics, readable, userId); _reportProgress(run); for (final metric in metrics) { diff --git a/lib/features/health/providers/health_repository.dart b/lib/features/health/providers/health_repository.dart index 6d498f68b..963ba2597 100644 --- a/lib/features/health/providers/health_repository.dart +++ b/lib/features/health/providers/health_repository.dart @@ -189,6 +189,44 @@ class HealthRepository { return true; } + /// The total of a cumulative [type] (steps, distance, active energy) + /// between [start] and [end] as Health Connect itself reports it. + /// + /// Health Connect resolves overlapping records from several apps by the + /// user's data source priority, and drops an app's second copy of the same + /// interval (e.g. a watch writing both its interval buckets and a workout + /// record). Adding up the raw records instead counts those twice. The value + /// is in the platform's raw unit (count, meters, kcal), like a raw read. + /// + /// Null on iOS, on failure, or when the platform returned nothing, so the + /// caller can fall back to the raw sum. + Future platformTotal(HealthDataType type, DateTime start, DateTime end) async { + if (kIsWeb || !Platform.isAndroid || !end.isAfter(start)) { + return null; + } + try { + final points = await _health.getHealthIntervalDataFromTypes( + startDate: start, + endDate: end, + types: [type], + // One bucket covering the whole range + interval: end.difference(start).inSeconds, + ); + final values = [ + for (final point in points) + if (point.value is NumericHealthValue) + (point.value as NumericHealthValue).numericValue.toDouble(), + ]; + if (values.isEmpty) { + return null; + } + return values.fold(0, (a, b) => a + b); + } catch (e) { + _logger.warning('Aggregate read of ${type.name} failed, using the raw sum: $e'); + return null; + } + } + /// Reads all [types] between [start] and [end] in windows of [window], /// handing each window's readings to [onBatch] as soon as it returned: /// the peak memory stays at one window (see [HealthMetric.readWindow]; diff --git a/test/features/health/providers/health_importer_test.dart b/test/features/health/providers/health_importer_test.dart index c1ef5455e..0790e7d0b 100644 --- a/test/features/health/providers/health_importer_test.dart +++ b/test/features/health/providers/health_importer_test.dart @@ -95,6 +95,8 @@ void main() { (invocation) async => (invocation.positionalArguments.first as List).toSet(), ); when(health.sourceName).thenReturn('apple'); + // No platform total by default: summed metrics fall back to their raw sum + when(health.platformTotal(any, any, any)).thenAnswer((_) async => null); when(measurements.addLocalDrift(any)).thenAnswer((_) async {}); when(measurements.updateLocalDrift(any)).thenAnswer((_) async {}); when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {}); @@ -856,6 +858,71 @@ void main() { ); }); + test('takes a summed day total from the platform, not the raw sum', () async { + // A watch writes a workout's steps twice, once in its interval buckets + // and once as a record of its own. Health Connect counts the overlap + // once; adding up the raw records counts it twice. + when(health.platformTotal(HealthDataType.STEPS, any, any)).thenAnswer((_) async => 7873); + stubReadings([ + HealthReading( + type: HealthDataType.STEPS, + value: 3866, + date: DateTime(2026, 10, 4, 11), + dateTo: DateTime(2026, 10, 4, 11, 30), + externalId: _idS1, + ), + HealthReading( + type: HealthDataType.STEPS, + value: 4007, + date: DateTime(2026, 10, 4, 11, 30), + dateTo: DateTime(2026, 10, 4, 12), + externalId: _idS2, + ), + HealthReading( + type: HealthDataType.STEPS, + value: 7813, + date: DateTime(2026, 10, 4, 11, 8), + dateTo: DateTime(2026, 10, 4, 11, 55), + externalId: _idS3, + ), + ]); + + await runImport(); + + final entry = + verify(measurements.addLocalDrift(captureAny)).captured.single as MeasurementEntry; + expect(entry.date, DateTime(2026, 10, 4)); + expect(entry.value, 7873); // not 15686 + verify( + health.platformTotal(HealthDataType.STEPS, DateTime(2026, 10, 4), DateTime(2026, 10, 5)), + ).called(1); + }); + + test('falls back to the raw sum when the platform has no total', () async { + stubReadings([ + HealthReading( + type: HealthDataType.STEPS, + value: 3866, + date: DateTime(2026, 10, 4, 11), + dateTo: DateTime(2026, 10, 4, 11, 30), + externalId: _idS1, + ), + HealthReading( + type: HealthDataType.STEPS, + value: 133, + date: DateTime(2026, 10, 4, 10, 30), + dateTo: DateTime(2026, 10, 4, 11), + externalId: _idS2, + ), + ]); + + await runImport(); + + final entry = + verify(measurements.addLocalDrift(captureAny)).captured.single as MeasurementEntry; + expect(entry.value, 3999); + }); + test('aggregates a day split across two read windows once', () async { // The batches arrive per window, but a day whose samples straddle a // window boundary must still become a single aggregate of all of them diff --git a/test/features/health/providers/health_importer_test.mocks.dart b/test/features/health/providers/health_importer_test.mocks.dart index 42f23a149..f80ef3723 100644 --- a/test/features/health/providers/health_importer_test.mocks.dart +++ b/test/features/health/providers/health_importer_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:health_bridge/health.dart' as _i5; @@ -99,6 +100,18 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { ) as _i4.Future); + @override + _i4.Future platformTotal( + _i5.HealthDataType? type, + DateTime? start, + DateTime? end, + ) => + (super.noSuchMethod( + Invocation.method(#platformTotal, [type, start, end]), + returnValue: _i4.Future.value(), + ) + as _i4.Future); + @override _i4.Future read({ required List<_i5.HealthDataType>? types, diff --git a/test/features/health/providers/health_sync_test.mocks.dart b/test/features/health/providers/health_sync_test.mocks.dart index 2af31fb18..d43bca2cf 100644 --- a/test/features/health/providers/health_sync_test.mocks.dart +++ b/test/features/health/providers/health_sync_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:health_bridge/health.dart' as _i5; @@ -99,6 +100,18 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { ) as _i4.Future); + @override + _i4.Future platformTotal( + _i5.HealthDataType? type, + DateTime? start, + DateTime? end, + ) => + (super.noSuchMethod( + Invocation.method(#platformTotal, [type, start, end]), + returnValue: _i4.Future.value(), + ) + as _i4.Future); + @override _i4.Future read({ required List<_i5.HealthDataType>? types, From 09c1160118efcd1661ed77fe517a5c714fe0f7cd Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 23 Oct 2026 19:47:54 +0200 Subject: [PATCH 2/3] Ask Health Connect for daily totals only when records overlap --- lib/core/shared_preferences.dart | 13 ++ lib/features/health/models/daily_windows.dart | 10 ++ .../health/providers/health_entry_writer.dart | 22 ++- .../health/providers/health_importer.dart | 29 +++- .../health/providers/health_repository.dart | 5 +- .../health/models/daily_windows_test.dart | 34 +++++ .../providers/health_importer_test.dart | 125 +++++++++++++++--- .../providers/health_importer_test.mocks.dart | 8 ++ .../health/providers/health_sync_test.dart | 1 + .../providers/health_sync_test.mocks.dart | 8 ++ 10 files changed, 230 insertions(+), 25 deletions(-) diff --git a/lib/core/shared_preferences.dart b/lib/core/shared_preferences.dart index 33eaf1cf0..588e6b46a 100644 --- a/lib/core/shared_preferences.dart +++ b/lib/core/shared_preferences.dart @@ -142,6 +142,7 @@ class PreferenceHelper { static const _healthSyncReadableTypesKey = 'healthSyncReadableTypes'; static const _healthSyncEmptyMetricsKey = 'healthSyncEmptyMetrics'; static const _healthSyncLastRunKey = 'healthSyncLastRun'; + static const _healthSyncDailySumsRereadKey = 'healthSyncDailySumsReread'; Future setHealthSyncEnabled(bool value) async { await PreferenceHelper.asyncPref.setBool(_healthSyncEnabledKey, value); @@ -211,11 +212,23 @@ class PreferenceHelper { return stored == null ? null : DateTime.tryParse(stored); } + /// Whether the summed metrics' history was read again for the platform + /// totals, which corrects the days imported while they were raw sums. + Future setHealthSyncDailySumsReread(bool value) async { + await PreferenceHelper.asyncPref.setBool(_healthSyncDailySumsRereadKey, value); + } + + Future getHealthSyncDailySumsReread() async { + final value = await PreferenceHelper.asyncPref.getBool(_healthSyncDailySumsRereadKey); + return value ?? false; + } + Future clearHealthSyncPreferences() async { await PreferenceHelper.asyncPref.remove(_healthSyncEnabledKey); await PreferenceHelper.asyncPref.remove(_healthSyncWatermarksKey); await PreferenceHelper.asyncPref.remove(_healthSyncReadableTypesKey); await PreferenceHelper.asyncPref.remove(_healthSyncEmptyMetricsKey); await PreferenceHelper.asyncPref.remove(_healthSyncLastRunKey); + await PreferenceHelper.asyncPref.remove(_healthSyncDailySumsRereadKey); } } diff --git a/lib/features/health/models/daily_windows.dart b/lib/features/health/models/daily_windows.dart index 26f1c7bb7..154dc1dd8 100644 --- a/lib/features/health/models/daily_windows.dart +++ b/lib/features/health/models/daily_windows.dart @@ -66,6 +66,16 @@ double mergedDurationMinutes(Iterable samples) { return total.inMicroseconds / Duration.microsecondsPerMinute; } +/// Whether any two of [samples] cover the same time. Back-to-back intervals +/// don't count, and a sample without an end covers no time. +bool hasOverlap(Iterable samples) { + final intervals = samples.where((r) => r.dateTo != null).toList() + ..sort((a, b) => a.date.compareTo(b.date)); + + // Sorted by start, any overlap shows between neighbours + return intervals.indexed.skip(1).any((e) => e.$2.date.isBefore(intervals[e.$1 - 1].dateTo!)); +} + /// Where the read window starts for [metric]. /// /// A daily aggregate is recomputed from what the window returns, so a start diff --git a/lib/features/health/providers/health_entry_writer.dart b/lib/features/health/providers/health_entry_writer.dart index d0b69784e..6921ae8e1 100644 --- a/lib/features/health/providers/health_entry_writer.dart +++ b/lib/features/health/providers/health_entry_writer.dart @@ -36,7 +36,7 @@ final _uuidPattern = RegExp(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[ /// or one per day for the metrics that aggregate. /// /// Owns the categories they are written into (see [resolveTargets]) and the -/// two counters a run reports at the end. Created per run, since both are +/// counters a run reports at the end. Created per run, since both are /// about that run. class HealthEntryWriter { HealthEntryWriter(this._measurements, this._source, this._health); @@ -60,6 +60,10 @@ class HealthEntryWriter { /// metric type allows, see [_isInRange]. var outOfRangeCount = 0; + /// Days during this run whose records overlap but got no platform total, + /// so their raw sum (which double counts) was stored instead. + var rawSumFallbackCount = 0; + /// Imports [metricReadings] into [target]'s category, deduplicating against /// the entries already present via their externalId. Returns the number of /// imported entries. @@ -176,14 +180,21 @@ class HealthEntryWriter { DailyAggregation.sum => values.sum, DailyAggregation.mergedDuration => mergedDurationMinutes(samples), }; - // Cumulative metrics: take the platform's deduplicated day total instead - // of the raw sum, which double counts overlapping records. Falls back to - // the raw sum when the platform total is unavailable. + // Overlapping records of a cumulative metric are double counted by the raw + // sum, so take the platform's deduplicated total. Asked only then: one call + // per day of history would run into Health Connect's read quota final type = metric.dataType; - if (metric.dailyAggregation == DailyAggregation.sum && type != null) { + var platformTotal = false; + if (metric.dailyAggregation == DailyAggregation.sum && + type != null && + _health.hasPlatformTotals && + hasOverlap(samples)) { final total = await _health.platformTotal(type, day, dayEnd(day, metric)); if (total != null) { aggregate = metric.toCategoryValue(total); + platformTotal = true; + } else { + rawSumFallbackCount++; } } // Round like the raw import: the server stores Decimal with 2 places @@ -194,6 +205,7 @@ class HealthEntryWriter { 'max': values.max, }, 'sample_count': values.length, + if (platformTotal) 'aggregated_by': 'platform', // The types actually seen, not the metric's own: a component can roll // several of them up (total sleep) 'record_type': (samples.map((r) => r.type.name).toSet().toList()..sort()).join(','), diff --git a/lib/features/health/providers/health_importer.dart b/lib/features/health/providers/health_importer.dart index e689f35c6..b682ed88d 100644 --- a/lib/features/health/providers/health_importer.dart +++ b/lib/features/health/providers/health_importer.dart @@ -189,12 +189,14 @@ class HealthImporter { String userId, ) async { final categories = await _measurements.getCategoriesOnce(); + final watermarks = await _readWatermarks(); + await _rereadDailySumsOnce(watermarks); final run = _SyncRun( userId: userId, categories: categories, endTime: DateTime.now(), - watermarks: await _readWatermarks(), + watermarks: watermarks, // Metrics the platform has nothing for never get a category, so counting // them as missing would ask for the full window on every sync knownEmpty: {...?await _prefs.getHealthSyncEmptyMetrics()}, @@ -327,6 +329,12 @@ class HealthImporter { if (_writer.outOfRangeCount > 0) { _logger.warning('Dropped ${_writer.outOfRangeCount} readings outside their metric limits'); } + if (_writer.rawSumFallbackCount > 0) { + _logger.warning( + 'No platform total for ${_writer.rawSumFallbackCount} days with overlapping records, ' + 'stored their raw sum', + ); + } } /// The result of a run that gave up before the metrics ran. @@ -355,6 +363,25 @@ class HealthImporter { return {for (final e in stored.entries) e.key: DateTime.parse(e.value)}; } + /// Drops the summed metrics' watermarks once where platform totals exist, + /// so their full history is read again and the days stored as double + /// counting raw sums are corrected. + Future _rereadDailySumsOnce(Map watermarks) async { + if (!_health.hasPlatformTotals || await _prefs.getHealthSyncDailySumsReread()) { + return; + } + final summed = { + for (final m in healthMetrics) + if (m.dailyAggregation == DailyAggregation.sum) m.metricType.name, + }; + if (watermarks.keys.any(summed.contains)) { + _logger.info('Reading the history of ${summed.join(', ')} again for the platform totals'); + watermarks.removeWhere((name, _) => summed.contains(name)); + await _writeWatermarks(watermarks); + } + await _prefs.setHealthSyncDailySumsReread(true); + } + Future _writeWatermarks(Map watermarks) async { await _prefs.setHealthSyncWatermarks({ for (final e in watermarks.entries) e.key: e.value.toIso8601String(), diff --git a/lib/features/health/providers/health_repository.dart b/lib/features/health/providers/health_repository.dart index 963ba2597..3a9fb6282 100644 --- a/lib/features/health/providers/health_repository.dart +++ b/lib/features/health/providers/health_repository.dart @@ -189,6 +189,9 @@ class HealthRepository { return true; } + /// Whether [platformTotal] can answer here at all: Health Connect only. + bool get hasPlatformTotals => !kIsWeb && Platform.isAndroid; + /// The total of a cumulative [type] (steps, distance, active energy) /// between [start] and [end] as Health Connect itself reports it. /// @@ -201,7 +204,7 @@ class HealthRepository { /// Null on iOS, on failure, or when the platform returned nothing, so the /// caller can fall back to the raw sum. Future platformTotal(HealthDataType type, DateTime start, DateTime end) async { - if (kIsWeb || !Platform.isAndroid || !end.isAfter(start)) { + if (!hasPlatformTotals || !end.isAfter(start)) { return null; } try { diff --git a/test/features/health/models/daily_windows_test.dart b/test/features/health/models/daily_windows_test.dart index ae28571a3..758a4d78d 100644 --- a/test/features/health/models/daily_windows_test.dart +++ b/test/features/health/models/daily_windows_test.dart @@ -95,6 +95,40 @@ void main() { }); }); + group('hasOverlap', () { + test('back-to-back records do not overlap', () { + expect( + hasOverlap([ + _asleep(DateTime(2026, 5, 5, 11, 30), DateTime(2026, 5, 5, 12)), + _asleep(DateTime(2026, 5, 5, 11), DateTime(2026, 5, 5, 11, 30)), + ]), + isFalse, + ); + }); + + test('a record inside a longer one overlaps, whatever the order', () { + // The workout record lies within the watch's own buckets + expect( + hasOverlap([ + _asleep(DateTime(2026, 5, 5, 11), DateTime(2026, 5, 5, 12)), + _asleep(DateTime(2026, 5, 5, 12), DateTime(2026, 5, 5, 13)), + _asleep(DateTime(2026, 5, 5, 10), DateTime(2026, 5, 5, 14)), + ]), + isTrue, + ); + }); + + test('a record without an end covers no time', () { + expect( + hasOverlap([ + _asleep(DateTime(2026, 5, 5, 11), DateTime(2026, 5, 5, 12)), + HealthReading(type: HealthDataType.STEPS, value: 10, date: DateTime(2026, 5, 5, 11, 30)), + ]), + isFalse, + ); + }); + }); + group('dayOf', () { test('a metric without a rollover counts the plain calendar day', () { expect(dayOf(DateTime(2026, 5, 4, 23, 30), steps), DateTime(2026, 5, 4)); diff --git a/test/features/health/providers/health_importer_test.dart b/test/features/health/providers/health_importer_test.dart index 0790e7d0b..1b21b9b5e 100644 --- a/test/features/health/providers/health_importer_test.dart +++ b/test/features/health/providers/health_importer_test.dart @@ -95,7 +95,8 @@ void main() { (invocation) async => (invocation.positionalArguments.first as List).toSet(), ); when(health.sourceName).thenReturn('apple'); - // No platform total by default: summed metrics fall back to their raw sum + // iOS by default: summed metrics stay raw sums + when(health.hasPlatformTotals).thenReturn(false); when(health.platformTotal(any, any, any)).thenAnswer((_) async => null); when(measurements.addLocalDrift(any)).thenAnswer((_) async {}); when(measurements.updateLocalDrift(any)).thenAnswer((_) async {}); @@ -397,6 +398,30 @@ void main() { expect(capturedReadStart(), DateTime(2026, 5, 2, 12)); }); + test('reads the history of the summed metrics once more for the platform totals', () async { + // Their days imported before held the double counted raw sum + await seedWatermarks('2026-06-01T12:00:00.000'); + await PreferenceHelper.instance.setHealthSyncReadableTypes([ + for (final metric in healthMetrics) + for (final type in metric.dataTypes) type.name, + ]); + when(measurements.getCategoriesOnce()).thenAnswer((_) async => categoriesForEveryMetric()); + when(health.hasPlatformTotals).thenReturn(true); + stubReadings([]); + + await runImport(); + + final starts = capturedReadStarts(); + expect(starts[HealthDataType.STEPS], DateTime(2020)); + expect(starts[HealthDataType.DISTANCE_DELTA], DateTime(2020)); + expect(starts[HealthDataType.ACTIVE_ENERGY_BURNED], DateTime(2020)); + expect(starts[HealthDataType.WEIGHT], DateTime(2026, 5, 2, 12)); + + await runImport(); + + expect(capturedReadStarts()[HealthDataType.STEPS]!.isAfter(DateTime(2020)), isTrue); + }); + test('a read the platform refuses for authorization is a permission issue', () async { // The one permission problem iOS reports at all, and what a reinstall // leaves behind: the preference says enabled, HealthKit disagrees @@ -862,6 +887,7 @@ void main() { // A watch writes a workout's steps twice, once in its interval buckets // and once as a record of its own. Health Connect counts the overlap // once; adding up the raw records counts it twice. + when(health.hasPlatformTotals).thenReturn(true); when(health.platformTotal(HealthDataType.STEPS, any, any)).thenAnswer((_) async => 7873); stubReadings([ HealthReading( @@ -893,34 +919,97 @@ void main() { verify(measurements.addLocalDrift(captureAny)).captured.single as MeasurementEntry; expect(entry.date, DateTime(2026, 10, 4)); expect(entry.value, 7873); // not 15686 + expect(entry.extraData!['aggregated_by'], 'platform'); verify( health.platformTotal(HealthDataType.STEPS, DateTime(2026, 10, 4), DateTime(2026, 10, 5)), ).called(1); }); - test('falls back to the raw sum when the platform has no total', () async { - stubReadings([ - HealthReading( - type: HealthDataType.STEPS, - value: 3866, - date: DateTime(2026, 10, 4, 11), - dateTo: DateTime(2026, 10, 4, 11, 30), - externalId: _idS1, - ), - HealthReading( - type: HealthDataType.STEPS, - value: 133, - date: DateTime(2026, 10, 4, 10, 30), - dateTo: DateTime(2026, 10, 4, 11), - externalId: _idS2, - ), - ]); + // Back to back, like a watch's interval buckets + final adjacentSteps = [ + HealthReading( + type: HealthDataType.STEPS, + value: 3866, + date: DateTime(2026, 10, 4, 11), + dateTo: DateTime(2026, 10, 4, 11, 30), + externalId: _idS1, + ), + HealthReading( + type: HealthDataType.STEPS, + value: 133, + date: DateTime(2026, 10, 4, 10, 30), + dateTo: DateTime(2026, 10, 4, 11), + externalId: _idS2, + ), + ]; + final overlappingSteps = [ + ...adjacentSteps, + HealthReading( + type: HealthDataType.STEPS, + value: 1000, + date: DateTime(2026, 10, 4, 10, 45), + dateTo: DateTime(2026, 10, 4, 11, 15), + externalId: _idS3, + ), + ]; + + test('sums records that do not overlap without asking the platform', () async { + when(health.hasPlatformTotals).thenReturn(true); + stubReadings(adjacentSteps); await runImport(); final entry = verify(measurements.addLocalDrift(captureAny)).captured.single as MeasurementEntry; expect(entry.value, 3999); + verifyNever(health.platformTotal(any, any, any)); + }); + + test('falls back to the raw sum when the platform has no total', () async { + when(health.hasPlatformTotals).thenReturn(true); + stubReadings(overlappingSteps); + + await runImport(); + + final entry = + verify(measurements.addLocalDrift(captureAny)).captured.single as MeasurementEntry; + expect(entry.value, 4999); + expect(entry.extraData, isNot(contains('aggregated_by'))); + verify(health.platformTotal(HealthDataType.STEPS, any, any)).called(1); + }); + + test('keeps the raw sum where the platform has no totals', () async { + stubReadings(overlappingSteps); + + await runImport(); + + final entry = + verify(measurements.addLocalDrift(captureAny)).captured.single as MeasurementEntry; + expect(entry.value, 4999); + verifyNever(health.platformTotal(any, any, any)); + }); + + test('converts a platform total into the category unit', () async { + when(health.hasPlatformTotals).thenReturn(true); + when( + health.platformTotal(HealthDataType.DISTANCE_DELTA, any, any), + ).thenAnswer((_) async => 6800); + stubReadings([ + for (final r in overlappingSteps) + HealthReading( + type: HealthDataType.DISTANCE_DELTA, + value: r.value, + date: r.date, + dateTo: r.dateTo, + externalId: r.externalId, + ), + ]); + + await runImport(); + + final entry = + verify(measurements.addLocalDrift(captureAny)).captured.single as MeasurementEntry; + expect(entry.value, 6.8); }); test('aggregates a day split across two read windows once', () async { diff --git a/test/features/health/providers/health_importer_test.mocks.dart b/test/features/health/providers/health_importer_test.mocks.dart index f80ef3723..587fc2fba 100644 --- a/test/features/health/providers/health_importer_test.mocks.dart +++ b/test/features/health/providers/health_importer_test.mocks.dart @@ -53,6 +53,14 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { ) as String); + @override + bool get hasPlatformTotals => + (super.noSuchMethod( + Invocation.getter(#hasPlatformTotals), + returnValue: false, + ) + as bool); + @override _i4.Future<_i2.HealthPlatformAvailability> availability() => (super.noSuchMethod( diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index 2eb5c06e6..cfe3f7cd3 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -68,6 +68,7 @@ void main() { (invocation) async => (invocation.positionalArguments.first as List).toSet(), ); when(health.sourceName).thenReturn('apple'); + when(health.hasPlatformTotals).thenReturn(false); when(measurements.addLocalDrift(any)).thenAnswer((_) async {}); when(measurements.updateLocalDrift(any)).thenAnswer((_) async {}); when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {}); diff --git a/test/features/health/providers/health_sync_test.mocks.dart b/test/features/health/providers/health_sync_test.mocks.dart index d43bca2cf..05b4def27 100644 --- a/test/features/health/providers/health_sync_test.mocks.dart +++ b/test/features/health/providers/health_sync_test.mocks.dart @@ -53,6 +53,14 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { ) as String); + @override + bool get hasPlatformTotals => + (super.noSuchMethod( + Invocation.getter(#hasPlatformTotals), + returnValue: false, + ) + as bool); + @override _i4.Future<_i2.HealthPlatformAvailability> availability() => (super.noSuchMethod( From d5ef743e48cd5e8e41d0f05c6acaa0b2f98e34e9 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 23 Oct 2026 19:50:19 +0200 Subject: [PATCH 3/3] Fall back to the raw sum when Health Connect reports 0 --- lib/features/health/models/health_metric.dart | 6 +++--- .../health/providers/health_entry_writer.dart | 6 ++++-- lib/features/health/providers/health_importer.dart | 2 +- lib/features/health/providers/health_repository.dart | 3 ++- .../health/providers/health_importer_test.dart | 12 ++++++++++++ 5 files changed, 22 insertions(+), 7 deletions(-) diff --git a/lib/features/health/models/health_metric.dart b/lib/features/health/models/health_metric.dart index 1f25a1d66..802e95eb0 100644 --- a/lib/features/health/models/health_metric.dart +++ b/lib/features/health/models/health_metric.dart @@ -255,9 +255,9 @@ const List healthMetrics = [ ), // The three cumulative types below are counters, not measurements: a single // record covers a few minutes and means nothing on its own, so only the - // day's total is stored. Both platforms can aggregate them themselves, which - // would replace the raw read with one row per day; until the importer has - // that path, they are read raw in small windows and summed here. + // day's total is stored. They are read raw in small windows and summed; a + // day whose records overlap takes Health Connect's deduplicated total + // instead, see HealthEntryWriter. HealthMetric( metricType: MetricType.steps, dataType: HealthDataType.STEPS, diff --git a/lib/features/health/providers/health_entry_writer.dart b/lib/features/health/providers/health_entry_writer.dart index 6921ae8e1..bac7f6d65 100644 --- a/lib/features/health/providers/health_entry_writer.dart +++ b/lib/features/health/providers/health_entry_writer.dart @@ -39,7 +39,7 @@ final _uuidPattern = RegExp(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[ /// counters a run reports at the end. Created per run, since both are /// about that run. class HealthEntryWriter { - HealthEntryWriter(this._measurements, this._source, this._health); + HealthEntryWriter(this._measurements, this._health) : _source = _health.sourceName; final MeasurementRepository _measurements; @@ -190,7 +190,9 @@ class HealthEntryWriter { _health.hasPlatformTotals && hasOverlap(samples)) { final total = await _health.platformTotal(type, day, dayEnd(day, metric)); - if (total != null) { + // Health Connect reports a day without data from its priority list as + // 0, which would wipe a day that has records + if (total != null && total > 0) { aggregate = metric.toCategoryValue(total); platformTotal = true; } else { diff --git a/lib/features/health/providers/health_importer.dart b/lib/features/health/providers/health_importer.dart index b682ed88d..e852076e2 100644 --- a/lib/features/health/providers/health_importer.dart +++ b/lib/features/health/providers/health_importer.dart @@ -159,7 +159,7 @@ class HealthImporter { return (imported: 0, issue: HealthSyncIssue.failed, completed: false); } - _writer = HealthEntryWriter(_measurements, _health.sourceName, _health); + _writer = HealthEntryWriter(_measurements, _health); final run = await _prepare(metrics, readable, userId); _reportProgress(run); for (final metric in metrics) { diff --git a/lib/features/health/providers/health_repository.dart b/lib/features/health/providers/health_repository.dart index 3a9fb6282..ac583f498 100644 --- a/lib/features/health/providers/health_repository.dart +++ b/lib/features/health/providers/health_repository.dart @@ -202,7 +202,8 @@ class HealthRepository { /// is in the platform's raw unit (count, meters, kcal), like a raw read. /// /// Null on iOS, on failure, or when the platform returned nothing, so the - /// caller can fall back to the raw sum. + /// caller can fall back to the raw sum. A range without data from the + /// user's priority list comes back as 0, not null. Future platformTotal(HealthDataType type, DateTime start, DateTime end) async { if (!hasPlatformTotals || !end.isAfter(start)) { return null; diff --git a/test/features/health/providers/health_importer_test.dart b/test/features/health/providers/health_importer_test.dart index 1b21b9b5e..5e5cbffa2 100644 --- a/test/features/health/providers/health_importer_test.dart +++ b/test/features/health/providers/health_importer_test.dart @@ -978,6 +978,18 @@ void main() { verify(health.platformTotal(HealthDataType.STEPS, any, any)).called(1); }); + test('falls back to the raw sum when the platform total is 0', () async { + when(health.hasPlatformTotals).thenReturn(true); + when(health.platformTotal(HealthDataType.STEPS, any, any)).thenAnswer((_) async => 0); + stubReadings(overlappingSteps); + + await runImport(); + + final entry = + verify(measurements.addLocalDrift(captureAny)).captured.single as MeasurementEntry; + expect(entry.value, 4999); + }); + test('keeps the raw sum where the platform has no totals', () async { stubReadings(overlappingSteps);