Repository navigation
fix(sri): walk sleep segments in elapsed minutes across DST changes #915
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -797,6 +797,25 @@ double _nightClockMin(int epochSec, Map<String, dynamic> 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<int> segmentClockMinutes(int startSec, int endSec, Map<String, dynamic> 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, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Repeated minutes turn wake into sleep When a repeated fall-back clock minute is asleep in one occurrence and awake in the other, Define and implement an explicit policy for combining sleep and wake observations that map to the same clock-minute, rather than allowing sleep to win by default. Prompt for AI agentsIn `lib/compute/crossday_pipeline.dart` at line 815:
**Repeated minutes turn wake into sleep**
When a repeated fall-back clock minute is asleep in one occurrence and awake in the other, `_crossDaySri` maps both occurrences of a repeated fall-back clock minute to the same grid index, then sets `asleep[m]` to true for any sleep segment without resolving a conflicting wake segment. Those minutes are therefore classified as asleep even when the other occurrence was awake, biasing SRI.
Define and implement an explicit policy for combining sleep and wake observations that map to the same clock-minute, rather than allowing sleep to win by default.
Comment on lines
+812
to
+815
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep the partially covered trailing minute in The new walk samples the start instant and then each elapsed minute after it. Hypnogram bounds are not minute-aligned. Sample the start instant, then each whole-minute boundary inside the segment. Keep the DST-aware Suggested fix
|
||
| ]; | ||
| } | ||
|
|
||
| /// 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; | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Unchanged nights are re-derived When stored day results use version 133 and the device has multiple raw days in scope, existing day results still stamped with algorithm version 133 are treated as unfinalized after this bump, even though this change only alters the cross-day SRI calculation. Use a cross-day-specific version for this SRI change, or otherwise invalidate only the cross-day artifact without marking unchanged per-day results stale. Prompt for AI agentsIn `lib/compute/derivation_engine.dart` at line 1957:
**Unchanged nights are re-derived**
When stored day results use version 133 and the device has multiple raw days in scope, existing day results still stamped with algorithm version 133 are treated as unfinalized after this bump, even though this change only alters the cross-day SRI calculation. `selectLightDeriveDays` then sends those raw days through per-day derivation one at a time, consuming repeated passes to recompute unchanged nightly results.
Use a cross-day-specific version for this SRI change, or otherwise invalidate only the cross-day artifact without marking unchanged per-day results stale. |
||
| /// The sibling SHAs this version was derived against, asserted against | ||
| /// pubspec.yaml in test/db_serve_version_and_reads_test.dart. | ||
| /// | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<Utf8>, Pointer<Utf8>, Int32); | ||
| typedef _SetenvDart = int Function(Pointer<Utf8>, Pointer<Utf8>, int); | ||
| typedef _UnsetenvNative = Int32 Function(Pointer<Utf8>); | ||
| typedef _UnsetenvDart = int Function(Pointer<Utf8>); | ||
| 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')); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Windows test suite fails before skips When the test suite runs on Windows, Guard the suite-level timezone setup and teardown so they do not call Prompt for AI agentsIn `test/sri_dst_segment_span_test.dart` at line 57:
**Windows test suite fails before skips**
When the test suite runs on Windows, `setUpAll` calls `_setProcessTz`, which looks up unavailable POSIX `setenv`/`tzset` symbols before per-test skips run; teardown also attempts to restore the timezone. The suite fails instead of being skipped.
Guard the suite-level timezone setup and teardown so they do not call `_setProcessTz` on Windows. |
||
| tearDownAll(() => _setProcessTz(originalTz)); | ||
|
Comment on lines
+57
to
+58
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Concurrent timezone tests interfere When this suite overlaps another timezone-dependent suite in the same process, Run timezone-mutating tests in an isolated process or serialize them so their process-wide timezone changes cannot overlap. Prompt for AI agentsIn `test/sri_dst_segment_span_test.dart` at lines 57-58:
**Concurrent timezone tests interfere**
When this suite overlaps another timezone-dependent suite in the same process, `setUpAll` changes the process-wide timezone through `_setProcessTz`, and `tearDownAll` restores the value captured at suite startup. The other suite can observe the wrong timezone or have its timezone reset, making timezone assertions fail or become misleading.
Run timezone-mutating tests in an isolated process or serialize them so their process-wide timezone changes cannot overlap. |
||
|
|
||
| // America/New_York: 2026-03-08 springs forward, 2026-11-01 falls back. | ||
| const d = <String, dynamic>{}; | ||
|
|
||
| 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); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Medium · SRI coverage misses touched minutes
When a hypnogram segment is not aligned to clock-minute boundaries and overlaps a minute that the start-anchored samples do not hit,
segmentClockMinutessamples at 60-second offsets fromstartSec, so it omits clock-minute bins the segment overlaps._crossDaySrileaves those bins uncovered, changing SRI coverage on ordinary nights too.Mark every clock-minute bin intersected by the segment rather than sampling at 60-second offsets from its start.
Prompt for AI agents