Ask Health Connect for daily totals only when records overlap

This commit is contained in:
Roland Geider
2026-10-23 19:47:54 +02:00
parent c46a6a5554
commit 09c1160118
10 changed files with 230 additions and 25 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

@@ -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(','),

View File

@@ -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,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<double?> platformTotal(HealthDataType type, DateTime start, DateTime end) async {
if (kIsWeb || !Platform.isAndroid || !end.isAfter(start)) {
if (!hasPlatformTotals || !end.isAfter(start)) {
return null;
}
try {

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

View File

@@ -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(

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

@@ -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(