diff --git a/lib/compute/crossday_pipeline.dart b/lib/compute/crossday_pipeline.dart index 98dee49e6..829af0828 100644 --- a/lib/compute/crossday_pipeline.dart +++ b/lib/compute/crossday_pipeline.dart @@ -797,6 +797,25 @@ double _nightClockMin(int epochSec, Map d) { return (_localTodMin(epochSec) + shiftMin) % 1440.0; } +/// Clock-minutes-of-day [0,1440) that a hypnogram segment [startSec, endSec) +/// (epoch SECONDS) covers, one entry per ELAPSED minute of the segment. Walking +/// elapsed time and mapping each instant through [_nightClockMin] keeps DST +/// honest: when the local clock steps back an hour in autumn (or forward in +/// spring) it is not monotone in elapsed time, so deriving the span from the +/// clock-minute DIFFERENCE of the endpoints over-counts — a 10-minute segment +/// across the autumn fall-back spanned 1390 clock-minutes (#914). The repeated +/// autumn hour maps two different instants to the same clock-minute; that is +/// fine for coverage, since the caller only sets a flag. An empty or reversed +/// segment covers nothing. Capped at a full grid (1440). +List segmentClockMinutes(int startSec, int endSec, Map d) { + if (endSec <= startSec) return const []; + final elapsedMin = math.min(((endSec - startSec) / 60).ceil(), 1440); + return [ + for (var k = 0; k < elapsedMin; k++) + _nightClockMin(startSec + k * 60, d).floor() % 1440, + ]; +} + /// How far a stored night's OWN local clock sits from the phone's CURRENT /// zone, in seconds [0,86400) — 0 when it was recorded in this zone, or when /// we cannot tell. Called by the record builder @@ -1309,29 +1328,20 @@ bool _isNextDay(String a, String b) { final end = (seg['end'] as num?)?.toDouble(); final stage = seg['stage'] as String?; if (start == null || end == null) continue; - // Segment bounds are epoch SECONDS; map to clock-minute-of-day [0,1440) - // on the clock the night was LIVED on (see _nightClockMin), so a trip - // does not shift every earlier night against the later ones. - final startMin = _nightClockMin(start.round(), d).floor(); - // end is exclusive of the segment's trailing edge; cover [start,end). - final endMinRaw = _nightClockMin(end.round(), d).ceil(); - // WRAP, don't clamp. Both bounds are clock-minutes-of-day in [0,1440), - // so a segment crossing local midnight reads e.g. start=1430, - // end=20 — and the old `for (m = startMin; m < endMin; m++)` simply - // never executed, silently DROPPING that segment (the comment claimed - // it "clamps into grid"; it didn't). Every night has exactly one such - // segment, so sleep-regularity was always computed with a hole at the - // boundary. Unwrap the end past 1440 and write back modulo the grid. - // `endMinRaw == startMin` stays a genuinely empty (sub-minute) segment. - final endMin = - endMinRaw < startMin ? endMinRaw + epochsPerDay : endMinRaw; - final span = math.min(endMin - startMin, epochsPerDay); // 'unobserved' is the band seeing nothing (off wrist, lost contact): // neither asleep nor awake, so those minutes stay uncovered. if (stage == 'unobserved') continue; final asleepSeg = stage != null && stage != 'wake'; - for (var k = 0; k < span; k++) { - final m = (startMin + k) % epochsPerDay; + // Segment bounds are epoch SECONDS. Walk the segment in ELAPSED minutes + // and map each instant to its clock-minute-of-day (segmentClockMinutes), + // so a segment crossing local midnight AND one crossing a DST change are + // both covered by the same per-minute `% epochsPerDay`. The old code + // derived the span from the clock-minute DIFFERENCE of the two + // endpoints, which is wrong whenever the clock is not monotone in + // elapsed time: across the autumn fall-back the clock steps back an + // hour, so a 10-minute segment read endMin-startMin == 1390 and marked + // nearly the whole day observed/asleep (#914). + for (final m in segmentClockMinutes(start.round(), end.round(), d)) { cov[m] = true; if (asleepSeg) asleep[m] = true; } diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart index 872bf5b82..9e4a10166 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -1947,7 +1947,14 @@ import 'vendor_sleep.dart'; // had every reading dropped, because the sparse substrate reads only rows // with HR. Each reading now joins the HR row of its minute. Wearables whose // temperature already rode on the HR rows, and every band day, unchanged. -const int kAlgoVersion = 133; +// 133 → 134 (analytics change): the sleep-regularity grid walks each hypnogram +// segment in ELAPSED minutes instead of deriving its span from the clock-minute +// difference of its endpoints (segmentClockMinutes in crossday_pipeline). Across +// the autumn fall-back the clock steps back an hour, so a sub-hour segment +// straddling it marked up to ~1390 clock-minutes observed/asleep instead of its +// true ~10, inflating SRI; spring over-counted similarly. Only nights whose +// sleep segments cross a DST change move; every other night's SRI is unchanged. +const int kAlgoVersion = 134; /// The sibling SHAs this version was derived against, asserted against /// pubspec.yaml in test/db_serve_version_and_reads_test.dart. /// diff --git a/test/sri_dst_segment_span_test.dart b/test/sri_dst_segment_span_test.dart new file mode 100644 index 000000000..39c817cce --- /dev/null +++ b/test/sri_dst_segment_span_test.dart @@ -0,0 +1,145 @@ +// SLEEP-REGULARITY SEGMENT COVERAGE ACROSS A DST TRANSITION (#914). +// +// `_crossDaySri` marks the clock-minutes-of-day a hypnogram segment covers. +// The old code derived the span from the clock-minute DIFFERENCE of the +// segment's two endpoints, which is wrong across a DST change: in the autumn +// the local clock steps BACK an hour, so a 10-minute segment that straddles the +// fall-back read `endMin - startMin == 1390` and marked nearly the whole day as +// observed (and asleep, if the segment was sleep), inflating SRI. The fix walks +// the segment in ELAPSED minutes and maps each instant to its clock-minute, so +// only the minutes actually lived are marked. +// +// The host running these tests almost certainly does not sit in a DST zone, so +// we move the PROCESS timezone with libc setenv("TZ")+tzset() before asserting +// (same mechanism as day_window_dst_test). Dart's DateTime reads the C +// library's local time on every call, so this genuinely re-homes the local +// calendar. POSIX only — the test self-skips on Windows. + +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/compute/crossday_pipeline.dart' + show segmentClockMinutes; + +typedef _SetenvNative = Int32 Function(Pointer, Pointer, Int32); +typedef _SetenvDart = int Function(Pointer, Pointer, int); +typedef _UnsetenvNative = Int32 Function(Pointer); +typedef _UnsetenvDart = int Function(Pointer); +typedef _TzsetNative = Void Function(); +typedef _TzsetDart = void Function(); + +void _setProcessTz(String? tz) { + final lib = DynamicLibrary.process(); + final key = 'TZ'.toNativeUtf8(); + try { + if (tz == null) { + lib.lookupFunction<_UnsetenvNative, _UnsetenvDart>('unsetenv')(key); + } else { + final value = tz.toNativeUtf8(); + lib.lookupFunction<_SetenvNative, _SetenvDart>('setenv')(key, value, 1); + calloc.free(value); + } + lib.lookupFunction<_TzsetNative, _TzsetDart>('tzset')(); + } finally { + calloc.free(key); + } +} + +int _utcSec(int y, int mo, int d, int h, int mi) => + DateTime.utc(y, mo, d, h, mi).millisecondsSinceEpoch ~/ 1000; + +void main() { + final originalTz = Platform.environment['TZ']; + final skip = Platform.isWindows ? 'POSIX setenv/tzset only' : null; + + setUpAll(() => _setProcessTz('America/New_York')); + tearDownAll(() => _setProcessTz(originalTz)); + + // America/New_York: 2026-03-08 springs forward, 2026-11-01 falls back. + const d = {}; + + test( + 'the DST fixture timezone actually applied (guards the whole file)', + () { + expect( + DateTime(2026, 3, 8).timeZoneOffset, + const Duration(hours: -5), + reason: + 'setenv(TZ)+tzset() did not re-home the local calendar; the ' + 'assertions below would be vacuous', + ); + }, + skip: skip, + ); + + test( + 'autumn fall-back: a 10-minute segment covers 10 clock-minutes, not 1390', + () { + // 05:55 UTC = 01:55 EDT, 06:05 UTC = 01:05 EST — 10 minutes elapsed across + // the 02:00 EDT -> 01:00 EST fall-back. + final mins = segmentClockMinutes( + _utcSec(2026, 11, 1, 5, 55), + _utcSec(2026, 11, 1, 6, 5), + d, + ); + expect(mins.length, 10, reason: 'elapsed minutes, not the 1390 of #914'); + expect(mins.toSet(), { + 115, + 116, + 117, + 118, + 119, + 60, + 61, + 62, + 63, + 64, + }, reason: '01:55–01:59 EDT then the repeated 01:00–01:04 EST'); + }, + skip: skip, + ); + + test( + 'spring forward: a 10-minute segment covers 10 clock-minutes, not 70', + () { + // 06:55 UTC = 01:55 EST, 07:05 UTC = 03:05 EDT — 10 minutes elapsed across + // the 02:00 EST -> 03:00 EDT jump. + final mins = segmentClockMinutes( + _utcSec(2026, 3, 8, 6, 55), + _utcSec(2026, 3, 8, 7, 5), + d, + ); + expect(mins.length, 10); + expect( + mins.toSet(), + {115, 116, 117, 118, 119, 180, 181, 182, 183, 184}, + reason: + '01:55–01:59 EST then 03:00–03:04 EDT (02:00–02:59 never lived)', + ); + }, + skip: skip, + ); + + test('ordinary local-midnight crossing still wraps correctly', () { + // 2026-06-15 23:50 EDT -> 00:10 EDT (no DST change). 20 minutes, wrapping + // the local-midnight boundary. + final mins = segmentClockMinutes( + _utcSec(2026, 6, 16, 3, 50), + _utcSec(2026, 6, 16, 4, 10), + d, + ); + expect(mins.length, 20); + expect(mins.first, 1430); // 23:50 + expect(mins.contains(1439), isTrue); // 23:59 + expect(mins.contains(0), isTrue); // 00:00 + expect(mins.last, 9); // 00:09 + }, skip: skip); + + test('empty or reversed segment covers nothing', () { + final t = _utcSec(2026, 6, 16, 3, 50); + expect(segmentClockMinutes(t, t, d), isEmpty); + expect(segmentClockMinutes(t + 60, t, d), isEmpty); + }, skip: skip); +}