Merge pull request #1391 from strobeskinzzz/fix/health-platform-totals

Use Health Connect's daily totals for steps, distance and active energy
This commit is contained in:
Roland Geider
2026-10-23 20:06:22 +02:00
committed by GitHub
11 changed files with 373 additions and 8 deletions

View File

@@ -142,6 +142,7 @@ class PreferenceHelper {
static const _healthSyncReadableTypesKey = 'healthSyncReadableTypes';
static const _healthSyncEmptyMetricsKey = 'healthSyncEmptyMetrics';
static const _healthSyncLastRunKey = 'healthSyncLastRun';
static const _healthSyncDailySumsRereadKey = 'healthSyncDailySumsReread';
Future<void> 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<void> setHealthSyncDailySumsReread(bool value) async {
await PreferenceHelper.asyncPref.setBool(_healthSyncDailySumsRereadKey, value);
}
Future<bool> getHealthSyncDailySumsReread() async {
final value = await PreferenceHelper.asyncPref.getBool(_healthSyncDailySumsRereadKey);
return value ?? false;
}
Future<void> 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);
}
}

View File

@@ -66,6 +66,16 @@ double mergedDurationMinutes(Iterable<HealthReading> 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<HealthReading> 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

View File

@@ -255,9 +255,9 @@ const List<HealthMetric> 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,

View File

@@ -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';
@@ -35,13 +36,16 @@ 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);
HealthEntryWriter(this._measurements, this._health) : _source = _health.sourceName;
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;
@@ -56,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.
@@ -167,11 +175,30 @@ 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),
};
// 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;
var platformTotal = false;
if (metric.dailyAggregation == DailyAggregation.sum &&
type != null &&
_health.hasPlatformTotals &&
hasOverlap(samples)) {
final total = await _health.platformTotal(type, day, dayEnd(day, metric));
// 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 {
rawSumFallbackCount++;
}
}
// Round like the raw import: the server stores Decimal with 2 places
final value = (aggregate * 100).roundToDouble() / 100;
final extraData = <String, dynamic>{
@@ -180,6 +207,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(','),

View File

@@ -159,7 +159,7 @@ class HealthImporter {
return (imported: 0, issue: HealthSyncIssue.failed, completed: false);
}
_writer = HealthEntryWriter(_measurements, _health.sourceName);
_writer = HealthEntryWriter(_measurements, _health);
final run = await _prepare(metrics, readable, userId);
_reportProgress(run);
for (final metric in metrics) {
@@ -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<void> _rereadDailySumsOnce(Map<String, DateTime> 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<void> _writeWatermarks(Map<String, DateTime> watermarks) async {
await _prefs.setHealthSyncWatermarks({
for (final e in watermarks.entries) e.key: e.value.toIso8601String(),

View File

@@ -189,6 +189,48 @@ 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.
///
/// 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. A range without data from the
/// user's priority list comes back as 0, not null.
Future<double?> platformTotal(HealthDataType type, DateTime start, DateTime end) async {
if (!hasPlatformTotals || !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<double>(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];

View File

@@ -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));

View File

@@ -95,6 +95,9 @@ void main() {
(invocation) async => (invocation.positionalArguments.first as List<HealthDataType>).toSet(),
);
when(health.sourceName).thenReturn('apple');
// 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 {});
when(measurements.addLocalDriftCategory(any)).thenAnswer((_) async {});
@@ -395,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
@@ -856,6 +883,147 @@ 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.hasPlatformTotals).thenReturn(true);
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
expect(entry.extraData!['aggregated_by'], 'platform');
verify(
health.platformTotal(HealthDataType.STEPS, DateTime(2026, 10, 4), DateTime(2026, 10, 5)),
).called(1);
});
// 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('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);
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 {
// The batches arrive per window, but a day whose samples straddle a
// window boundary must still become a single aggregate of all of them

View File

@@ -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;
@@ -52,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(
@@ -99,6 +108,18 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository {
)
as _i4.Future<bool>);
@override
_i4.Future<double?> platformTotal(
_i5.HealthDataType? type,
DateTime? start,
DateTime? end,
) =>
(super.noSuchMethod(
Invocation.method(#platformTotal, [type, start, end]),
returnValue: _i4.Future<double?>.value(),
)
as _i4.Future<double?>);
@override
_i4.Future<void> read({
required List<_i5.HealthDataType>? types,

View File

@@ -68,6 +68,7 @@ void main() {
(invocation) async => (invocation.positionalArguments.first as List<HealthDataType>).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 {});

View File

@@ -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;
@@ -52,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(
@@ -99,6 +108,18 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository {
)
as _i4.Future<bool>);
@override
_i4.Future<double?> platformTotal(
_i5.HealthDataType? type,
DateTime? start,
DateTime? end,
) =>
(super.noSuchMethod(
Invocation.method(#platformTotal, [type, start, end]),
returnValue: _i4.Future<double?>.value(),
)
as _i4.Future<double?>);
@override
_i4.Future<void> read({
required List<_i5.HealthDataType>? types,