Modern Apps git

← Modern-Apps.git

clock: an alarm set during the second fall-back hour fires in that hour

Commit
f4d6b9fc5cc532dbb325f5546fae471ec192c996
Author
Vayun Mathur <[email protected]>
When
2026-12-01 15:04 UTC (4 days ago)
Parents
e2e2bbe
calculateNextTriggerMillis resolved the alarm time via
LocalDateTime.toInstant, which always picks the earlier
offset: on fall-back day (America/New_York 2026-11-01,
01:00-02:00 twice), setting 01:30 at 01:15 EST (second
pass) resolved to the already-past 01:30 EDT and stepped a
full day (24h15m late; a Sundays-only alarm skipped a
week).

Each candidate date now expands through occurrences(),
returning both overlap instants when a genuine second pass
exists (validated by local-time round-trip, which rejects
DST-gap resolutions), and the first future occurrence on a
matching weekday wins; the wear protocol mirror got the
same fix (its clock-wear duplicate needs syncing โ€” spawned
separately). Four regression tests (one-shot and
Sunday-only in the second pass; a before-overlap guard
proving the first occurrence still wins) failed pre-fix.
Verified: :clock:testDevUnitTest 272 tests pass; lint
errors are pre-existing on untouched files.

Diff

clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.kt b/clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.ktindex 0a3bf90903..598358144d 100644--- a/clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.kt+++ b/clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.kt@@ -3,11 +3,13 @@ package com.vayunmathur.clock.domain import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone+import kotlinx.datetime.offsetAt import kotlinx.datetime.plus import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json+import kotlin.time.Duration.Companion.days import kotlin.time.Instant  /**@@ -157,6 +159,11 @@ fun buildWearClockSnapshot(  * [timeZone]. Calendar-based day stepping, matching the phone scheduler:  * adding a fixed 24h would land an hour off across DST transitions.  * An alarm whose time is exactly now fires tomorrow / on its next day.+ *+ * On a fall-back overlap day the wall time occurs twice; when "now" is+ * already inside the second pass (the earlier-offset instant is past but+ * the later-offset one is still ahead) the alarm fires at that second+ * occurrence today, matching the phone scheduler.  */ fun nextWearAlarmTriggerMillis(     hour: Int,@@ -167,24 +174,41 @@ fun nextWearAlarmTriggerMillis( ): Long {     val now = Instant.fromEpochMilliseconds(nowMillis)     val today = now.toLocalDateTime(timeZone).date-    var candidate = LocalDateTime(today, kotlinx.datetime.LocalTime(hour, minute))-    if (candidate.toInstant(timeZone) <= now) {-        candidate = LocalDateTime(-            candidate.date.plus(1, DateTimeUnit.DAY), candidate.time,-        )-    }-    if (daysMask == 0) return candidate.toInstant(timeZone).toEpochMilliseconds()-    repeat(7) {-        val bit = when (candidate.dayOfWeek) {-            kotlinx.datetime.DayOfWeek.SUNDAY -> 0-            else -> candidate.dayOfWeek.ordinal + 1 // Mon ordinal 0 -> bit 1+    val time = kotlinx.datetime.LocalTime(hour, minute)+    // Scan today through a week out (8 dates: a weekday-only alarm whose+    // time already passed today legitimately fires 7 days from today).+    for (dayOffset in 0..7) {+        val candidate = LocalDateTime(today.plus(dayOffset, DateTimeUnit.DAY), time)+        if (daysMask != 0) {+            val bit = when (candidate.dayOfWeek) {+                kotlinx.datetime.DayOfWeek.SUNDAY -> 0+                else -> candidate.dayOfWeek.ordinal + 1 // Mon ordinal 0 -> bit 1+            }+            if (daysMask and (1 shl bit) == 0) continue         }-        if (daysMask and (1 shl bit) != 0) {-            return candidate.toInstant(timeZone).toEpochMilliseconds()+        for (occurrence in candidate.wearOccurrences(timeZone)) {+            if (occurrence > now) return occurrence.toEpochMilliseconds()         }-        candidate = LocalDateTime(-            candidate.date.plus(1, DateTimeUnit.DAY), candidate.time,-        )     }-    return candidate.toInstant(timeZone).toEpochMilliseconds()+    return LocalDateTime(today.plus(8, DateTimeUnit.DAY), time)+        .toInstant(timeZone).toEpochMilliseconds()+}++/**+ * The instant(s) this wall time occurs on its date in [timeZone]: one,+ * except on a fall-back overlap day where it occurs twice โ€” the+ * earlier-offset instant plus the same wall time under the later offset.+ * The local-time round-trip rejects gap resolutions and offset changes+ * that belong to the next day rather than to a second pass today.+ */+private fun LocalDateTime.wearOccurrences(timeZone: TimeZone): List<Instant> {+    val first = toInstant(timeZone)+    val laterOffset = timeZone.offsetAt(first.plus(1.days))+    if (laterOffset == timeZone.offsetAt(first)) return listOf(first)+    val second = toInstant(laterOffset)+    return if (second > first && second.toLocalDateTime(timeZone) == this) {+        listOf(first, second)+    } else {+        listOf(first)+    } }
clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.kt b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.ktindex 3b1591c9a3..72ab7a1760 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.kt@@ -11,10 +11,12 @@ import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.isoDayNumber+import kotlinx.datetime.offsetAt import kotlinx.datetime.plus import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock+import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.minutes import kotlin.time.Instant @@ -233,47 +235,60 @@ object AlarmScheduler {      * the autumn one, and also shifts the weekday the repeat mask is tested      * against near midnight. [LocalDateTime.toInstant] resolves a wall time      * inside a DST gap forward and an overlap to the earlier offset.+     *+     * The overlap needs the second pass as well: on the fall-back day a+     * wall time happens twice, so when "now" is already inside the second+     * pass (the earlier-offset instant is past but the later-offset one is+     * still ahead) the alarm fires at that second occurrence today, not+     * tomorrow or on its next repeat day.      */     internal fun calculateNextTriggerMillis(alarm: Alarm, now: Instant, timeZone: TimeZone): Long {         val today = now.toLocalDateTime(timeZone).date -        // 1. Create a LocalDateTime for today at the alarm time-        var candidate = LocalDateTime(today, alarm.time)--        // 2. Initial check: if the time has already passed today,-        // we must start looking from tomorrow-        if (candidate.toInstant(timeZone) <= now) {-            candidate = candidate.nextDay(alarm)-        }--        // 3. Scenario A: No days selected (One-shot alarm)-        if (alarm.days == 0) {-            return candidate.toInstant(timeZone).toEpochMilliseconds()-        }--        // 4. Scenario B: Recurring days (Find the next matching day)-        // We check up to 7 days in the future-        repeat(DAYS_IN_WEEK) {-            val dayOfWeek = candidate.dayOfWeek // kotlinx.datetime.DayOfWeek+        // Scan today through a week out (8 dates: a weekday-only alarm whose+        // time already passed today legitimately fires 7 days from today).+        for (dayOffset in 0..DAYS_IN_WEEK) {+            val candidate = LocalDateTime(today.plus(dayOffset, DateTimeUnit.DAY), alarm.time) -            // Map kotlinx DayOfWeek (Mon=1...Sun=7) to your bitmask (Sun=0...Sat=6)-            val bit = if (dayOfWeek == DayOfWeek.SUNDAY) 0 else dayOfWeek.isoDayNumber--            if ((alarm.days and (1 shl bit)) != 0) {-                return candidate.toInstant(timeZone).toEpochMilliseconds()+            if (alarm.days != 0) {+                // Map kotlinx DayOfWeek (Mon=1...Sun=7) to the bitmask (Sun=0...Sat=6)+                val dayOfWeek = candidate.dayOfWeek+                val bit = if (dayOfWeek == DayOfWeek.SUNDAY) 0 else dayOfWeek.isoDayNumber+                if ((alarm.days and (1 shl bit)) == 0) continue             } -            // Move to the next day and check again-            candidate = candidate.nextDay(alarm)+            for (occurrence in candidate.occurrences(timeZone)) {+                if (occurrence > now) return occurrence.toEpochMilliseconds()+            }         } -        // Fallback (should be unreachable if bits are set)-        return candidate.toInstant(timeZone).toEpochMilliseconds()+        // Fallback (unreachable for masks with any of bits 0..6 set)+        return LocalDateTime(today.plus(DAYS_IN_WEEK + 1, DateTimeUnit.DAY), alarm.time)+            .toInstant(timeZone).toEpochMilliseconds()     } -    /** Same wall-clock time on the next calendar date. */-    private fun LocalDateTime.nextDay(alarm: Alarm): LocalDateTime =-        LocalDateTime(date.plus(1, DateTimeUnit.DAY), alarm.time)+    /**+     * The instant(s) this wall time occurs on its date in [timeZone]: one,+     * except on a fall-back overlap day where it occurs twice โ€” the+     * earlier-offset instant [LocalDateTime.toInstant] resolves to, plus+     * the same wall time under the later offset when that is genuinely a+     * second occurrence of this local time.+     */+    private fun LocalDateTime.occurrences(timeZone: TimeZone): List<Instant> {+        val first = toInstant(timeZone)+        // The offset in force a day later is the post-transition one on an+        // overlap day (transitions do not recur within a day), so it names+        // the second pass. The local-time round-trip rejects lookalikes:+        // gap resolutions, and dates whose next day merely has a new offset.+        val laterOffset = timeZone.offsetAt(first.plus(1.days))+        if (laterOffset == timeZone.offsetAt(first)) return listOf(first)+        val second = toInstant(laterOffset)+        return if (second > first && second.toLocalDateTime(timeZone) == this) {+            listOf(first, second)+        } else {+            listOf(first)+        }+    }      private const val DAYS_IN_WEEK = 7     private const val TAG = "AlarmScheduler"
clock/src/test/java/com/vayunmathur/clock/domain/WearClockProtocolTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/domain/WearClockProtocolTest.kt b/clock/src/test/java/com/vayunmathur/clock/domain/WearClockProtocolTest.ktindex d085cc7dea..d569b7096a 100644--- a/clock/src/test/java/com/vayunmathur/clock/domain/WearClockProtocolTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/domain/WearClockProtocolTest.kt@@ -109,6 +109,18 @@ class WearClockProtocolTest {         )     } +    @Test+    fun nextTriggerDuringSecondFallBackOccurrenceFiresToday() {+        // 2026-11-01 fall-back in New York: at 06:15Z the wall clock reads+        // 01:15 EST (second pass through 01:00-02:00), so a 01:30 alarm+        // fires at 06:30Z today, not tomorrow (one-shot) or next Sunday.+        val newYork = TimeZone.of("America/New_York")+        val now = kotlin.time.Instant.parse("2026-11-01T06:15:00Z").toEpochMilliseconds()+        val expected = kotlin.time.Instant.parse("2026-11-01T06:30:00Z").toEpochMilliseconds()+        assertEquals(expected, nextWearAlarmTriggerMillis(1, 30, 0, now, newYork))+        assertEquals(expected, nextWearAlarmTriggerMillis(1, 30, 1 shl 0, now, newYork))+    }+     @Test     fun nextTriggerRecurringUsesSundayBitZero() {         val mondayAfter = utcMillis(LocalDateTime(2026, 1, 5, 8, 0))
clock/src/test/java/com/vayunmathur/clock/platform/AlarmSchedulerTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/AlarmSchedulerTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/AlarmSchedulerTest.ktindex 578f55f61f..1c8b03c65f 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/AlarmSchedulerTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/AlarmSchedulerTest.kt@@ -1,5 +1,7 @@ package com.vayunmathur.clock.platform +// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+ import android.app.AlarmManager import android.content.Context import androidx.test.core.app.ApplicationProvider@@ -106,6 +108,39 @@ class AlarmSchedulerTest {         assertEquals(LocalTime(3, 30), local.time)     } +    @Test+    fun oneShotDuringSecondFallBackOccurrenceFiresAtSecondOccurrenceToday() {+        // 2026-11-01 fall-back in New York: 01:00-02:00 happens twice+        // (EDT then EST). At 06:15Z the wall clock reads 01:15 EST (the+        // second pass), so a 01:30 alarm is 15 minutes away, not tomorrow.+        val now = kotlin.time.Instant.parse("2026-11-01T06:15:00Z")+        val trigger = AlarmScheduler.calculateNextTriggerMillis(alarm(days = 0, hour = 1, minute = 30), now, newYork)+        assertEquals(kotlin.time.Instant.parse("2026-11-01T06:30:00Z").toEpochMilliseconds(), trigger)+        val local = kotlin.time.Instant.fromEpochMilliseconds(trigger).toLocalDateTime(newYork)+        assertEquals(LocalDate(2026, 11, 1), local.date)+        assertEquals(LocalTime(1, 30), local.time)+    }++    @Test+    fun recurringDuringSecondFallBackOccurrenceFiresAtSecondOccurrenceToday() {+        // Same instant as above; 2026-11-01 is a Sunday (bit 0). A+        // Sundays-only 01:30 alarm must fire at today's second 01:30,+        // not skip a whole week to the next Sunday.+        val sundayBit = 1 shl 0+        val now = kotlin.time.Instant.parse("2026-11-01T06:15:00Z")+        val trigger = AlarmScheduler.calculateNextTriggerMillis(alarm(days = sundayBit, hour = 1, minute = 30), now, newYork)+        assertEquals(kotlin.time.Instant.parse("2026-11-01T06:30:00Z").toEpochMilliseconds(), trigger)+    }++    @Test+    fun oneShotBeforeFallBackOverlapStillFiresAtFirstOccurrence() {+        // 04:15Z is 00:15 EDT, before the overlap: the next 01:30 is the+        // first (EDT) occurrence at 05:30Z, not the second one.+        val now = kotlin.time.Instant.parse("2026-11-01T04:15:00Z")+        val trigger = AlarmScheduler.calculateNextTriggerMillis(alarm(days = 0, hour = 1, minute = 30), now, newYork)+        assertEquals(kotlin.time.Instant.parse("2026-11-01T05:30:00Z").toEpochMilliseconds(), trigger)+    }+     @Test     fun scheduleArmsAlarmClockAndCancelDisarms() {         val am = ctx.getSystemService(AlarmManager::class.java)