Modern Apps git

← Modern-Apps.git

games-hub: fix streaks breaking across DST transitions

Commit
43a5aaac13ea0b71be8e01aab5099885dd89b568
Author
Vayun Mathur <[email protected]>
When
2026-11-08 02:40 UTC (28 days ago)
Parents
05b6fca
StreakCalculator compared local-midnight instants with a fixed 86.4M ms day, but consecutive local midnights are 23h/25h apart across a daylight saving change. Playing on both sides of a spring-forward Sunday reset the current streak to 0 and split the longest streak (e.g. America/Denver 2026-03-08/09: Mar 8 -> Mar 9 midnights are 23h apart so the run broke, and todayStart minus 24h landed at 01:00, matching neither today nor yesterday).

Compare calendar days via LocalDate.toEpochDays() diffs of exactly one instead of millisecond arithmetic, in both longestStreak and currentStreak. Day boundaries are still local days; only the equality check changed, so non-DST behavior is identical.

Adds a regression test running the calculator under America/Denver across both 2026 transitions (Mar 8/9 and Nov 1/2): two-day play yields current 2 and longest 2. The old code returned current 0 and longest 1 on the spring case.

Verified with :games:hub:testDevUnitTest (17 tests, 0 failures). User-visible effect: streaks no longer reset for players twice a year.

Diff

games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.ktindex 80def03971..108bf7e522 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.kt@@ -1,9 +1,8 @@ package com.vayunmathur.games.hub.util -import kotlin.time.Duration.Companion.days import kotlin.time.Instant+import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone-import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.toLocalDateTime import com.vayunmathur.games.hub.data.entities.PlaySessionEntity @@ -28,10 +27,18 @@ object StreakCalculator {         )     } -    private fun qualifyingDays(sessions: List<PlaySessionEntity>, minSessionMs: Long): List<Long> {-        val qualifyingDays = mutableSetOf<Long>()+    // Calendar days (not 24h instants): across a DST transition consecutive local+    // midnights are 23h/25h apart, so fixed-millisecond day arithmetic breaks+    // streaks twice a year. Comparing LocalDate epoch days is DST-proof.+    private fun qualifyingDays(sessions: List<PlaySessionEntity>, minSessionMs: Long): List<LocalDate> {+        val tz = TimeZone.currentSystemDefault()+        val qualifyingDays = mutableSetOf<LocalDate>()         for (s in sessions) {-            if (isQualifyingSession(s, minSessionMs)) qualifyingDays.add(dayStart(s.startTime))+            if (isQualifyingSession(s, minSessionMs)) {+                qualifyingDays.add(+                    Instant.fromEpochMilliseconds(s.startTime).toLocalDateTime(tz).date+                )+            }         }         return qualifyingDays.sorted()     }@@ -42,11 +49,11 @@ object StreakCalculator {         else -> false     } -    private fun longestStreak(sortedDays: List<Long>): Int {+    private fun longestStreak(sortedDays: List<LocalDate>): Int {         var maxStreak = 1         var curRun = 1         for (i in 1 until sortedDays.size) {-            if (sortedDays[i] - sortedDays[i - 1] == DAY_MILLIS) {+            if (sortedDays[i].toEpochDays() - sortedDays[i - 1].toEpochDays() == 1L) {                 curRun++                 if (curRun > maxStreak) maxStreak = curRun             } else {@@ -56,32 +63,23 @@ object StreakCalculator {         return maxStreak     } -    private fun currentStreak(sortedDays: List<Long>, now: Long): Int {-        val todayStart = dayStart(now)-        val yesterdayStart = todayStart - DAY_MILLIS+    private fun currentStreak(sortedDays: List<LocalDate>, now: Long): Int {+        val tz = TimeZone.currentSystemDefault()+        val today = Instant.fromEpochMilliseconds(now).toLocalDateTime(tz).date         val lastDay = sortedDays.last()-        if (lastDay != todayStart && lastDay != yesterdayStart) return 0+        val lastEpochDay = lastDay.toEpochDays()+        val todayEpochDay = today.toEpochDays()+        if (lastEpochDay != todayEpochDay && lastEpochDay != todayEpochDay - 1) return 0         var streak = 1         var idx = sortedDays.lastIndex - 1-        var expectedDay = lastDay - DAY_MILLIS-        while (idx >= 0 && sortedDays[idx] >= expectedDay) {-            if (sortedDays[idx] == expectedDay) {+        var expectedEpochDay = lastEpochDay - 1+        while (idx >= 0 && sortedDays[idx].toEpochDays() >= expectedEpochDay) {+            if (sortedDays[idx].toEpochDays() == expectedEpochDay) {                 streak++-                expectedDay -= DAY_MILLIS+                expectedEpochDay--             }             idx--         }         return streak     }--    private val DAY_MILLIS = 1.days.inWholeMilliseconds--    private fun dayStart(millis: Long): Long {-        val tz = TimeZone.currentSystemDefault()-        return Instant.fromEpochMilliseconds(millis)-            .toLocalDateTime(tz)-            .date-            .atStartOfDayIn(tz)-            .toEpochMilliseconds()-    } }
games/hub/src/test/java/com/vayunmathur/games/hub/util/HubCalculatorsTest.kt
diff --git a/games/hub/src/test/java/com/vayunmathur/games/hub/util/HubCalculatorsTest.kt b/games/hub/src/test/java/com/vayunmathur/games/hub/util/HubCalculatorsTest.ktindex fa72556708..d4c969d145 100644--- a/games/hub/src/test/java/com/vayunmathur/games/hub/util/HubCalculatorsTest.kt+++ b/games/hub/src/test/java/com/vayunmathur/games/hub/util/HubCalculatorsTest.kt@@ -82,6 +82,38 @@ class HubCalculatorsTest {         assertEquals(1, yesterday.currentStreak)     } +    @Test+    fun streakSurvivesDaylightSavingTransitions() {+        val denver = java.util.TimeZone.getTimeZone("America/Denver")+        val previous = java.util.TimeZone.getDefault()+        java.util.TimeZone.setDefault(denver)+        try {+            val zone = java.time.ZoneId.of("America/Denver")+            fun noon(m: Int, d: Int) =+                java.time.ZonedDateTime.of(2026, m, d, 12, 0, 0, 0, zone).toInstant().toEpochMilli()+            fun daySession(start: Long) = PlaySessionEntity(+                gameId = "g", sessionId = "s$start",+                startTime = start, endTime = start + 120_000, durationMs = 120_000,+            )+            // Spring forward: 2026-03-08 is a 23-hour day in Denver.+            val spring = StreakCalculator.calculate(+                listOf(daySession(noon(3, 8)), daySession(noon(3, 9))),+                now = noon(3, 9),+            )+            assertEquals(2, spring.currentStreak)+            assertEquals(2, spring.longestStreak)+            // Fall back: 2026-11-01 is a 25-hour day in Denver.+            val fall = StreakCalculator.calculate(+                listOf(daySession(noon(11, 1)), daySession(noon(11, 2))),+                now = noon(11, 2),+            )+            assertEquals(2, fall.currentStreak)+            assertEquals(2, fall.longestStreak)+        } finally {+            java.util.TimeZone.setDefault(previous)+        }+    }+     @Test     fun formatPlaytimeAndDuration() {         assertEquals("0m", formatPlaytime(0))