From ea741d197bc918023f87f6c7fc69e0f0d8af83b1 Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:12:33 +0530 Subject: [PATCH 1/2] health connect sleep replace stops short of yesterday's afternoon wake --- .../HealthConnectSleepWriter.kt | 17 +++++++++- .../HealthConnectSleepWriterTest.kt | 17 ++++++++++ lib/health/health_export.dart | 10 ++---- lib/health/health_sleep_session.dart | 14 ++++++--- test/health_sleep_export_test.dart | 31 ++++++++++++++++++- 5 files changed, 76 insertions(+), 13 deletions(-) diff --git a/android/app/src/main/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriter.kt b/android/app/src/main/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriter.kt index df79889e2..12d498915 100644 --- a/android/app/src/main/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriter.kt +++ b/android/app/src/main/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriter.kt @@ -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)) { @@ -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(previousWake.plusSeconds(1), cleanupEnd) + } return SleepCleanupRange(cleanupStart, cleanupEnd) } @@ -80,6 +93,8 @@ object HealthConnectSleepWriter { session.startTime, session.endTime, ZoneId.systemDefault(), + (call.argument("previousWake") as? Number) + ?.toLong()?.let(Instant::ofEpochMilli), ) // This removes both records created by this writer and legacy diff --git a/android/app/src/test/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriterTest.kt b/android/app/src/test/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriterTest.kt index 722af7678..1856fad2b 100644 --- a/android/app/src/test/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriterTest.kt +++ b/android/app/src/test/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriterTest.kt @@ -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) diff --git a/lib/health/health_export.dart b/lib/health/health_export.dart index f0df57144..b9bb55e0e 100644 --- a/lib/health/health_export.dart +++ b/lib/health/health_export.dart @@ -1468,8 +1468,8 @@ 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). + // noon. Health Connect passes it to the native replace too, which clamps + // its own noon-to-noon window with it. Future previousWake() async { final prev = DateTime(dayStart.year, dayStart.month, dayStart.day - 1); final pb = _decode( @@ -1483,11 +1483,7 @@ class HealthExporter { 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(), )) { debugPrint('[health] write Android sleep session returned false'); success = false; diff --git a/lib/health/health_sleep_session.dart b/lib/health/health_sleep_session.dart index 4ed122b84..3d88065f9 100644 --- a/lib/health/health_sleep_session.dart +++ b/lib/health/health_sleep_session.dart @@ -310,7 +310,9 @@ HealthSleepStage? healthSleepStageOf(String? stage) { } abstract interface class HealthConnectSleepSessionWriter { - Future replace(HealthSleepSession session); + /// [previousWake] keeps the native cleanup off yesterday's night when it + /// woke after noon (see [sleepCleanupWindow]). + Future replace(HealthSleepSession session, {DateTime? previousWake}); /// Delete our own SleepSessionRecords overlapping [start, end). Future clear(DateTime start, DateTime end); @@ -326,8 +328,12 @@ class MethodChannelHealthConnectSleepSessionWriter Future _pending = Future.value(); @override - Future replace(HealthSleepSession session) => - _invoke('replaceSleepSession', session.toMap()); + Future replace(HealthSleepSession session, {DateTime? previousWake}) => + _invoke('replaceSleepSession', { + ...session.toMap(), + if (previousWake != null) + 'previousWake': previousWake.millisecondsSinceEpoch, + }); @override Future clear(DateTime start, DateTime end) => @@ -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); } } diff --git a/test/health_sleep_export_test.dart b/test/health_sleep_export_test.dart index e51407d78..c0c01ba1d 100644 --- a/test/health_sleep_export_test.dart +++ b/test/health_sleep_export_test.dart @@ -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 = []; + 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(); + expect(args['previousWake'], wake.millisecondsSinceEpoch); }); test( @@ -1162,7 +1188,10 @@ class _RecordingClearWriter implements HealthConnectSleepSessionWriter { final List<(DateTime, DateTime)> cleared; @override - Future replace(HealthSleepSession session) async => true; + Future replace( + HealthSleepSession session, { + DateTime? previousWake, + }) async => true; @override Future clear(DateTime start, DateTime end) async { From 000291529a57bc11d0e12f28b78fae3c7d3be32e Mon Sep 17 00:00:00 2001 From: Mohammad Abdul Sahil <127765312+abdulsaheel@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:54:22 +0530 Subject: [PATCH 2/2] health connect sleep: pass previous wake on the priority path, best-effort lookup, clamp cleanup start to session start --- .../HealthConnectSleepWriter.kt | 2 +- lib/health/health_export.dart | 30 ++++++++++++++----- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/android/app/src/main/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriter.kt b/android/app/src/main/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriter.kt index 12d498915..7824fbe94 100644 --- a/android/app/src/main/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriter.kt +++ b/android/app/src/main/kotlin/wtf/openstrap/openstrap_edge/HealthConnectSleepWriter.kt @@ -46,7 +46,7 @@ internal fun sleepCleanupRange( 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(previousWake.plusSeconds(1), cleanupEnd) + return SleepCleanupRange(minOf(previousWake.plusSeconds(1), start), cleanupEnd) } return SleepCleanupRange(cleanupStart, cleanupEnd) } diff --git a/lib/health/health_export.dart b/lib/health/health_export.dart index b9bb55e0e..81b9124a0 100644 --- a/lib/health/health_export.dart +++ b/lib/health/health_export.dart @@ -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); }, @@ -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 _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 _exportDay( @@ -1470,13 +1490,7 @@ class HealthExporter { // a night must stop short of yesterday's night if that one woke after // noon. Health Connect passes it to the native replace too, which clamps // its own noon-to-noon window with it. - Future 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; - } + Future previousWake() => _previousWake(dayStart); if (Platform.isAndroid && !androidSleepAlreadyWritten) { try {