diff --git a/lib/compute/crossday_pipeline.dart b/lib/compute/crossday_pipeline.dart index 36a01c10c..a91a178d9 100644 --- a/lib/compute/crossday_pipeline.dart +++ b/lib/compute/crossday_pipeline.dart @@ -804,6 +804,89 @@ 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) 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 segmentClockMinutes(int startSec, int endSec, Map 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 asleep, List cov}) sriNightGrid( + Object? hyp, Map d) { + const epochsPerDay = 1440; + final asleep = List.filled(epochsPerDay, false); + final cov = List.filled(epochsPerDay, false); + // Epoch minute that owns each clock-minute slot; -1 = unclaimed. + final owner = List.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 @@ -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.filled(epochsPerDay, false); - final cov = List.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 diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart index 7657d4075..e13e2bf1a 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -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. /// diff --git a/test/ed2a_substrate_transfer_test.dart b/test/ed2a_substrate_transfer_test.dart index f93a7f329..56b52d208 100644 --- a/test/ed2a_substrate_transfer_test.dart +++ b/test/ed2a_substrate_transfer_test.dart @@ -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()); diff --git a/test/ed2b_algo_version_114_test.dart b/test/ed2b_algo_version_114_test.dart index dde2df1bf..70fcf60d0 100644 --- a/test/ed2b_algo_version_114_test.dart +++ b/test/ed2b_algo_version_114_test.dart @@ -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(); diff --git a/test/fixtures/whoop_freeze/gen4_minus0400.json b/test/fixtures/whoop_freeze/gen4_minus0400.json index fbdb553c5..d10043a67 100644 --- a/test/fixtures/whoop_freeze/gen4_minus0400.json +++ b/test/fixtures/whoop_freeze/gen4_minus0400.json @@ -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, @@ -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, @@ -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, @@ -76422,7 +76422,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76430,7 +76430,7 @@ }, { "date": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76438,7 +76438,7 @@ }, { "date": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -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, @@ -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, @@ -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, diff --git a/test/fixtures/whoop_freeze/gen4_plus0530.json b/test/fixtures/whoop_freeze/gen4_plus0530.json index 9795ebd6f..08a8c4238 100644 --- a/test/fixtures/whoop_freeze/gen4_plus0530.json +++ b/test/fixtures/whoop_freeze/gen4_plus0530.json @@ -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, @@ -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, @@ -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, @@ -76422,7 +76422,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76430,7 +76430,7 @@ }, { "date": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76438,7 +76438,7 @@ }, { "date": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -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, @@ -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, @@ -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, diff --git a/test/fixtures/whoop_freeze/gen4_utc.json b/test/fixtures/whoop_freeze/gen4_utc.json index 075a83fdf..0ac954612 100644 --- a/test/fixtures/whoop_freeze/gen4_utc.json +++ b/test/fixtures/whoop_freeze/gen4_utc.json @@ -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, @@ -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, @@ -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, @@ -76422,7 +76422,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76430,7 +76430,7 @@ }, { "date": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -76438,7 +76438,7 @@ }, { "date": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen4", "coverage_devices": "", @@ -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, @@ -77656,7 +77656,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "payload_json": { "day_id": "2026-07-14", "active_min": 239, @@ -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, diff --git a/test/fixtures/whoop_freeze/gen5_minus0400.json b/test/fixtures/whoop_freeze/gen5_minus0400.json index fcb51c36e..969d75f10 100644 --- a/test/fixtures/whoop_freeze/gen5_minus0400.json +++ b/test/fixtures/whoop_freeze/gen5_minus0400.json @@ -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, @@ -26121,7 +26121,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51914,7 +51914,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76935,7 +76935,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76943,7 +76943,7 @@ }, { "date": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76951,7 +76951,7 @@ }, { "date": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76961,7 +76961,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, @@ -78169,7 +78169,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "payload_json": { "day_id": "2026-07-14", "active_min": 240, @@ -79377,7 +79377,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/fixtures/whoop_freeze/gen5_plus0530.json b/test/fixtures/whoop_freeze/gen5_plus0530.json index 08d320a6f..f46a40e77 100644 --- a/test/fixtures/whoop_freeze/gen5_plus0530.json +++ b/test/fixtures/whoop_freeze/gen5_plus0530.json @@ -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, @@ -26121,7 +26121,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51914,7 +51914,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76935,7 +76935,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76943,7 +76943,7 @@ }, { "date": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76951,7 +76951,7 @@ }, { "date": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76961,7 +76961,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, @@ -78169,7 +78169,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "payload_json": { "day_id": "2026-07-14", "active_min": 240, @@ -79377,7 +79377,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/fixtures/whoop_freeze/gen5_utc.json b/test/fixtures/whoop_freeze/gen5_utc.json index f02ab5dcb..8e678a9a7 100644 --- a/test/fixtures/whoop_freeze/gen5_utc.json +++ b/test/fixtures/whoop_freeze/gen5_utc.json @@ -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, @@ -26121,7 +26121,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "payload_json": { "date": "2026-07-14", "day_confidence": 0.6, @@ -51914,7 +51914,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "payload_json": { "date": "2026-07-15", "day_confidence": 0.6, @@ -76935,7 +76935,7 @@ "metric_series_version": [ { "date": "2026-07-13", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76943,7 +76943,7 @@ }, { "date": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76951,7 +76951,7 @@ }, { "date": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "source": "band", "device_family": "gen5", "coverage_devices": "", @@ -76961,7 +76961,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, @@ -78169,7 +78169,7 @@ }, { "day_id": "2026-07-14", - "algo_version": 137, + "algo_version": 138, "payload_json": { "day_id": "2026-07-14", "active_min": 239, @@ -79377,7 +79377,7 @@ }, { "day_id": "2026-07-15", - "algo_version": 137, + "algo_version": 138, "payload_json": { "day_id": "2026-07-15", "active_min": 40, diff --git a/test/sri_dst_segment_span_test.dart b/test/sri_dst_segment_span_test.dart new file mode 100644 index 000000000..40c4c064b --- /dev/null +++ b/test/sri_dst_segment_span_test.dart @@ -0,0 +1,240 @@ +// 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, sriNightGrid; + +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; + + // DynamicLibrary.process() has no setenv/tzset off POSIX, so the hooks must + // not run there or they fail the file before the per-test skips apply. + setUpAll(() { + if (skip == null) _setProcessTz('America/New_York'); + }); + tearDownAll(() { + if (skip == null) _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); + + // #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); + + test('repeated fall-back hour: wake in one occurrence stays wake', () { + // 05:00–06:00 UTC = 01:00–01:59 EDT (awake), then 06:00–07:00 UTC = + // 01:00–01:59 EST (asleep). Same clock-minutes, two lived hours: the + // earlier one owns the slot, so the wake hour is not turned into sleep. + final grid = sriNightGrid([ + { + 'start': _utcSec(2026, 11, 1, 5, 0), + 'end': _utcSec(2026, 11, 1, 6, 0), + 'stage': 'wake', + }, + { + 'start': _utcSec(2026, 11, 1, 6, 0), + 'end': _utcSec(2026, 11, 1, 7, 0), + 'stage': 'deep', + }, + ], d); + for (var m = 60; m < 120; m++) { + expect(grid.cov[m], isTrue); + expect(grid.asleep[m], isFalse, reason: 'minute $m'); + } + // Same answer whatever order the segments arrive in. + final rev = sriNightGrid([ + { + 'start': _utcSec(2026, 11, 1, 6, 0), + 'end': _utcSec(2026, 11, 1, 7, 0), + 'stage': 'deep', + }, + { + 'start': _utcSec(2026, 11, 1, 5, 0), + 'end': _utcSec(2026, 11, 1, 6, 0), + 'stage': 'wake', + }, + ], d); + expect(rev.asleep.sublist(60, 120).any((a) => a), isFalse); + }, skip: skip); + + test('shared boundary minute stays asleep in the grid', () { + final grid = sriNightGrid([ + { + 'start': _utcSec(2026, 6, 15, 4, 0), + 'end': _utcSec(2026, 6, 15, 4, 5) + 30, + 'stage': 'light', + }, + { + 'start': _utcSec(2026, 6, 15, 4, 5) + 30, + 'end': _utcSec(2026, 6, 15, 4, 10), + 'stage': 'wake', + }, + ], d); + expect(grid.asleep[5], isTrue); + expect(grid.asleep[6], isFalse); + expect(grid.cov[9], isTrue); + }, skip: skip); +}