Modern Apps git

← Modern-Apps.git

clock: stopwatch and timers run on a monotonic base

Commit
7ed9a9e983978b0385eeeb8a3edecb057169c5bb
Author
Vayun Mathur <[email protected]>
When
2026-11-21 12:33 UTC (14 days ago)
Parents
c48f36a
Elapsed time was measured against the wall clock, so a
timezone or clock change mid-stopwatch/timer corrupted the
elapsed value. DualTimeBase stores wall and elapsedRealtime
anchors together: display and remaining-time prefer the
monotonic anchor (immune to wall jumps), and a monotonic
anchor ahead of now is the reboot signal that falls back to
wall (so powered-off time still counts, expiring timers
while off). Timers carry the anchor in Room v4; expiry arms
ELAPSED_REALTIME_WAKEUP when usable. Restore/reboot paths
re-anchor instead of staying on the jumpable clock. Alarms
are wall appointments and deliberately untouched.

Verified: clock 256 tests pass incl. 10 new dual-base tests
(wall jumps, reboot fallback, legacy null anchors).

Diff

clock/schemas/com.vayunmathur.clock.data.ClockDatabase/4.json
diff --git a/clock/schemas/com.vayunmathur.clock.data.ClockDatabase/4.json b/clock/schemas/com.vayunmathur.clock.data.ClockDatabase/4.jsonnew file mode 100644index 0000000000..7af54f85db--- /dev/null+++ b/clock/schemas/com.vayunmathur.clock.data.ClockDatabase/4.json@@ -0,0 +1,136 @@+{+  "formatVersion": 1,+  "database": {+    "version": 4,+    "identityHash": "5ce888cc9a2d5d6c49fa69b02c466946",+    "entities": [+      {+        "tableName": "Timer",+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`isRunning` INTEGER NOT NULL, `name` TEXT NOT NULL, `remainingStartTime` INTEGER NOT NULL, `remainingLength` INTEGER NOT NULL, `totalLength` INTEGER NOT NULL, `remainingStartElapsedRealtime` INTEGER, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",+        "fields": [+          {+            "fieldPath": "isRunning",+            "columnName": "isRunning",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "name",+            "columnName": "name",+            "affinity": "TEXT",+            "notNull": true+          },+          {+            "fieldPath": "remainingStartTime",+            "columnName": "remainingStartTime",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "remainingLength",+            "columnName": "remainingLength",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "totalLength",+            "columnName": "totalLength",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "remainingStartElapsedRealtime",+            "columnName": "remainingStartElapsedRealtime",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "id",+            "columnName": "id",+            "affinity": "INTEGER",+            "notNull": true+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "id"+          ]+        }+      },+      {+        "tableName": "Alarm",+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`time` INTEGER NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `days` INTEGER NOT NULL, `ringtoneUri` TEXT, `vibrate` INTEGER NOT NULL, `snoozeMinutes` INTEGER NOT NULL, `gradualVolumeSeconds` INTEGER NOT NULL, `snoozedUntil` INTEGER, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",+        "fields": [+          {+            "fieldPath": "time",+            "columnName": "time",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "name",+            "columnName": "name",+            "affinity": "TEXT",+            "notNull": true+          },+          {+            "fieldPath": "enabled",+            "columnName": "enabled",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "days",+            "columnName": "days",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "ringtoneUri",+            "columnName": "ringtoneUri",+            "affinity": "TEXT"+          },+          {+            "fieldPath": "vibrate",+            "columnName": "vibrate",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "snoozeMinutes",+            "columnName": "snoozeMinutes",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "gradualVolumeSeconds",+            "columnName": "gradualVolumeSeconds",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "snoozedUntil",+            "columnName": "snoozedUntil",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "id",+            "columnName": "id",+            "affinity": "INTEGER",+            "notNull": true+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "id"+          ]+        }+      }+    ],+    "setupQueries": [+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '5ce888cc9a2d5d6c49fa69b02c466946')"+    ]+  }+}\ No newline at end of file
clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.kt b/clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.ktindex 466622dc7f..db325ba034 100644--- a/clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.kt+++ b/clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.kt@@ -17,9 +17,19 @@ import kotlinx.coroutines.flow.Flow import kotlinx.datetime.LocalTime import kotlin.time.Clock import kotlin.time.Duration+import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Instant -/** A persisted countdown timer, with its remaining length measured from [remainingStartTime] while running. */+/**+ * A persisted countdown timer, with its remaining length measured from the+ * dual anchors while running: [remainingStartTime] is the wall-clock anchor+ * and [remainingStartElapsedRealtime] the monotonic (`elapsedRealtime`)+ * anchor taken at the same moment. Remaining time is measured on the+ * monotonic base when that anchor is still usable (immune to wall-clock /+ * timezone jumps) and on the wall base after a reboot resets the monotonic+ * clock (see `platform/DualTimeBase`). Null monotonic anchor = a row written+ * before the dual base existed (or written paused): wall base only.+ */ @Entity data class Timer(     var isRunning: Boolean,@@ -27,21 +37,38 @@ data class Timer(     var remainingStartTime: Instant,     var remainingLength: Duration,     var totalLength: Duration,+    var remainingStartElapsedRealtime: Long? = null,     @PrimaryKey(autoGenerate = true)     override var id: Long = 0, ): DatabaseItem {-    fun stopped(): Timer {-        val now = Clock.System.now()+    fun stopped(+        wallNow: Instant = Clock.System.now(),+        monoNowMs: Long? = com.vayunmathur.clock.platform.DualTimeBase.elapsedRealtimeMs(),+    ): Timer {         // Pausing after the finish line (e.g. the finish broadcast is still         // in flight) must not persist a negative remaining length; the         // notification pause path already clamps, this one did not.-        val remainingTime = (remainingLength - (now - remainingStartTime)).coerceAtLeast(Duration.ZERO)-        return copy(isRunning = false, remainingLength = remainingTime)-    }-    fun started(): Timer {-        val now = Clock.System.now()-        return copy(isRunning = true, remainingStartTime = now)+        val remainingMs = com.vayunmathur.clock.platform.DualTimeBase.timerRemainingMs(+            remainingLength.inWholeMilliseconds,+            remainingStartTime.toEpochMilliseconds(),+            remainingStartElapsedRealtime,+            wallNow.toEpochMilliseconds(),+            monoNowMs,+        )+        return copy(+            isRunning = false,+            remainingLength = remainingMs.milliseconds,+            remainingStartElapsedRealtime = null,+        )     }+    fun started(+        wallNow: Instant = Clock.System.now(),+        monoNowMs: Long? = com.vayunmathur.clock.platform.DualTimeBase.elapsedRealtimeMs(),+    ): Timer = copy(+        isRunning = true,+        remainingStartTime = wallNow,+        remainingStartElapsedRealtime = monoNowMs,+    ) }  /** A persisted alarm; [days] is a weekday bitmask with bit 0 as Sunday. */@@ -105,7 +132,7 @@ interface AlarmDao {  /** Room database holding the clock app's timers and alarms. */ @ColumnTypeConverters(DefaultConverters::class)-@Database(entities = [Timer::class, Alarm::class], version = 3, exportSchema = true)+@Database(entities = [Timer::class, Alarm::class], version = 4, exportSchema = true) abstract class ClockDatabase: RoomDatabase() {     abstract fun timerDao(): TimerDao     abstract fun alarmDao(): AlarmDao@@ -122,6 +149,12 @@ abstract class ClockDatabase: RoomDatabase() {             Migration(2, 3) {                 it.execSQL("ALTER TABLE Alarm ADD COLUMN snoozedUntil INTEGER")             },+            Migration(3, 4) {+                // Dual time base: monotonic anchor for running timers.+                // Nullable: pre-existing rows have no monotonic anchor and+                // keep measuring on the wall base until next started().+                it.execSQL("ALTER TABLE Timer ADD COLUMN remainingStartElapsedRealtime INTEGER")+            },         )     } }
clock/src/main/java/com/vayunmathur/clock/intents/SetTimerIntent.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/intents/SetTimerIntent.kt b/clock/src/main/java/com/vayunmathur/clock/intents/SetTimerIntent.ktindex 269f6c074b..075d50bbee 100644--- a/clock/src/main/java/com/vayunmathur/clock/intents/SetTimerIntent.kt+++ b/clock/src/main/java/com/vayunmathur/clock/intents/SetTimerIntent.kt@@ -28,6 +28,7 @@ class SetTimerIntent : AssistantIntent<SetTimerData, Unit>(             remainingStartTime = Clock.System.now(),             remainingLength = length,             totalLength = length,+            remainingStartElapsedRealtime = com.vayunmathur.clock.platform.DualTimeBase.elapsedRealtimeMs(),         )         val repository = ClockRepository.get(this)         val id = repository.upsertTimer(timer)
clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.ktindex 3cfd2380d0..56852e9413 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt@@ -18,9 +18,10 @@ import kotlin.time.Duration  * meaning what the database says: after a reboot (AlarmManager is wiped),  * and after the timezone or the wall clock changes (AlarmManager entries are  * absolute epoch millis, so a 07:00 alarm computed in the old zone would- * otherwise fire at 07:00-old-zone in the new one). Timers need no such- * handling for time changes — their end is a duration from a stored instant,- * which a zone change does not move.+ * otherwise fire at 07:00-old-zone in the new one). Timers are durations+ * measured on the dual (prefer-monotonic) base in `restoreTimers`, so a+ * zone/wall change does not move their end either; that pass exists for+ * reboot, where AlarmManager is wiped and the monotonic base resets.  */ class BootReceiver : BroadcastReceiver() {     // Broad catch is deliberate: onReceive must not throw, and Room throws@@ -111,8 +112,22 @@ class BootReceiver : BroadcastReceiver() {         repository.getAllTimers().filter { it.isRunning }.forEach { timer ->             // One bad timer must not take the others down with it.             runCatching {-                if (timerRemaining(timer, now) > Duration.ZERO) {-                    sendTimerNotification(context, timer, true)+                val monoNowMs = DualTimeBase.elapsedRealtimeMs()+                // Dual base: monotonic when the anchor survived (a timezone /+                // wall change does not reboot the monotonic clock), wall after+                // a reboot (where the powered-off span should count).+                val remaining = timerRemaining(timer, now, monoNowMs)+                if (remaining > Duration.ZERO) {+                    // Re-anchor both bases at the restore moment with the+                    // banked remaining, so a stale pre-reboot monotonic anchor+                    // does not leave every future read on the wall base.+                    val rebased = timer.copy(+                        remainingLength = remaining,+                        remainingStartTime = now,+                        remainingStartElapsedRealtime = monoNowMs,+                    )+                    repository.upsertTimer(rebased)+                    sendTimerNotification(context, rebased, true)                     timersRearmed++                 } else {                     repository.upsertTimer(@@ -120,6 +135,7 @@ class BootReceiver : BroadcastReceiver() {                             isRunning = false,                             remainingLength = Duration.ZERO,                             remainingStartTime = now,+                            remainingStartElapsedRealtime = null,                         )                     )                     // TimerReceiver posts the "time's up" notification and re-writes
clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.kt b/clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.ktindex 005bb11cf7..0422c06823 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.kt@@ -5,6 +5,7 @@ import com.vayunmathur.clock.data.Timer import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import kotlin.time.Duration+import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Instant  /**@@ -86,14 +87,26 @@ interface TimerActions {     } } -/** Remaining duration for [timer] at instant [now], clamped to >= 0. */-fun timerRemaining(timer: Timer, now: Instant): Duration {-    val raw = if (timer.isRunning) {-        timer.remainingLength - (now - timer.remainingStartTime)-    } else {-        timer.remainingLength-    }-    return raw.coerceAtLeast(Duration.ZERO)+/** Remaining duration for [timer] at instant [now], clamped to >= 0. Wall base only. */+fun timerRemaining(timer: Timer, now: Instant): Duration =+    timerRemaining(timer, now, null)++/**+ * Remaining duration for [timer] at wall instant [now] with monotonic reading+ * [elapsedRealtimeMs], clamped to >= 0. While running, the dual base prefers+ * the timer's monotonic anchor (immune to wall/timezone jumps) and falls back+ * to the wall anchor when that anchor is unusable (e.g. after a reboot).+ */+fun timerRemaining(timer: Timer, now: Instant, elapsedRealtimeMs: Long?): Duration {+    if (!timer.isRunning) return timer.remainingLength.coerceAtLeast(Duration.ZERO)+    val remainingMs = DualTimeBase.timerRemainingMs(+        timer.remainingLength.inWholeMilliseconds,+        timer.remainingStartTime.toEpochMilliseconds(),+        timer.remainingStartElapsedRealtime,+        now.toEpochMilliseconds(),+        elapsedRealtimeMs,+    )+    return remainingMs.milliseconds }  /** Everything the stopwatch tab draws. */
clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt b/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.ktindex 07018cca26..d7a755beb6 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt@@ -143,6 +143,8 @@ class ClockViewModel(      private val _stopwatchTotal = MutableStateFlow(Duration.ZERO)     private val _stopwatchStart = MutableStateFlow(Clock.System.now())+    /** Monotonic anchor paired with [_stopwatchStart]; null = none stored / unusable. */+    private val _stopwatchStartMono = MutableStateFlow<Long?>(null)      private val _lapTimes = MutableStateFlow<List<Duration>>(emptyList())     val lapTimes: StateFlow<List<Duration>> = _lapTimes.asStateFlow()@@ -161,16 +163,38 @@ class ClockViewModel(                 ds.booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false),                 ds.longFlow(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL, 0L),                 ds.longFlow(StopwatchActionReceiver.KEY_STOPWATCH_START, 0L),+                ds.longFlow(StopwatchActionReceiver.KEY_STOPWATCH_START_MONO, 0L),                 ds.stringFlow(StopwatchActionReceiver.KEY_STOPWATCH_LAPS),-            ) { isRunning, totalMs, startMs, lapsStr ->+            ) { isRunning, totalMs, startMs, startMonoMs, lapsStr ->+                val storedMono = startMonoMs.takeIf { it > 0L }+                val wallNowMs = Clock.System.now().toEpochMilliseconds()+                val monoNowMs = DualTimeBase.elapsedRealtimeMs()+                // Reboot detection: the stored monotonic anchor is ahead of+                // the (reset) monotonic clock, so it can never measure this+                // run again. Bank the wall-base elapsed into the total and+                // re-anchor both bases at now; counting then stays monotonic+                // instead of falling back to the jumpable wall clock until+                // uptime happens to pass the pre-reboot anchor.+                val rebased = isRunning && startMs > 0L &&+                    storedMono != null && !DualTimeBase.isMonotonicUsable(storedMono, monoNowMs)+                if (rebased) {+                    _stopwatchTotal.value = DualTimeBase.stopwatchElapsedMs(+                        totalMs, startMs, storedMono, wallNowMs, monoNowMs,+                    ).milliseconds+                    _stopwatchStart.value = Instant.fromEpochMilliseconds(wallNowMs)+                    _stopwatchStartMono.value = monoNowMs+                } else {+                    _stopwatchTotal.value = totalMs.milliseconds+                    _stopwatchStart.value =+                        if (startMs > 0) Instant.fromEpochMilliseconds(startMs) else Clock.System.now()+                    _stopwatchStartMono.value = storedMono+                }                 _stopwatchRunning.value = isRunning-                _stopwatchTotal.value = totalMs.milliseconds-                _stopwatchStart.value =-                    if (startMs > 0) Instant.fromEpochMilliseconds(startMs) else Clock.System.now()                 _lapTimes.value = lapsStr                     .takeIf { it.isNotEmpty() }                     ?.split(",")?.mapNotNull { it.toLongOrNull()?.milliseconds }                     .orEmpty()+                if (rebased) persistStopwatchState()             }.collect {}         }     }@@ -192,11 +216,13 @@ class ClockViewModel(         val running = _stopwatchRunning.value         val totalMs = _stopwatchTotal.value.inWholeMilliseconds         val startMs = _stopwatchStart.value.toEpochMilliseconds()+        val startMonoMs = _stopwatchStartMono.value ?: 0L         val lapsStr = _lapTimes.value.joinToString(",") { it.inWholeMilliseconds.toString() }         viewModelScope.launch(persistDispatcher) {             ds.setBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, running)             ds.setLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL, totalMs)             ds.setLong(StopwatchActionReceiver.KEY_STOPWATCH_START, startMs)+            ds.setLong(StopwatchActionReceiver.KEY_STOPWATCH_START_MONO, startMonoMs)             ds.setString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS, lapsStr)         }     }@@ -210,9 +236,20 @@ class ClockViewModel(         _stopwatchRunning,         _stopwatchTotal,         _stopwatchStart,+        _stopwatchStartMono,         now,-    ) { running, total, start, instant ->-        if (running) (instant - start) + total else total+    ) { running, total, start, startMono, instant ->+        if (running) {+            DualTimeBase.stopwatchElapsedMs(+                total.inWholeMilliseconds,+                start.toEpochMilliseconds(),+                startMono,+                instant.toEpochMilliseconds(),+                DualTimeBase.elapsedRealtimeMs(),+            ).milliseconds+        } else {+            total+        }     }.stateIn(         viewModelScope,         SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS),@@ -222,10 +259,17 @@ class ClockViewModel(     override fun toggleStopwatch() {         val ctx = getApplication<Application>()         if (_stopwatchRunning.value) {-            _stopwatchTotal.value = _stopwatchTotal.value + (Clock.System.now() - _stopwatchStart.value)+            _stopwatchTotal.value = DualTimeBase.stopwatchElapsedMs(+                _stopwatchTotal.value.inWholeMilliseconds,+                _stopwatchStart.value.toEpochMilliseconds(),+                _stopwatchStartMono.value,+                Clock.System.now().toEpochMilliseconds(),+                DualTimeBase.elapsedRealtimeMs(),+            ).milliseconds             _stopwatchRunning.value = false         } else {             _stopwatchStart.value = Clock.System.now()+            _stopwatchStartMono.value = DualTimeBase.elapsedRealtimeMs()             _stopwatchRunning.value = true         }         persistStopwatchState()@@ -236,6 +280,7 @@ class ClockViewModel(         val ctx = getApplication<Application>()         _stopwatchRunning.value = false         _stopwatchTotal.value = Duration.ZERO+        _stopwatchStartMono.value = null         _lapTimes.value = emptyList()         persistStopwatchState()         StopwatchNotificationHelper.updateNotification(ctx)@@ -297,6 +342,7 @@ class ClockViewModel(                         Clock.System.now(),                         length.seconds,                         length.seconds,+                        remainingStartElapsedRealtime = DualTimeBase.elapsedRealtimeMs(),                     )                     val ctx = getApplication<Application>()                     viewModelScope.launch(Dispatchers.IO) {
clock/src/main/java/com/vayunmathur/clock/platform/DualTimeBase.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/DualTimeBase.kt b/clock/src/main/java/com/vayunmathur/clock/platform/DualTimeBase.ktnew file mode 100644index 0000000000..c6a5a24d0d--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/platform/DualTimeBase.kt@@ -0,0 +1,77 @@+package com.vayunmathur.clock.platform++import android.os.SystemClock++/**+ * Dual wall-clock / monotonic anchors for stopwatch and countdown timers.+ *+ * A running interval is persisted with BOTH anchors taken at the same+ * moment: the wall-clock instant (`Clock.System.now()`, epoch millis) and+ * the monotonic instant ([SystemClock.elapsedRealtime], millis since boot+ * including deep sleep). Elapsed time is then measured on the monotonic+ * base whenever that anchor is still usable, so a timezone change, an NTP+ * correction or a manual wall-clock jump cannot stretch or shrink the+ * interval. The wall anchor is the fallback for the one case the monotonic+ * base cannot survive: a reboot resets `elapsedRealtime` to (near) zero,+ * detected as `nowMono < storedMono`; measuring on the wall base then+ * includes the powered-off span, which is the sane reading for both a+ * stopwatch (it kept "running" while off) and a timer (it may have expired+ * while off, and its caller clamps/completes it).+ *+ * All functions are pure over explicit millisecond values so host tests can+ * simulate wall jumps and reboots without a device; only [elapsedRealtimeMs]+ * touches Android.+ */+object DualTimeBase {++    /** Current monotonic time: millis since boot, including deep sleep. */+    fun elapsedRealtimeMs(): Long = SystemClock.elapsedRealtime()++    /** Whether a stored monotonic anchor can still measure against [nowMonoMs]. */+    fun isMonotonicUsable(storedMonoMs: Long?, nowMonoMs: Long?): Boolean =+        storedMonoMs != null && nowMonoMs != null && nowMonoMs >= storedMonoMs++    /**+     * Elapsed millis between the dual anchors and now. Monotonic when+     * usable, else the wall delta clamped at zero (a backwards wall jump+     * with no usable monotonic anchor must not rewind a display).+     */+    fun elapsedMs(+        wallStartMs: Long,+        monoStartMs: Long?,+        wallNowMs: Long,+        monoNowMs: Long?,+    ): Long = if (isMonotonicUsable(monoStartMs, monoNowMs)) {+        monoNowMs!! - monoStartMs!!+    } else {+        (wallNowMs - wallStartMs).coerceAtLeast(0L)+    }++    /** Total stopwatch elapsed: banked [totalMs] plus the live dual-base delta. */+    fun stopwatchElapsedMs(+        totalMs: Long,+        wallStartMs: Long,+        monoStartMs: Long?,+        wallNowMs: Long,+        monoNowMs: Long?,+    ): Long = totalMs + elapsedMs(wallStartMs, monoStartMs, wallNowMs, monoNowMs)++    /** Countdown remaining: [remainingMs] minus the live dual-base delta, clamped at zero. */+    fun timerRemainingMs(+        remainingMs: Long,+        wallStartMs: Long,+        monoStartMs: Long?,+        wallNowMs: Long,+        monoNowMs: Long?,+    ): Long = (remainingMs - elapsedMs(wallStartMs, monoStartMs, wallNowMs, monoNowMs))+        .coerceAtLeast(0L)++    /**+     * Monotonic trigger instant (on the `elapsedRealtime` base, for+     * `AlarmManager.ELAPSED_REALTIME_WAKEUP`) for a countdown with+     * [remainingMs] left, or null when the monotonic base is unusable and+     * the caller must fall back to a wall-clock (`RTC_WAKEUP`) trigger.+     */+    fun timerTriggerElapsedMs(nowMonoMs: Long?, remainingMs: Long): Long? =+        nowMonoMs?.let { it + remainingMs.coerceAtLeast(0L) }+}
clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.ktindex 3632790598..8fa46c25f2 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.kt@@ -27,16 +27,21 @@ class StopwatchActionReceiver : BroadcastReceiver() {                         val isRunning = ds.getBoolean(KEY_STOPWATCH_RUNNING, false)                         val totalMs = ds.getLong(KEY_STOPWATCH_TOTAL) ?: 0L                         val startMs = ds.getLong(KEY_STOPWATCH_START) ?: 0L-                        +                        val startMonoMs = (ds.getLong(KEY_STOPWATCH_START_MONO) ?: 0L).takeIf { it > 0L }+                         if (isRunning) {-                            // Pause: add elapsed time to total-                            val now = Clock.System.now().toEpochMilliseconds()-                            val elapsed = now - startMs+                            // Pause: add elapsed time to total (dual base)+                            val elapsed = DualTimeBase.elapsedMs(+                                startMs, startMonoMs,+                                Clock.System.now().toEpochMilliseconds(),+                                DualTimeBase.elapsedRealtimeMs(),+                            )                             ds.setLong(KEY_STOPWATCH_TOTAL, totalMs + elapsed)                             ds.setBoolean(KEY_STOPWATCH_RUNNING, false)                         } else {-                            // Resume: set start time to now+                            // Resume: set both anchors to now                             ds.setLong(KEY_STOPWATCH_START, Clock.System.now().toEpochMilliseconds())+                            ds.setLong(KEY_STOPWATCH_START_MONO, DualTimeBase.elapsedRealtimeMs())                             ds.setBoolean(KEY_STOPWATCH_RUNNING, true)                         }                         // Update notification@@ -45,12 +50,16 @@ class StopwatchActionReceiver : BroadcastReceiver() {                     ACTION_LAP -> {                         val isRunning = ds.getBoolean(KEY_STOPWATCH_RUNNING, false)                         if (!isRunning) return@launch-                        +                         val totalMs = ds.getLong(KEY_STOPWATCH_TOTAL) ?: 0L                         val startMs = ds.getLong(KEY_STOPWATCH_START) ?: 0L-                        val now = Clock.System.now().toEpochMilliseconds()-                        val currentTotal = totalMs + (now - startMs)-                        +                        val startMonoMs = (ds.getLong(KEY_STOPWATCH_START_MONO) ?: 0L).takeIf { it > 0L }+                        val currentTotal = DualTimeBase.stopwatchElapsedMs(+                            totalMs, startMs, startMonoMs,+                            Clock.System.now().toEpochMilliseconds(),+                            DualTimeBase.elapsedRealtimeMs(),+                        )+                         val lapsStr = ds.getString(KEY_STOPWATCH_LAPS) ?: ""                         val newLapsStr = if (lapsStr.isEmpty()) currentTotal.toString() else "$lapsStr,$currentTotal"                         ds.setString(KEY_STOPWATCH_LAPS, newLapsStr)@@ -81,6 +90,8 @@ class StopwatchActionReceiver : BroadcastReceiver() {         const val KEY_STOPWATCH_RUNNING = "stopwatch_running"         const val KEY_STOPWATCH_TOTAL = "stopwatch_total_ms"         const val KEY_STOPWATCH_START = "stopwatch_start_ms"+        /** Monotonic (`elapsedRealtime`) anchor paired with [KEY_STOPWATCH_START]; 0 = none stored. */+        const val KEY_STOPWATCH_START_MONO = "stopwatch_start_elapsed_realtime_ms"         const val KEY_STOPWATCH_LAPS = "stopwatch_laps"         const val STOPWATCH_NOTIFICATION_ID = 9001     }
clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt b/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.ktindex df4784fb17..fa162d0c18 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt@@ -19,6 +19,8 @@ object StopwatchNotificationHelper {         val isRunning = ds.getBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false)         val totalMs = ds.getLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL) ?: 0L         val startMs = ds.getLong(StopwatchActionReceiver.KEY_STOPWATCH_START) ?: 0L+        val startMonoMs = (ds.getLong(StopwatchActionReceiver.KEY_STOPWATCH_START_MONO) ?: 0L)+            .takeIf { it > 0L }          val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager @@ -28,15 +30,19 @@ object StopwatchNotificationHelper {             return         } -        val contentText = formatElapsed(isRunning, totalMs, startMs)+        val contentText = formatElapsed(isRunning, totalMs, startMs, startMonoMs)         val builder = baseBuilder(context, contentText)         addActions(context, builder, isRunning)         nm.notify(StopwatchActionReceiver.STOPWATCH_NOTIFICATION_ID, builder.build())     } -    private fun formatElapsed(isRunning: Boolean, totalMs: Long, startMs: Long): String {+    private fun formatElapsed(isRunning: Boolean, totalMs: Long, startMs: Long, startMonoMs: Long?): String {         val elapsedMs = if (isRunning) {-            totalMs + (Clock.System.now().toEpochMilliseconds() - startMs)+            DualTimeBase.stopwatchElapsedMs(+                totalMs, startMs, startMonoMs,+                Clock.System.now().toEpochMilliseconds(),+                DualTimeBase.elapsedRealtimeMs(),+            )         } else {             totalMs         }
clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.ktindex 8ab34c3b52..23630930ea 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.kt@@ -16,7 +16,6 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlin.time.Clock-import kotlin.time.Duration  /** Handles timer notification actions (pause, resume, cancel, reset) against persisted timers. */ class TimerActionReceiver : BroadcastReceiver() {@@ -57,17 +56,8 @@ class TimerActionReceiver : BroadcastReceiver() {     ) {         val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager         val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager-        // Pause the timer: calculate remaining, update DB, cancel alarm and notification-        val now = Clock.System.now()-        val remaining = if (timer.isRunning) {-            timer.remainingLength - (now - timer.remainingStartTime)-        } else {-            timer.remainingLength-        }-        val pausedTimer = timer.copy(-            isRunning = false,-            remainingLength = remaining.coerceAtLeast(Duration.ZERO),-        )+        // Pause the timer: bank dual-base remaining, update DB, cancel alarm and notification+        val pausedTimer = if (timer.isRunning) timer.stopped() else timer.copy(remainingStartElapsedRealtime = null)         repository.upsertTimer(pausedTimer)         cancelAlarm(context, am, timer)         nm.cancel(timer.id.hashCode())@@ -78,8 +68,8 @@ class TimerActionReceiver : BroadcastReceiver() {         repository: ClockRepository,         timer: Timer,     ) {-        // Resume the timer: update DB with new start time, reschedule notification-        val resumedTimer = timer.copy(isRunning = true, remainingStartTime = Clock.System.now())+        // Resume the timer: update DB with fresh dual anchors, reschedule notification+        val resumedTimer = timer.started()         repository.upsertTimer(resumedTimer)         com.vayunmathur.clock.ui.components.sendTimerNotification(             context,@@ -112,7 +102,8 @@ class TimerActionReceiver : BroadcastReceiver() {         val resetTimer = timer.copy(             isRunning = false,             remainingLength = timer.totalLength,-            remainingStartTime = Clock.System.now()+            remainingStartTime = Clock.System.now(),+            remainingStartElapsedRealtime = null,         )         repository.upsertTimer(resetTimer)         cancelAlarm(context, am, timer)
clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt b/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.ktindex 2cb1277617..1f14e0f66c 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt@@ -62,6 +62,7 @@ class TimerReceiver : BroadcastReceiver() {                         isRunning = false,                         remainingLength = Duration.ZERO,                         remainingStartTime = Clock.System.now(),+                        remainingStartElapsedRealtime = null,                     )                     repository.upsertTimer(completed)                 } catch (e: Exception) {
clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt b/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.ktindex 6506298e43..db7c574df1 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt@@ -30,7 +30,7 @@ fun TimerPage(clockViewModel: ClockViewModel) {     val actions = remember(clockViewModel, context) {         object : TimerActions {             override fun start(duration: Duration, name: String) {-                val timer = Timer(true, name, Clock.System.now(), duration, duration)+                val timer = Timer(true, name, Clock.System.now(), duration, duration, remainingStartElapsedRealtime = com.vayunmathur.clock.platform.DualTimeBase.elapsedRealtimeMs())                 clockViewModel.upsert(timer) { sendTimerNotification(context, timer.copy(id = it), true) }             }             override fun delete(timer: Timer) { sendTimerNotification(context, timer, false); clockViewModel.delete(timer) }@@ -40,13 +40,13 @@ fun TimerPage(clockViewModel: ClockViewModel) {                 if (timer.isRunning) sendTimerNotification(context, updated, true)             }             override fun reset(timer: Timer) {-                clockViewModel.upsert(timer.copy(isRunning = false, remainingLength = timer.totalLength, remainingStartTime = Clock.System.now()))+                clockViewModel.upsert(timer.copy(isRunning = false, remainingLength = timer.totalLength, remainingStartTime = Clock.System.now(), remainingStartElapsedRealtime = null))                 sendTimerNotification(context, timer, false)             }             override fun toggle(timer: Timer) {                 when {                     !timer.isRunning && timer.remainingLength <= Duration.ZERO -> {-                        val restarted = timer.copy(isRunning = true, remainingLength = timer.totalLength, remainingStartTime = Clock.System.now())+                        val restarted = timer.started().copy(remainingLength = timer.totalLength)                         clockViewModel.upsert(restarted); sendTimerNotification(context, restarted, true)                     }                     timer.isRunning -> { clockViewModel.upsert(timer.stopped()); sendTimerNotification(context, timer, false) }
clock/src/main/java/com/vayunmathur/clock/ui/components/TimerCard.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/components/TimerCard.kt b/clock/src/main/java/com/vayunmathur/clock/ui/components/TimerCard.ktindex 6459008199..1aa5c1e9c5 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/components/TimerCard.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/components/TimerCard.kt@@ -47,7 +47,7 @@ import kotlin.time.Duration.Companion.seconds  @Composable fun TimerCard(timer: Timer, now: kotlin.time.Instant, actions: TimerActions) {-    val realRemainingTime = remember(timer, now) { timerRemaining(timer, now) }+    val realRemainingTime = remember(timer, now) { timerRemaining(timer, now, com.vayunmathur.clock.platform.DualTimeBase.elapsedRealtimeMs()) }     val isCompleted = realRemainingTime == Duration.ZERO && !timer.isRunning     val stateLabel = when {         isCompleted -> "Completed"
clock/src/main/java/com/vayunmathur/clock/ui/components/TimerNotification.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/components/TimerNotification.kt b/clock/src/main/java/com/vayunmathur/clock/ui/components/TimerNotification.ktindex 533b3b3ea4..b350a6749d 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/components/TimerNotification.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/components/TimerNotification.kt@@ -35,8 +35,25 @@ fun sendTimerNotification(context: Context, timer: Timer, isStarting: Boolean) {         return     } -    val remaining = if (timer.isRunning) timer.remainingLength - (Clock.System.now() - timer.remainingStartTime) else timer.remainingLength+    val monoNowMs = com.vayunmathur.clock.platform.DualTimeBase.elapsedRealtimeMs()+    val remaining = com.vayunmathur.clock.platform.timerRemaining(timer, Clock.System.now(), monoNowMs)+    // Wall-clock end for the notification chronometer (it renders a wall time).     val endTimestamp = System.currentTimeMillis() + remaining.inWholeMilliseconds+    // Countdown expiry is a duration, not a wall appointment: arm it on the+    // monotonic base when that anchor is usable so a wall jump cannot fire+    // it early/late. Unusable (legacy row / reboot) -> wall RTC trigger.+    val monoTriggerMs = if (timer.isRunning) {+        com.vayunmathur.clock.platform.DualTimeBase.timerTriggerElapsedMs(+            monoNowMs.takeIf {+                com.vayunmathur.clock.platform.DualTimeBase.isMonotonicUsable(+                    timer.remainingStartElapsedRealtime, it,+                )+            },+            remaining.inWholeMilliseconds,+        )+    } else {+        null+    }      val pauseIntent = PendingIntent.getBroadcast(context, notificationId + 1, Intent(context, com.vayunmathur.clock.platform.TimerActionReceiver::class.java).apply { action = com.vayunmathur.clock.platform.TimerActionReceiver.ACTION_PAUSE; putExtra("timer_id", timer.id) }, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)     val resumeIntent = PendingIntent.getBroadcast(context, notificationId + 2, Intent(context, com.vayunmathur.clock.platform.TimerActionReceiver::class.java).apply { action = com.vayunmathur.clock.platform.TimerActionReceiver.ACTION_RESUME; putExtra("timer_id", timer.id) }, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)@@ -63,13 +80,21 @@ fun sendTimerNotification(context: Context, timer: Timer, isStarting: Boolean) {      nm.notify(notificationId, builder.build())     try {-        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, endTimestamp, pendingAlarm)+        if (monoTriggerMs != null) {+            am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, monoTriggerMs, pendingAlarm)+        } else {+            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, endTimestamp, pendingAlarm)+        }     } catch (e: SecurityException) {         // Exact-alarm special access revoked after the first-launch gate:         // callers include Compose click handlers and the assistant-intent         // path, where this throw crashed the app. An inexact while-idle         // alarm still finishes the timer, just without exact timing.         Log.error("TimerNotification", "Timer ${timer.id}: exact alarm denied; falling back to inexact", e)-        am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, endTimestamp, pendingAlarm)+        if (monoTriggerMs != null) {+            am.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, monoTriggerMs, pendingAlarm)+        } else {+            am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, endTimestamp, pendingAlarm)+        }     } }
clock/src/main/java/com/vayunmathur/clock/ui/dialogs/NewTimerDialog.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/dialogs/NewTimerDialog.kt b/clock/src/main/java/com/vayunmathur/clock/ui/dialogs/NewTimerDialog.ktindex 812e8cdc65..6f7a554325 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/dialogs/NewTimerDialog.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/dialogs/NewTimerDialog.kt@@ -118,7 +118,7 @@ fun NewTimerDialog(                                          if (h > 0 || m > 0 || s > 0) {                         val duration = h.hours + m.minutes + s.seconds-                        val timer = Timer(true, name, Clock.System.now(), duration, duration)+                        val timer = Timer(true, name, Clock.System.now(), duration, duration, remainingStartElapsedRealtime = com.vayunmathur.clock.platform.DualTimeBase.elapsedRealtimeMs())                         clockViewModel.upsert(timer) {                             sendTimerNotification(context, timer.copy(id = it), true)                         }
clock/src/test/java/com/vayunmathur/clock/data/ClockDataTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/data/ClockDataTest.kt b/clock/src/test/java/com/vayunmathur/clock/data/ClockDataTest.ktindex 9112ef4581..fe1197691b 100644--- a/clock/src/test/java/com/vayunmathur/clock/data/ClockDataTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/data/ClockDataTest.kt@@ -102,8 +102,28 @@ class ClockDataTest {      @Test     fun migrationsDeclared() {-        assertEquals(2, ClockDatabase.migrations.size)-        assertEquals(listOf(1 to 2, 2 to 3), ClockDatabase.migrations.map { it.startVersion to it.endVersion })+        assertEquals(3, ClockDatabase.migrations.size)+        assertEquals(+            listOf(1 to 2, 2 to 3, 3 to 4),+            ClockDatabase.migrations.map { it.startVersion to it.endVersion },+        )+    }++    @Test+    fun timerStartedStoresMonotonicAnchorAndStoppedClearsIt() {+        val paused = timer()+        assertEquals(null, paused.remainingStartElapsedRealtime)+        val running = paused.started(monoNowMs = 123_000L)+        assertEquals(123_000L, running.remainingStartElapsedRealtime)+        // Wall jumps +1h while only 10s of monotonic time passes: stopping+        // must bank the monotonic delta, not the wall delta.+        val stopped = running.stopped(+            wallNow = running.remainingStartTime + 1.minutes * 60,+            monoNowMs = 133_000L,+        )+        assertFalse(stopped.isRunning)+        assertEquals(null, stopped.remainingStartElapsedRealtime)+        assertTrue(stopped.remainingLength > 4.minutes)     }  }
clock/src/test/java/com/vayunmathur/clock/data/MigrationsAndDataTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/data/MigrationsAndDataTest.kt b/clock/src/test/java/com/vayunmathur/clock/data/MigrationsAndDataTest.ktindex 563ee873a7..329d06775c 100644--- a/clock/src/test/java/com/vayunmathur/clock/data/MigrationsAndDataTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/data/MigrationsAndDataTest.kt@@ -50,10 +50,11 @@ class MigrationsAndDataTest {     }      @Test fun migrationsApplyTheirSqlInOrder() { kotlinx.coroutines.runBlocking {-        assertEquals(2, ClockDatabase.migrations.size)+        assertEquals(3, ClockDatabase.migrations.size)         val recording = RecordingConnection()         ClockDatabase.migrations[0].migrate(recording.connection)         ClockDatabase.migrations[1].migrate(recording.connection)+        ClockDatabase.migrations[2].migrate(recording.connection)         assertEquals(             listOf(                 "ALTER TABLE Alarm ADD COLUMN ringtoneUri TEXT",@@ -61,6 +62,7 @@ class MigrationsAndDataTest {                 "ALTER TABLE Alarm ADD COLUMN snoozeMinutes INTEGER NOT NULL DEFAULT 5",                 "ALTER TABLE Alarm ADD COLUMN gradualVolumeSeconds INTEGER NOT NULL DEFAULT 0",                 "ALTER TABLE Alarm ADD COLUMN snoozedUntil INTEGER",+                "ALTER TABLE Timer ADD COLUMN remainingStartElapsedRealtime INTEGER",             ),             recording.sql,         )
clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.ktindex a878abc370..8ba2aec990 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.kt@@ -112,6 +112,13 @@ class ReceiversDeepTest {         StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_TOGGLE))         await("running") { ds.getBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false) }         Thread.sleep(150)+        // Robolectric's monotonic clock is tied to its paused scheduler and+        // does not advance over Thread.sleep, so backdate the stored+        // monotonic anchor to simulate 200ms of real elapsed time.+        ds.setLong(+            StopwatchActionReceiver.KEY_STOPWATCH_START_MONO,+            DualTimeBase.elapsedRealtimeMs() - 200L,+        )         // Toggling again pauses and banks the elapsed total.         StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_TOGGLE))         await("paused with banked total") {
clock/src/test/java/com/vayunmathur/clock/pure/DualTimeBaseTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/pure/DualTimeBaseTest.kt b/clock/src/test/java/com/vayunmathur/clock/pure/DualTimeBaseTest.ktnew file mode 100644index 0000000000..b9dffd7043--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/pure/DualTimeBaseTest.kt@@ -0,0 +1,131 @@+package com.vayunmathur.clock.pure++import com.vayunmathur.clock.platform.DualTimeBase+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Dual wall/monotonic base: wall jumps must not move a running stopwatch or+ * countdown, and a reboot (monotonic reset) must fall back to the wall base.+ * Pure millisecond arithmetic mirroring how ClockViewModel, the stopwatch /+ * timer receivers and BootReceiver feed DualTimeBase.+ */+class DualTimeBaseTest {+    // A run started at wall 1_700_000_000_000 with 3_600_000 ms uptime.+    private val wallStart = 1_700_000_000_000L+    private val monoStart = 3_600_000L+    private val hourMs = 3_600_000L++    @Test+    fun wallJumpForwardDoesNotChangeStopwatchElapsed() {+        // One real hour passes; wall clock also jumps +6h (timezone change).+        val elapsed = DualTimeBase.stopwatchElapsedMs(+            totalMs = 90_000L,+            wallStartMs = wallStart,+            monoStartMs = monoStart,+            wallNowMs = wallStart + hourMs + 6 * hourMs,+            monoNowMs = monoStart + hourMs,+        )+        assertEquals(90_000L + hourMs, elapsed)+    }++    @Test+    fun wallJumpBackwardDoesNotChangeStopwatchElapsed() {+        val elapsed = DualTimeBase.elapsedMs(+            wallStart, monoStart,+            wallNowMs = wallStart - 2 * hourMs,+            monoNowMs = monoStart + 60_000L,+        )+        assertEquals(60_000L, elapsed)+    }++    @Test+    fun wallJumpDoesNotChangeTimerRemaining() {+        // 5-minute timer, 1 minute really elapsed, wall jumps +1h.+        val remaining = DualTimeBase.timerRemainingMs(+            remainingMs = 300_000L,+            wallStartMs = wallStart,+            monoStartMs = monoStart,+            wallNowMs = wallStart + hourMs,+            monoNowMs = monoStart + 60_000L,+        )+        assertEquals(240_000L, remaining)+    }++    @Test+    fun rebootFallsBackToWallForStopwatch() {+        // After reboot mono resets below the stored anchor; wall kept running.+        assertFalse(DualTimeBase.isMonotonicUsable(monoStart, nowMonoMs = 120_000L))+        val elapsed = DualTimeBase.elapsedMs(+            wallStart, monoStart,+            wallNowMs = wallStart + 2 * hourMs,+            monoNowMs = 120_000L,+        )+        assertEquals(2 * hourMs, elapsed)+    }++    @Test+    fun rebootTimerExpiredWhileOffClampsToZero() {+        val remaining = DualTimeBase.timerRemainingMs(+            remainingMs = 300_000L,+            wallStartMs = wallStart,+            monoStartMs = monoStart,+            wallNowMs = wallStart + hourMs,+            monoNowMs = 5_000L, // reset by reboot+        )+        assertEquals(0L, remaining)+    }++    @Test+    fun rebootTimerStillRunningUsesWallSpan() {+        val remaining = DualTimeBase.timerRemainingMs(+            remainingMs = 3 * hourMs,+            wallStartMs = wallStart,+            monoStartMs = monoStart,+            wallNowMs = wallStart + hourMs,+            monoNowMs = 5_000L,+        )+        assertEquals(2 * hourMs, remaining)+    }++    @Test+    fun legacyRowWithoutMonoAnchorUsesWall() {+        val elapsed = DualTimeBase.elapsedMs(+            wallStart, monoStartMs = null,+            wallNowMs = wallStart + 30_000L,+            monoNowMs = monoStart + 999_999L,+        )+        assertEquals(30_000L, elapsed)+    }++    @Test+    fun backwardsWallWithNoMonoAnchorClampsToZero() {+        val elapsed = DualTimeBase.elapsedMs(+            wallStart, monoStartMs = null,+            wallNowMs = wallStart - hourMs,+            monoNowMs = null,+        )+        assertEquals(0L, elapsed)+    }++    @Test+    fun monotonicTriggerIsNowMonoPlusRemaining() {+        assertTrue(DualTimeBase.isMonotonicUsable(monoStart, monoStart + 1L))+        assertEquals(+            monoStart + 240_000L,+            DualTimeBase.timerTriggerElapsedMs(monoStart, 240_000L),+        )+        assertNull(DualTimeBase.timerTriggerElapsedMs(null, 240_000L))+    }++    @Test+    fun monoAnchorEqualToNowIsUsableWithZeroElapsed() {+        assertEquals(+            0L,+            DualTimeBase.elapsedMs(wallStart, monoStart, wallStart + hourMs, monoStart),+        )+    }+}