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
128 changes: 86 additions & 42 deletions lib/compute/crossday_pipeline.dart
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,89 @@ 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) 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; the
/// caller (sriNightGrid) keeps the earlier one. Assumes
/// `clock_shift_sec` is a whole number of minutes. Empty/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 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 < n; k++) _nightClockMin(base + k * 60, d).floor() % 1440,
];
}

/// One night's SRI grid: which clock-minutes-of-day [0,1440) the hypnogram
/// [hyp] observed ([cov]) and which of those were asleep ([asleep]).
///
/// Segment bounds are epoch SECONDS. Each segment is walked in ELAPSED minutes
/// and every instant mapped to its clock-minute (segmentClockMinutes), so a
/// segment crossing local midnight AND one crossing a DST change are both
/// covered by the same per-minute modulo. 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 a
/// 10-minute segment read endMin-startMin == 1390 and marked nearly the whole
/// day observed/asleep (#914).
///
/// The repeated autumn hour maps two lived minutes onto one clock-minute. The
/// EARLIER lived minute owns the slot, so being awake in one occurrence and
/// asleep in the other can't turn the wake into sleep. Two segments touching
/// the SAME lived minute (a partly-covered boundary) still share it, asleep
/// winning, as before.
({List<bool> asleep, List<bool> cov}) sriNightGrid(
Object? hyp, Map<String, dynamic> d) {
const epochsPerDay = 1440;
final asleep = List<bool>.filled(epochsPerDay, false);
final cov = List<bool>.filled(epochsPerDay, false);
// Epoch minute that owns each clock-minute slot; -1 = unclaimed.
final owner = List<int>.filled(epochsPerDay, -1);
if (hyp is! List) return (asleep: asleep, cov: cov);
for (final seg in hyp) {
if (seg is! Map) continue;
final start = (seg['start'] as num?)?.toDouble();
final end = (seg['end'] as num?)?.toDouble();
final stage = seg['stage'] as String?;
if (start == null || end == null) continue;
// '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';
final s0 = start.round();
final firstMin = (s0 - (s0 % 60)) ~/ 60;
final mins = segmentClockMinutes(s0, end.round(), d);
for (var k = 0; k < mins.length; k++) {
final m = mins[k];
final em = firstMin + k;
if (owner[m] != -1 && em > owner[m]) continue; // later repeat
if (em != owner[m]) {
asleep[m] = false; // an earlier lived minute takes the slot
owner[m] = em;
}
cov[m] = true;
if (asleepSeg) asleep[m] = true;
}
}
return (asleep: asleep, cov: cov);
}

/// 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
Expand Down Expand Up @@ -1259,48 +1342,9 @@ bool _isNextDay(String a, String b) {
}
}
gridDates.add(date);
// Fresh blank day grid (all wake, all invalid until covered).
final asleep = List<bool>.filled(epochsPerDay, false);
final cov = List<bool>.filled(epochsPerDay, false);

final hyp = d['hypnogram'];
if (hyp is List) {
for (final seg in hyp) {
if (seg is! Map) continue;
final start = (seg['start'] as num?)?.toDouble();
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;
cov[m] = true;
if (asleepSeg) asleep[m] = true;
}
}
}
sleepWake.addAll(asleep);
valid.addAll(cov);
final grid = sriNightGrid(d['hypnogram'], d);
sleepWake.addAll(grid.asleep);
valid.addAll(grid.cov);
}

