Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,17 @@ import kotlinx.coroutines.withContext

internal data class SleepCleanupRange(val start: Instant, val end: Instant)

internal fun sleepCleanupRange(start: Instant, end: Instant, zoneId: ZoneId): SleepCleanupRange {
/**
* Noon-to-noon around the wake. Starts after [previousWake] when the day
* before's night woke inside the window (after noon), else the delete takes
* that night too and nothing writes it back. Never past this night's onset.
*/
internal fun sleepCleanupRange(
start: Instant,
end: Instant,
zoneId: ZoneId,
previousWake: Instant? = null,
): SleepCleanupRange {
require(start.isBefore(end))
val localEnd = end.atZone(zoneId)
val endDate = if (localEnd.toLocalTime().isBefore(LocalTime.NOON)) {
Expand All @@ -35,6 +45,9 @@ internal fun sleepCleanupRange(start: Instant, end: Instant, zoneId: ZoneId): Sl
val cleanupEnd = endDate.atTime(LocalTime.NOON).atZone(zoneId).toInstant()
val calculatedStart = endDate.minusDays(1).atTime(LocalTime.NOON).atZone(zoneId).toInstant()
val cleanupStart = if (start.isBefore(calculatedStart)) start else calculatedStart
if (previousWake != null && !previousWake.isBefore(cleanupStart) && previousWake.isBefore(start)) {
return SleepCleanupRange(minOf(previousWake.plusSeconds(1), start), cleanupEnd)
}
return SleepCleanupRange(cleanupStart, cleanupEnd)
}

Expand Down Expand Up @@ -80,6 +93,8 @@ object HealthConnectSleepWriter {
session.startTime,
session.endTime,
ZoneId.systemDefault(),
(call.argument<Any>("previousWake") as? Number)
?.toLong()?.let(Instant::ofEpochMilli),
)

// This removes both records created by this writer and legacy
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,23 @@ class HealthConnectSleepWriterTest {
assertTrue(staleFragmentStart.isBefore(range.end))
}

@Test
fun cleanupRangeStartsAfterPreviousNightThatWokeAfterNoon() {
val sessionStart = localInstant(2026, 8, 5, 23, 30)
val sessionEnd = localInstant(2026, 8, 6, 7, 0)
val previousWake = localInstant(2026, 8, 5, 14, 0)

val range = sleepCleanupRange(sessionStart, sessionEnd, berlin, previousWake)

assertEquals(previousWake.plusSeconds(1), range.start)
assertEquals(localInstant(2026, 8, 6, 12, 0), range.end)
// A morning wake is outside the window and changes nothing.
val morning = sleepCleanupRange(
sessionStart, sessionEnd, berlin, localInstant(2026, 8, 5, 7, 0),
)
assertEquals(localInstant(2026, 8, 5, 12, 0), morning.start)
}

@Test
fun cleanupRangeUsesLocalNoonAcrossDstTransition() {
val sessionStart = localInstant(2026, 10, 25, 1, 30)
Expand Down
40 changes: 25 additions & 15 deletions lib/health/health_export.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1237,7 +1237,12 @@ class HealthExporter {
// day — so one entry is equivalent to the whole list, without
// holding 400 decoded bundles to re-derive the same answer.
newestFirstDays: [priorityDay],
write: _androidSleep.replace,
write: (b) async => _androidSleep.replace(
b,
previousWake: await _previousWake(
_localMidnight(priorityDay!.key) ?? DateTime.now(),
),
),
exportBulk: (androidSleepAlreadyWritten) async {
bulkDone = await exportBulk(androidSleepAlreadyWritten);
},
Expand Down Expand Up @@ -1443,6 +1448,21 @@ class HealthExporter {
});
}

/// When the day before's night woke; null when unknown. Best-effort: a failed
/// lookup must not block the sleep write it only clamps.
Future<DateTime?> _previousWake(DateTime dayStart) async {
try {
final prev = DateTime(dayStart.year, dayStart.month, dayStart.day - 1);
final pb = _decode(
(await LocalDb.dayResult(dayLabelOf(prev)))?['payload_json'],
);
return pb == null ? null : normalizeHealthSleepSession(pb)?.end;
} catch (e) {
debugPrint('[health] previous wake lookup: $e');
return null;
}
}

/// Write one day's metrics. DELETES our prior samples for the day window first
/// (so a re-derive overwrites instead of duplicating). Best-effort; never throws.
Future<bool> _exportDay(
Expand All @@ -1468,26 +1488,16 @@ class HealthExporter {
// on both stores (Health Connect SleepSessionRecord; HealthKit inBed+Core).
// Both the clear on a no-night day and HealthKit's replace on a day with
// a night must stop short of yesterday's night if that one woke after
// noon. Health Connect only uses it for the clear (its delete matches on
// start time; the native replace computes its own window).
Future<DateTime?> previousWake() async {
final prev = DateTime(dayStart.year, dayStart.month, dayStart.day - 1);
final pb = _decode(
(await LocalDb.dayResult(dayLabelOf(prev)))?['payload_json'],
);
return pb == null ? null : normalizeHealthSleepSession(pb)?.end;
}
// noon. Health Connect passes it to the native replace too, which clamps
// its own noon-to-noon window with it.
Future<DateTime?> previousWake() => _previousWake(dayStart);

if (Platform.isAndroid && !androidSleepAlreadyWritten) {
try {
if (!await _androidSleep.replace(
b,
dayStart: dayStart,
// Only the no-night clear reads it; skip decoding yesterday's
// bundle on every other day of a long first export.
previousWake: normalizeHealthSleepSession(b) == null
? await previousWake()
: null,
previousWake: await previousWake(),
Comment thread
abdulsaheel marked this conversation as resolved.
Resolved
)) {
debugPrint('[health] write Android sleep session returned false');
success = false;
Expand Down
14 changes: 10 additions & 4 deletions lib/health/health_sleep_session.dart
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,9 @@ HealthSleepStage? healthSleepStageOf(String? stage) {
}

abstract interface class HealthConnectSleepSessionWriter {
Future<bool> replace(HealthSleepSession session);
/// [previousWake] keeps the native cleanup off yesterday's night when it
/// woke after noon (see [sleepCleanupWindow]).
Future<bool> replace(HealthSleepSession session, {DateTime? previousWake});

/// Delete our own SleepSessionRecords overlapping [start, end).
Future<bool> clear(DateTime start, DateTime end);
Expand All @@ -326,8 +328,12 @@ class MethodChannelHealthConnectSleepSessionWriter
Future<void> _pending = Future<void>.value();

@override
Future<bool> replace(HealthSleepSession session) =>
_invoke('replaceSleepSession', session.toMap());
Future<bool> replace(HealthSleepSession session, {DateTime? previousWake}) =>
_invoke('replaceSleepSession', {
...session.toMap(),
if (previousWake != null)
'previousWake': previousWake.millisecondsSinceEpoch,
});

@override
Future<bool> clear(DateTime start, DateTime end) =>
Expand Down Expand Up @@ -397,7 +403,7 @@ class HealthConnectSleepSessionExporter {
// Health Connect handles a stage-less record and belongs in its own change,
// verified on a device.
if (session.stages.isEmpty) return true;
return writer.replace(session);
return writer.replace(session, previousWake: previousWake);
Comment thread
abdulsaheel marked this conversation as resolved.
Resolved
}
}

Expand Down
31 changes: 30 additions & 1 deletion test/health_sleep_export_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,32 @@ void main() {
DateTime(2026, 8, 5, 7, 46).millisecondsSinceEpoch,
);
expect(args['stages'] as List, hasLength(6));
expect(args.containsKey('previousWake'), isFalse);
});

test('replace hands yesterday\'s wake to the native cleanup', () async {
const channel = MethodChannel('openstrap/test_health_connect_prev_wake');
final calls = <MethodCall>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
calls.add(call);
return true;
});
addTearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
});
final exporter = HealthConnectSleepSessionExporter(
writer: MethodChannelHealthConnectSleepSessionWriter(channel: channel),
);
final wake = DateTime(2026, 8, 4, 14);

expect(
await exporter.replace(_overnightBundle(), previousWake: wake),
isTrue,
);
final args = (calls.single.arguments as Map).cast<String, Object?>();
expect(args['previousWake'], wake.millisecondsSinceEpoch);
});

test(
Expand Down Expand Up @@ -1162,7 +1188,10 @@ class _RecordingClearWriter implements HealthConnectSleepSessionWriter {
final List<(DateTime, DateTime)> cleared;

@override
Future<bool> replace(HealthSleepSession session) async => true;
Future<bool> replace(
HealthSleepSession session, {
DateTime? previousWake,
}) async => true;

@override
Future<bool> clear(DateTime start, DateTime end) async {
Expand Down
Loading