From 48ad175cd95f470ff4fb390d24912e1c4fb5e2d4 Mon Sep 17 00:00:00 2001 From: uvtqt Date: Thu, 26 Nov 2026 19:38:36 +0100 Subject: [PATCH 1/2] fix(sri): walk sleep segments in elapsed minutes across DST changes Sleep-regularity built its per-minute coverage grid by mapping each hypnogram segment's two endpoints to clock-minute-of-day and taking the difference as the span. That is wrong whenever the local clock is not monotone in elapsed time. Across the autumn fall-back the clock steps back an hour, so a 10-minute segment straddling it read `endMin - startMin == 1390` and marked nearly the whole day as observed (and asleep, if the segment was sleep), inflating the published SRI. The spring-forward jump over-counted by up to an hour as well. Walk the segment in elapsed minutes instead and map each instant to its clock-minute (new `segmentClockMinutes` helper beside `_nightClockMin`). Only the minutes actually lived are marked, and an ordinary local-midnight crossing is handled by the same per-minute `% 1440`. Bump kAlgoVersion 133 -> 134: this changes the SRI output for nights whose sleep segments cross a DST change; every other night is unchanged. Fixes #914. Co-Authored-By: Claude Opus 4.8 --- lib/compute/crossday_pipeline.dart | 48 +++++---- lib/compute/derivation_engine.dart | 9 +- test/sri_dst_segment_span_test.dart | 145 ++++++++++++++++++++++++++++ 3 files changed, 182 insertions(+), 20 deletions(-) create mode 100644 test/sri_dst_segment_span_test.dart diff --git a/lib/compute/crossday_pipeline.dart b/lib/compute/crossday_pipeline.dart index 6e30ae520..c123f2818 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 @@ -1264,29 +1283,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 43f87d4f6..7e851f2c2 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -1956,7 +1956,14 @@ import 'vendor_sleep.dart'; // series over the newest 400 days, where older rows used to fall back to the // compressed per-row series. Typical band users unchanged; stored crossday // output only. -const int kAlgoVersion = 135; +// 135 → 136 (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 = 136; /// 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); +} From 214d651d0208bf70500d126127b57e993092bb37 Mon Sep 17 00:00:00 2001 From: uvtqt Date: Fri, 27 Nov 2026 21:48:11 +0100 Subject: [PATCH 2/2] fix(sri): cover every touched minute, preserving non-DST parity Review on #915 (IamYVJ) found segmentClockMinutes dropped the last partly-touched minute whenever a segment started off a minute boundary: sampling at startSec + k*60 for ceil(elapsed/60) steps covered 0-4 for a 00:00:30-00:05:30 segment instead of 0-5. Hypnogram segments come from per-second labels, so ~49% of arbitrary-second segments differed, and the dropped boundary minute also moved the sleep/wake bit at sleep->wake transitions (asleep minute flipping to wake). Anchor the walk at the start of the minute startSec falls in and count the minutes the segment TOUCHES: base = startSec - startSec % 60 n = ((startSec % 60) + (endSec - startSec) + 59) ~/ 60 This matches the old ceil(endClock) - floor(startClock) span on non-DST nights (so only DST nights change, as the changelog now states) while keeping the elapsed-time step that fixes the fall-back over-count (#914). Because the caller only ever sets cov/asleep true, a boundary minute touched by both a sleep and a wake pass stays asleep, as before. Tests: add fractional-second parity (00:00:30-00:05:10 covers 0-5) and a sleep/wake boundary sharing its minute. Clarify the changelog: the bump re-derives every day on disk, only DST-night SRI values differ. Co-Authored-By: Claude Opus 4.8 --- lib/compute/crossday_pipeline.dart | 36 +++++++++++++++++++---------- lib/compute/derivation_engine.dart | 15 +++++++----- test/sri_dst_segment_span_test.dart | 35 ++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 18 deletions(-) diff --git a/lib/compute/crossday_pipeline.dart b/lib/compute/crossday_pipeline.dart index c123f2818..5e4026f4b 100644 --- a/lib/compute/crossday_pipeline.dart +++ b/lib/compute/crossday_pipeline.dart @@ -798,21 +798,33 @@ double _nightClockMin(int epochSec, Map d) { } /// 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). +/// (epoch SECONDS) TOUCHES — every minute `floor(startClock)..ceil(endClock)`, +/// one entry per touched minute. We anchor the walk at the start of the minute +/// `startSec` falls in and STEP through elapsed time, mapping each minute +/// through [_nightClockMin]. This keeps two properties at once: +/// - Touched-minute parity with the old `ceil(endClock) - floor(startClock)` +/// span on ordinary nights: segments built from per-second labels start on +/// arbitrary seconds, so a plain `ceil(elapsed/60)` walk from `startSec` +/// dropped the last partly-touched minute (00:00:30–00:05:30 covered 0–4, +/// not 0–5) and flipped sleep/wake boundary bits. The `startSec % 60` offset +/// in the minute count restores the touched edge (reviewer measurement on +/// #915). +/// - DST honesty: across the autumn fall-back the clock steps back an hour, so +/// it is NOT monotone in elapsed time. Deriving the span from the endpoints' +/// clock-minute DIFFERENCE over-counted — a 10-minute segment spanned 1390 +/// clock-minutes (#914). Stepping elapsed time and mapping each minute marks +/// only the minutes actually lived. +/// The repeated autumn hour maps two instants to the same clock-minute; that is +/// fine, since the caller only ever sets `cov`/`asleep` true (never false), so a +/// boundary minute touched by both a sleep and a wake pass stays asleep. Assumes +/// `clock_shift_sec` is a whole number of minutes. Empty/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); + final base = startSec - (startSec % 60); // start of the first touched minute + final n = math.min(((startSec % 60) + (endSec - startSec) + 59) ~/ 60, 1440); return [ - for (var k = 0; k < elapsedMin; k++) - _nightClockMin(startSec + k * 60, d).floor() % 1440, + for (var k = 0; k < n; k++) _nightClockMin(base + k * 60, d).floor() % 1440, ]; } diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart index 7e851f2c2..5c4bd1609 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -1957,12 +1957,15 @@ import 'vendor_sleep.dart'; // compressed per-row series. Typical band users unchanged; stored crossday // output only. // 135 → 136 (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. +// segment through the minutes it TOUCHES, stepping elapsed time, 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. The walk keeps touched-minute parity with the +// old span on non-DST nights, so while the bump re-derives every day still on +// disk (rows are immutable per version), only nights whose sleep segments cross +// a DST change get a different SRI value. const int kAlgoVersion = 136; /// 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 index 39c817cce..7ebda64e7 100644 --- a/test/sri_dst_segment_span_test.dart +++ b/test/sri_dst_segment_span_test.dart @@ -142,4 +142,39 @@ void main() { expect(segmentClockMinutes(t, t, d), isEmpty); expect(segmentClockMinutes(t + 60, t, d), isEmpty); }, skip: skip); + + // #915 review: segments are built from per-second labels, so they start/end on + // arbitrary seconds. The walk must cover every minute the segment TOUCHES + // (old floor(start)..ceil(end) semantics), including the last partly-touched + // minute — a naive ceil(elapsed/60) walk from startSec dropped it. + test('fractional-second segment covers every touched minute (parity)', () { + // 00:00:30 -> 00:05:10 EDT touches minutes 0..5 (not 0..4). + final mins = segmentClockMinutes( + _utcSec(2026, 6, 15, 4, 0) + 30, + _utcSec(2026, 6, 15, 4, 5) + 10, + d, + ); + expect(mins.toSet(), {0, 1, 2, 3, 4, 5}); + expect(mins.length, 6); + }, skip: skip); + + test('adjacent sleep/wake segments share the boundary minute (asleep wins)', + () { + // A sleep segment ending at 00:05:30 and a wake segment starting there both + // touch minute 5. Since _crossDaySri only ever sets asleep[m] true, that + // boundary minute stays asleep — the old behaviour the walk must preserve. + final sleep = segmentClockMinutes( + _utcSec(2026, 6, 15, 4, 0), + _utcSec(2026, 6, 15, 4, 5) + 30, + d, + ).toSet(); + final wake = segmentClockMinutes( + _utcSec(2026, 6, 15, 4, 5) + 30, + _utcSec(2026, 6, 15, 4, 10), + d, + ).toSet(); + expect(sleep, contains(5)); + expect(wake, contains(5)); + expect(sleep.intersection(wake), {5}, reason: 'exactly one shared minute'); + }, skip: skip); }