Modern Apps git

← Modern-Apps.git

sync: hybrid monotonic stamps for last-writer-wins ordering

Commit
3199e95dc4153c7c9cad8b395fee6c35c4df4ba9
Author
Vayun Mathur <[email protected]>
When
2026-11-21 11:15 UTC (15 days ago)
Parents
e3bde5f
All three synced apps ordered changes by raw wall-clock
updatedAt, so a device with a fast clock won every conflict
forever and a backwards clock jump could resurrect deleted
rows. New library SyncStamp: next = max(wall, last+1),
observe(remote) advances the local high-water mark.

Todo and notes mint local stamps from MAX(updatedAt) in the
table itself, so a pulled future stamp automatically advances
the next local write - no schema change, nothing to migrate.
Everysync persists its high-water mark in DataStore and
observes every folded remote stamp before minting merge
timestamps and tombstones.

Tests: backwards-clock monotonicity and future-remote advance
in all three apps plus the library primitive (13 new tests).
Verified: todo, notes, everysync and library suites pass.

Diff

everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.ktindex a5bc9f4897..f783e58851 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.kt@@ -29,6 +29,7 @@ import com.vayunmathur.everysync.sync.RelayMerge import com.vayunmathur.everysync.sync.RelayPlan import com.vayunmathur.everysync.sync.RelaySnapshot import com.vayunmathur.everysync.sync.RelayStore+import com.vayunmathur.everysync.sync.SyncStamps import com.vayunmathur.everysync.sync.TodoListRelayStore import com.vayunmathur.everysync.sync.TodoRelayStore import com.vayunmathur.everysync.sync.VaultKeys@@ -301,7 +302,11 @@ class E2eeProvider : SyncProvider {         writeRemoteStamps: (suspend (item: T, stamp: Long) -> Unit)? = null,     ) {         val channel = RelaySync.recordChannel(channelType, vault.vaultId)-        val now = System.currentTimeMillis()+        // Hybrid stamp for this cycle: advance past every remote stamp the+        // fold is about to see, then mint a `now` that is monotonic even if+        // the wall clock jumped backwards (see SyncStamps). The merge uses+        // `now` for snapshot bookkeeping and hard-delete tombstone stamps.+        SyncStamps.seedFromStore(context)         // Full log pull (from 0): the merge needs full remote state, not a         // delta. The pull cursor still advances so live-push paths can skip         // re-reads; the merge itself never depends on it.@@ -311,6 +316,9 @@ class E2eeProvider : SyncProvider {         // would delete every baseline-present row (see RelayMerge).         val pulled = pullRemoteOrAbort(channel, vault.key, channelType)         val remote = pulled.items.mapNotNull { store.parseRemote(it) }+        remote.forEach { SyncStamps.observe(kind.updatedAt(it)) }+        val now = SyncStamps.next()+        SyncStamps.persist(context)         val local = readLocalOrAbort(store, channelType)         val baseline = store.loadBaseline()         val plan = RelayMerge.merge(kind, local, remote, baseline, now)
everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.ktindex e2699068b1..957894b65d 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt@@ -85,10 +85,10 @@ object RelayBlobStore {         runCatching { fileFor(context, vaultId, name).delete() }     } -    fun encode(name: String, bytes: ByteArray, updatedAt: Long = System.currentTimeMillis()): String =+    fun encode(name: String, bytes: ByteArray, updatedAt: Long = SyncStamps.next()): String =         json.encodeToString(BlobEnvelope(name, sha256(bytes), Base64.encode(bytes), updatedAt)) -    fun encodeDelete(name: String, updatedAt: Long = System.currentTimeMillis()): String =+    fun encodeDelete(name: String, updatedAt: Long = SyncStamps.next()): String =         json.encodeToString(BlobEnvelope(name, "", "", updatedAt, true))      fun decode(raw: String): BlobEnvelope? = runCatching {@@ -136,6 +136,7 @@ object RelayBlobStore {         items.mapNotNull { decode(it) }             .filter { isSafeBlobName(it.name) }             .forEach { env ->+                SyncStamps.observe(env.updatedAt)                 val prev = latest[env.name]                 if (prev == null || env.updatedAt >= prev.updatedAt) latest[env.name] = env             }@@ -171,7 +172,7 @@ object RelayBlobStore {         vaultId: String,         vaultKey: ByteArray,         blobs: List<Pair<String, ByteArray>>,-        updatedAt: Long = System.currentTimeMillis(),+        updatedAt: Long = SyncStamps.next(),     ): Int? {         if (blobs.isEmpty()) return null         val items = blobs.map { (name, bytes) -> encode(name, bytes, updatedAt) }@@ -182,7 +183,7 @@ object RelayBlobStore {         vaultId: String,         vaultKey: ByteArray,         names: List<String>,-        updatedAt: Long = System.currentTimeMillis(),+        updatedAt: Long = SyncStamps.next(),     ): Int? {         if (names.isEmpty()) return null         val items = names.map { encodeDelete(it, updatedAt) }
everysync/src/main/java/com/vayunmathur/everysync/sync/SyncStamps.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/SyncStamps.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/SyncStamps.ktnew file mode 100644index 0000000000..da29e218ca--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/SyncStamps.kt@@ -0,0 +1,60 @@+package com.vayunmathur.everysync.sync++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.HybridStampGenerator++/**+ * EverySync's hybrid stamp source for the stamps it mints itself.+ *+ * The `updatedAt` values that order [RelayMerge] mostly originate in the+ * sink apps (todo/notes mint hybrid stamps in their own stores), but+ * EverySync also mints stamps: the merge `now` (relay tombstones for+ * hard-delete stores are stamped `max(remote, now)`) and blob envelopes+ * ([RelayBlobStore], LWW by `updatedAt`). Minting those from the raw wall+ * clock would reintroduce clock-skew wins/regressions at this layer, so+ * they go through one [HybridStampGenerator]:+ *+ *  - [observe] every remote stamp a merge fold sees, so the next local+ *    stamp is past it;+ *  - [next] is `max(wall, last + 1)`, so a backwards clock jump never+ *    regresses a stamp this process mints.+ *+ * The generator's high-water mark is persisted in the shared DataStore+ * under [KEY] (seeded in [seedFromStore], written back by [persist]) so+ * monotonicity survives process death. In-process callers that cannot+ * suspend (blob envelope encoding) use [next]/[observe] directly; the+ * persisted seed is loaded once per process by the merge driver, which+ * also persists after each cycle.+ */+object SyncStamps {+    /** DataStore key for the persisted hybrid high-water mark. */+    const val KEY = "everysync_hybrid_stamp"++    private val generator = HybridStampGenerator()+    @Volatile private var seeded = false++    /** Mints the next hybrid stamp (see [HybridStampGenerator.next]). */+    fun next(): Long = generator.next()++    /** Advances the local counter past a remote stamp (hybrid receive rule). */+    fun observe(remote: Long) {+        generator.observe(remote)+    }++    /** The highest stamp minted or observed so far in this process. */+    val last: Long get() = generator.last++    /** Seeds the in-process generator from the persisted high-water mark. */+    suspend fun seedFromStore(context: Context) {+        if (seeded) return+        seeded = true+        val persisted = DataStoreUtils.getInstance(context).getLongAwait(KEY) ?: 0L+        generator.observe(persisted)+    }++    /** Persists the current high-water mark if it advanced past the stored one. */+    suspend fun persist(context: Context) {+        DataStoreUtils.getInstance(context).setLongIfGreater(KEY, generator.last)+    }+}
everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.ktindex 430556fdd4..d88747f90c 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/adapters/PasswordKind.kt@@ -2,6 +2,7 @@ package com.vayunmathur.everysync.sync.adapters  import com.vayunmathur.everysync.data.RemotePassword import com.vayunmathur.everysync.sync.EntityKind+import com.vayunmathur.everysync.sync.SyncStamps import com.vayunmathur.everysync.sync.relayContentHash import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json@@ -72,7 +73,7 @@ object PasswordKind : EntityKind<RemotePassword>() {         note: String = "",         totpSecret: String? = null,         websites: List<String> = emptyList(),-        updatedAt: Long = System.currentTimeMillis(),+        updatedAt: Long = SyncStamps.next(),     ) = RemotePassword(         uid = uid,         isPasskey = false,@@ -100,7 +101,7 @@ object PasswordKind : EntityKind<RemotePassword>() {         lastUsedTime: Long = System.currentTimeMillis(),         signCount: Int = 0,         linkedPasswordSyncId: String? = null,-        updatedAt: Long = System.currentTimeMillis(),+        updatedAt: Long = SyncStamps.next(),     ) = RemotePassword(         uid = uid,         isPasskey = true,
everysync/src/test/java/com/vayunmathur/everysync/sync/SyncStampsTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/sync/SyncStampsTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/sync/SyncStampsTest.ktnew file mode 100644index 0000000000..5d23265aff--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/sync/SyncStampsTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.everysync.sync++import com.vayunmathur.everysync.data.RemotePassword+import com.vayunmathur.everysync.sync.adapters.PasswordKind+import com.vayunmathur.library.util.HybridStampGenerator+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Hybrid stamps at the EverySync layer: the merge `now` minted by the+ * driver (and blob/password factory stamps via [SyncStamps]) must stay+ * monotonic when the wall clock jumps backwards, and observing a future+ * remote stamp must advance subsequent local stamps past it.+ */+class SyncStampsTest {++    @Test+    fun stampsIncreaseWhenWallClockJumpsBackwards() {+        var wall = 1_000_000L+        val gen = HybridStampGenerator(initialLast = 0L, wallNow = { wall })+        val first = gen.next()+        wall = 1L // wall clock jumps far backwards+        val second = gen.next()+        val third = gen.next()+        assertTrue(second > first, "stamp regressed after backwards clock: $first -> $second")+        assertTrue(third > second, "stamps must keep increasing: $second -> $third")+    }++    @Test+    fun futureRemoteStampAdvancesSubsequentLocalStamps() {+        var wall = 1_000L+        val gen = HybridStampGenerator(initialLast = 0L, wallNow = { wall })+        gen.next()+        gen.observe(remote = 999_999L)+        assertTrue(gen.next() > 999_999L, "local stamp did not advance past remote")+    }++    @Test+    fun mergeTombstoneStampIsPastFutureRemoteAfterObserve() {+        // Passwords hard-delete: a baseline-present record absent locally+        // propagates a tombstone stamped max(remote, now). With `now` from+        // a generator that observed the remote stamp first, the tombstone+        // sorts strictly after the future remote record it replaces.+        val future = 999_999L+        var wall = 1_000L+        val gen = HybridStampGenerator(initialLast = 0L, wallNow = { wall })+        val remote = RemotePassword(uid = "p1", name = "Bank", updatedAt = future)+        gen.observe(remote.updatedAt)+        val now = gen.next()+        val baseline = mapOf(+            remote.uid to RelaySnapshot(+                remote.uid, PasswordKind.kind, PasswordKind.contentHash(remote),+                remote.updatedAt, remote.updatedAt, now,+            ),+        )+        val plan = RelayMerge.merge(PasswordKind, emptyList(), listOf(remote), baseline, now)+        assertEquals(1, plan.remoteOut.size)+        assertTrue(plan.remoteOut[0].deleted)+        assertTrue(+            plan.remoteOut[0].updatedAt > future,+            "tombstone stamp ${plan.remoteOut[0].updatedAt} not past remote $future",+        )+    }++    @Test+    fun syncStampsObjectIsMonotonicAcrossCalls() {+        val a = SyncStamps.next()+        SyncStamps.observe(a + 10_000L)+        val b = SyncStamps.next()+        assertTrue(b > a + 10_000L, "SyncStamps did not advance past observed stamp: $a -> $b")+    }+}
library/src/main/java/com/vayunmathur/library/util/SyncStamp.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/SyncStamp.kt b/library/src/main/java/com/vayunmathur/library/util/SyncStamp.ktnew file mode 100644index 0000000000..380b066995--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/util/SyncStamp.kt@@ -0,0 +1,77 @@+package com.vayunmathur.library.util++/**+ * Hybrid logical stamps for last-writer-wins sync ordering.+ *+ * Plain wall-clock stamps (`System.currentTimeMillis()`) break under clock+ * skew: a device whose clock runs fast mints stamps ahead of every other+ * device and then wins every conflict forever, and a device whose clock+ * jumps backwards can mint a stamp older than its own previous edit, so+ * that edit silently loses.+ *+ * A hybrid stamp stays in the same epoch-ms [Long] space as the wall stamps+ * it replaces (no schema or wire change: `updatedAt` columns and relay+ * envelopes keep carrying a Long), but is monotonic per store:+ *+ *  - local mint: `next = max(wallNow, lastStamp + 1)` โ€” even if the wall+ *    clock jumps backwards, stamps from one store never go backwards;+ *  - on receiving a remote stamp: `lastStamp = max(lastStamp, remote)` โ€”+ *    the next local stamp is then strictly past anything this store has+ *    seen, which is the hybrid-logical-clock receive rule.+ *+ * Cross-device ordering is still wall-based (two devices with skewed clocks+ * order by their stamps as before); this only removes the pathological+ * cases: same-device regression, and a fast device permanently winning+ * against a device that has actually seen (and advanced past) its stamps.+ *+ * [lastStamp] must be persisted per store by the caller (the highest stamp+ * the store has minted or observed โ€” e.g. `MAX(updatedAt)` over its rows,+ * or a persisted high-water key) so monotonicity survives process death.+ * Overflow saturates at [Long.MAX_VALUE] instead of wrapping negative.+ */+object SyncStamp {+    /** The next local stamp given the persisted [last] stamp and a wall reading. */+    fun next(last: Long, wallNow: Long): Long {+        if (last == Long.MAX_VALUE) return Long.MAX_VALUE+        return maxOf(wallNow, last + 1)+    }++    /** The persisted stamp after observing a [remote] stamp. */+    fun observe(last: Long, remote: Long): Long = maxOf(last, remote)+}++/**+ * Stateful [SyncStamp] generator for one store.+ *+ * Holds the store's last stamp in memory; the caller seeds [initialLast]+ * from (and persists [last] back to) the store's durable high-water mark.+ * [next] and [observe] are synchronized, so one generator may be shared by+ * every writer of a store. [wallNow] is injectable for tests.+ */+class HybridStampGenerator(+    initialLast: Long = 0L,+    private val wallNow: () -> Long = { System.currentTimeMillis() },+) {+    private var lastStamp: Long = initialLast++    /** The highest stamp minted or observed so far; persist this per store. */+    val last: Long+        @Synchronized get() = lastStamp++    /** Mints a stamp strictly greater than every stamp minted/observed before. */+    @Synchronized+    fun next(): Long {+        lastStamp = SyncStamp.next(lastStamp, wallNow())+        return lastStamp+    }++    /**+     * Advances the local counter past a [remote] stamp received from a peer,+     * so subsequent [next] stamps sort after it. Returns the new [last].+     */+    @Synchronized+    fun observe(remote: Long): Long {+        lastStamp = SyncStamp.observe(lastStamp, remote)+        return lastStamp+    }+}
library/src/test/java/com/vayunmathur/library/util/SyncStampTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/SyncStampTest.kt b/library/src/test/java/com/vayunmathur/library/util/SyncStampTest.ktnew file mode 100644index 0000000000..e4d83229ed--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/SyncStampTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.library.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Pure hybrid-stamp rules: monotonic per store, advanced by remote stamps. */+class SyncStampTest {++    @Test+    fun nextFollowsWallWhenWallIsAhead() {+        assertEquals(1_000L, SyncStamp.next(last = 10L, wallNow = 1_000L))+    }++    @Test+    fun nextStillIncreasesWhenWallJumpsBackwards() {+        var wall = 1_000L+        val gen = HybridStampGenerator(initialLast = 0L, wallNow = { wall })+        val first = gen.next()+        wall = 10L // clock jumps backwards+        val second = gen.next()+        val third = gen.next()+        assertEquals(1_000L, first)+        assertTrue(second > first, "stamp regressed after backwards clock: $first -> $second")+        assertTrue(third > second, "stamps must keep increasing: $second -> $third")+    }++    @Test+    fun observeFutureRemoteAdvancesSubsequentLocalStamps() {+        var wall = 1_000L+        val gen = HybridStampGenerator(initialLast = 0L, wallNow = { wall })+        gen.next()+        gen.observe(remote = 999_999L)+        val after = gen.next()+        assertTrue(after > 999_999L, "local stamp $after not past observed remote 999999")+        // An older remote stamp must not pull the counter back.+        gen.observe(remote = 5L)+        assertTrue(gen.next() > after)+    }++    @Test+    fun nextSaturatesAtMaxInsteadOfOverflowing() {+        assertEquals(Long.MAX_VALUE, SyncStamp.next(last = Long.MAX_VALUE, wallNow = 1L))+        assertEquals(Long.MAX_VALUE, SyncStamp.observe(last = Long.MAX_VALUE, remote = 1L))+    }+}
notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.ktindex 0ff98a172c..32bf7dd091 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt@@ -12,6 +12,7 @@ import androidx.room3.migration.Migration import androidx.sqlite.execSQL import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.library.util.DatabaseMigrations+import com.vayunmathur.library.util.SyncStamp import kotlinx.coroutines.flow.Flow  const val DB_NAME = "notes-db"@@ -41,9 +42,23 @@ abstract class NoteDao {     @Query("SELECT * FROM Note WHERE updatedAt > :since")     abstract suspend fun getUpdatedSince(since: Long): List<Note> +    /**+     * Highest stamp this store has minted or observed. The rows themselves+     * are the persisted hybrid-stamp high-water mark: a pulled remote stamp+     * lands via [upsertRaw], so the next local stamp (see [upsert]) is+     * automatically past it, and monotonicity survives process death with+     * no extra column.+     */+    @Query("SELECT MAX(updatedAt) FROM Note")+    abstract suspend fun maxUpdatedAt(): Long?++    /** Next hybrid stamp for a local write (see [SyncStamp]). */+    suspend fun nextStamp(): Long =+        SyncStamp.next(maxUpdatedAt() ?: 0L, System.currentTimeMillis())+     /** Local write: bumps updatedAt so the change is picked up by sync. */     suspend fun upsert(value: Note): Long =-        upsertRaw(value.copy(updatedAt = System.currentTimeMillis()))+        upsertRaw(value.copy(updatedAt = nextStamp()))      /** Writes [value] verbatim. Only the relay sync uses this, to preserve a pulled timestamp. */     @Upsert@@ -59,8 +74,10 @@ abstract class NoteDao {     abstract suspend fun deleteAll()      /** Local batch write (list reorder, legacy import): bumps updatedAt like [upsert]. */-    suspend fun upsertAll(values: List<Note>) =-        upsertAllRaw(values.map { it.copy(updatedAt = System.currentTimeMillis()) })+    suspend fun upsertAll(values: List<Note>) {+        val now = nextStamp()+        upsertAllRaw(values.map { it.copy(updatedAt = now) })+    }      /** Writes [values] verbatim. Only the relay sync uses this. */     @Upsert
notes/src/test/java/com/vayunmathur/notes/data/NoteHybridStampTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/data/NoteHybridStampTest.kt b/notes/src/test/java/com/vayunmathur/notes/data/NoteHybridStampTest.ktnew file mode 100644index 0000000000..2d8412581e--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/data/NoteHybridStampTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.notes.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.HybridStampGenerator+import com.vayunmathur.notes.seedNotesDb+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Hybrid sync stamps for the notes store: local stamps stay monotonic when+ * the wall clock jumps backwards, and a received future remote stamp+ * advances subsequent local stamps past it. The DAO persists the+ * high-water mark as `MAX(updatedAt)` over its rows (pulled stamps land+ * via `upsertRaw`), so no extra column is needed.+ */+@RunWith(RobolectricTestRunner::class)+class NoteHybridStampTest {+    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val repo get() = seedNotesDb(context)++    @BeforeTest fun purge() = runTest {+        repo.purge(); repo.deleteAllSnapshots()+    }++    @Test+    fun generatorStampsIncreaseWhenWallClockJumpsBackwards() {+        var wall = 1_000_000L+        var persisted = 0L+        val gen = HybridStampGenerator(initialLast = persisted, wallNow = { wall })+        val first = gen.next().also { persisted = gen.last }+        wall = 1L // wall clock jumps far backwards+        val second = gen.next().also { persisted = gen.last }+        assertTrue(second > first, "stamp regressed after backwards clock: $first -> $second")+        // A fresh generator seeded from the persisted mark stays ahead too.+        val restarted = HybridStampGenerator(initialLast = persisted, wallNow = { wall })+        assertTrue(restarted.next() > second)+    }++    @Test+    fun localUpsertAfterFutureRemoteStampExceedsRemote() = runTest {+        val future = System.currentTimeMillis() + 86_400_000L+        repo.upsertRaw(Note(title = "From fast device", content = "", syncId = "remote", updatedAt = future))+        repo.upsert(Note(title = "Local edit", content = "", syncId = "local"))+        val local = repo.getBySyncId("local")!!+        assertTrue(+            local.updatedAt > future,+            "local stamp ${local.updatedAt} did not advance past remote $future",+        )+        // Sequential local writes keep increasing even within one millisecond.+        repo.upsert(local.copy(title = "Local edit 2"))+        assertTrue(repo.getBySyncId("local")!!.updatedAt > local.updatedAt)+    }+}
todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.ktindex db1f83f262..193dfd5f67 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt@@ -10,6 +10,7 @@ import androidx.room3.Upsert import androidx.room3.migration.Migration import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.library.util.DatabaseMigrations+import com.vayunmathur.library.util.SyncStamp import kotlinx.coroutines.flow.Flow  const val DB_NAME = "todo-db"@@ -59,13 +60,27 @@ abstract class TodoDao {     @Query("SELECT * FROM Todo WHERE deleted = 0 AND listSyncId = :listSyncId")     abstract suspend fun getInList(listSyncId: String): List<Todo> +    /**+     * Highest stamp this store has minted or observed. The rows themselves+     * are the persisted hybrid-stamp high-water mark: a pulled remote stamp+     * lands via [upsertRaw], so the next local stamp (see [upsert]) is+     * automatically past it, and monotonicity survives process death with+     * no extra column.+     */+    @Query("SELECT MAX(updatedAt) FROM Todo")+    abstract suspend fun maxUpdatedAt(): Long?++    /** Next hybrid stamp for a local write (see [SyncStamp]). */+    suspend fun nextStamp(): Long =+        SyncStamp.next(maxUpdatedAt() ?: 0L, System.currentTimeMillis())+     /** Local write: bumps updatedAt so the change is picked up by sync. */     suspend fun upsert(value: Todo): Long =-        upsertRaw(value.copy(updatedAt = System.currentTimeMillis()))+        upsertRaw(value.copy(updatedAt = nextStamp()))      /** Local bulk write: bumps updatedAt on every row so reorders reach sync. */     suspend fun upsertAll(values: List<Todo>) {-        val now = System.currentTimeMillis()+        val now = nextStamp()         upsertAllRaw(values.map { it.copy(updatedAt = now) })     } @@ -105,11 +120,19 @@ abstract class TodoListDao {     @Query("SELECT MAX(position) FROM TodoList WHERE deleted = 0")     abstract suspend fun maxPosition(): Double? +    /** Highest stamp minted/observed by the lists store (see [TodoDao.maxUpdatedAt]). */+    @Query("SELECT MAX(updatedAt) FROM TodoList")+    abstract suspend fun maxUpdatedAt(): Long?++    /** Next hybrid stamp for a local list write (see [SyncStamp]). */+    suspend fun nextStamp(): Long =+        SyncStamp.next(maxUpdatedAt() ?: 0L, System.currentTimeMillis())+     suspend fun upsert(value: TodoList): Long =-        upsertRaw(value.copy(updatedAt = System.currentTimeMillis()))+        upsertRaw(value.copy(updatedAt = nextStamp()))      suspend fun upsertAll(values: List<TodoList>) {-        val now = System.currentTimeMillis()+        val now = nextStamp()         upsertAllRaw(values.map { it.copy(updatedAt = now) })     } 
todo/src/test/java/com/vayunmathur/todo/data/TodoHybridStampTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/data/TodoHybridStampTest.kt b/todo/src/test/java/com/vayunmathur/todo/data/TodoHybridStampTest.ktnew file mode 100644index 0000000000..0c9a3b19b2--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/data/TodoHybridStampTest.kt@@ -0,0 +1,67 @@+package com.vayunmathur.todo.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.HybridStampGenerator+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Hybrid sync stamps for the todo store: local stamps stay monotonic when+ * the wall clock jumps backwards, and a received future remote stamp+ * advances subsequent local stamps past it. The DAO persists the+ * high-water mark as `MAX(updatedAt)` over its rows (pulled stamps land+ * via `upsertRaw`), so no extra column is needed.+ */+@RunWith(RobolectricTestRunner::class)+class TodoHybridStampTest {+    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val harness = lazy { TestTodoRepository.create(context) }+    private val repo: TodoRepository get() = harness.value.repository++    @AfterTest fun tearDown() {+        if (harness.isInitialized()) harness.value.close()+    }++    @Test+    fun generatorStampsIncreaseWhenWallClockJumpsBackwards() {+        var wall = 1_000_000L+        var persisted = 0L+        val gen = HybridStampGenerator(initialLast = persisted, wallNow = { wall })+        val first = gen.next().also { persisted = gen.last }+        wall = 1L // wall clock jumps far backwards+        val second = gen.next().also { persisted = gen.last }+        assertTrue(second > first, "stamp regressed after backwards clock: $first -> $second")+        // A fresh generator seeded from the persisted mark stays ahead too.+        val restarted = HybridStampGenerator(initialLast = persisted, wallNow = { wall })+        assertTrue(restarted.next() > second)+    }++    @Test+    fun localUpsertAfterFutureRemoteStampExceedsRemote() = runTest {+        val future = System.currentTimeMillis() + 86_400_000L+        repo.upsertRaw(Todo(syncId = "remote", title = "From fast device", updatedAt = future))+        repo.upsert(Todo(syncId = "local", title = "Local edit"))+        val local = repo.getBySyncId("local")!!+        assertTrue(+            local.updatedAt > future,+            "local stamp ${local.updatedAt} did not advance past remote $future",+        )+        // Sequential local writes keep increasing even within one millisecond.+        repo.upsert(local.copy(title = "Local edit 2"))+        assertTrue(repo.getBySyncId("local")!!.updatedAt > local.updatedAt)+    }++    @Test+    fun listUpsertAfterFutureRemoteStampExceedsRemote() = runTest {+        val future = System.currentTimeMillis() + 86_400_000L+        repo.upsertListRaw(TodoList(syncId = "rlist", name = "Remote", updatedAt = future))+        repo.upsertList(TodoList(syncId = "llist", name = "Local"))+        val local = repo.getListBySyncId("llist")!!+        assertTrue(local.updatedAt > future, "list stamp ${local.updatedAt} not past remote $future")+    }+}