// SLP-08's per-pair floor. The analytics default is half a clock day (720
Expand Down
13 changes: 12 additions & 1 deletion lib/compute/derivation_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1968,7 +1968,18 @@ import 'vendor_sleep.dart';
// today, not yesterday's; the rolling HRV timeline skips differences across
// holes and needs 10 real pairs; a night still going at midnight is owned by
// the day it ends. Band days move through all three; stored day output only.
const int kAlgoVersion = 137;
// 137 → 138 (analytics change): the sleep-regularity grid walks each hypnogram
// 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 hypnogram segments
// (sleep or wake) cross a DST change get a different SRI value. In the
// repeated autumn hour each clock-minute keeps its first occurrence only.
const int kAlgoVersion = 138;
/// The sibling SHAs this version was derived against, asserted against
/// pubspec.yaml in test/db_serve_version_and_reads_test.dart.
///
Expand Down
2 changes: 1 addition & 1 deletion test/ed2a_substrate_transfer_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ void main() {
markTestSkipped('committed golden is UTC; run this test with TZ=UTC');
return;
}
expect(kAlgoVersion, 137, reason: 'ED-2b repins analytics; transfer remains exact');
expect(kAlgoVersion, 138, reason: 'ED-2b repins analytics; transfer remains exact');
final fixture = _fixture();
final baseline = substrateFromDecodedPage(fixture.frames, fixture.rr);
final transferred = Substrate.fromTransfer(baseline.toJson());
Expand Down
2 changes: 1 addition & 1 deletion test/ed2b_algo_version_114_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import 'package:openstrap_edge/compute/derivation_engine.dart';
void main() {
// WHY: finalized days need a new version when the analytics pin changes outputs.
test('ED-2b adoption and workout rest repin name their output changes', () {
expect(kAlgoVersion, 137);
expect(kAlgoVersion, 138);
// #113 moved code between repos with no output change, so the version holds.
expect(kAnalyticsPin, 'b92686a20e4a9a1852d5e43c52d3e3b42f360e7b');
final src = File('lib/compute/derivation_engine.dart').readAsStringSync();
Expand Down
18 changes: 9 additions & 9 deletions test/fixtures/whoop_freeze/gen4_minus0400.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"day_result": [
{
"day_id": "2026-07-13",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"date": "2026-07-13",
"day_confidence": 0.6,
Expand Down Expand Up @@ -25943,7 +25943,7 @@
},
{
"day_id": "2026-07-14",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"date": "2026-07-14",
"day_confidence": 0.6,
Expand Down Expand Up @@ -51563,7 +51563,7 @@
},
{
"day_id": "2026-07-15",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"date": "2026-07-15",
"day_confidence": 0.6,
Expand Down Expand Up @@ -76422,23 +76422,23 @@
"metric_series_version": [
{
"date": "2026-07-13",
"algo_version": 137,
"algo_version": 138,
"source": "band",
"device_family": "gen4",
"coverage_devices": "",
"priority_hash": "accel1Hz=;hr1Hz=;ppgRedIr=;rrIntervals=;skinTempRaw="
},
{
"date": "2026-07-14",
"algo_version": 137,
"algo_version": 138,
"source": "band",
"device_family": "gen4",
"coverage_devices": "",
"priority_hash": "accel1Hz=;hr1Hz=;ppgRedIr=;rrIntervals=;skinTempRaw="
},
{
"date": "2026-07-15",
"algo_version": 137,
"algo_version": 138,
"source": "band",
"device_family": "gen4",
"coverage_devices": "",
Expand All @@ -76448,7 +76448,7 @@
"wake_day_features": [
{
"day_id": "2026-07-13",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"day_id": "2026-07-13",
"active_min": 90,
Expand Down Expand Up @@ -77656,7 +77656,7 @@
},
{
"day_id": "2026-07-14",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"day_id": "2026-07-14",
"active_min": 240,
Expand Down Expand Up @@ -78864,7 +78864,7 @@
},
{
"day_id": "2026-07-15",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"day_id": "2026-07-15",
"active_min": 40,
Expand Down
18 changes: 9 additions & 9 deletions test/fixtures/whoop_freeze/gen4_plus0530.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"day_result": [
{
"day_id": "2026-07-13",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"date": "2026-07-13",
"day_confidence": 0.6,
Expand Down Expand Up @@ -25943,7 +25943,7 @@
},
{
"day_id": "2026-07-14",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"date": "2026-07-14",
"day_confidence": 0.6,
Expand Down Expand Up @@ -51563,7 +51563,7 @@
},
{
"day_id": "2026-07-15",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"date": "2026-07-15",
"day_confidence": 0.6,
Expand Down Expand Up @@ -76422,23 +76422,23 @@
"metric_series_version": [
{
"date": "2026-07-13",
"algo_version": 137,
"algo_version": 138,
"source": "band",
"device_family": "gen4",
"coverage_devices": "",
"priority_hash": "accel1Hz=;hr1Hz=;ppgRedIr=;rrIntervals=;skinTempRaw="
},
{
"date": "2026-07-14",
"algo_version": 137,
"algo_version": 138,
"source": "band",
"device_family": "gen4",
"coverage_devices": "",
"priority_hash": "accel1Hz=;hr1Hz=;ppgRedIr=;rrIntervals=;skinTempRaw="
},
{
"date": "2026-07-15",
"algo_version": 137,
"algo_version": 138,
"source": "band",
"device_family": "gen4",
"coverage_devices": "",
Expand All @@ -76448,7 +76448,7 @@
"wake_day_features": [
{
"day_id": "2026-07-13",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"day_id": "2026-07-13",
"active_min": 90,
Expand Down Expand Up @@ -77656,7 +77656,7 @@
},
{
"day_id": "2026-07-14",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"day_id": "2026-07-14",
"active_min": 240,
Expand Down Expand Up @@ -78864,7 +78864,7 @@
},
{
"day_id": "2026-07-15",
"algo_version": 137,
"algo_version": 138,
"payload_json": {
"day_id": "2026-07-15",
"active_min": 40,
Expand Down
Loading