Modern Apps git

← Modern-Apps.git

everysync: restoring a snapshot can no longer overwrite (and re-publish) newer edits

Commit
5fe7bc8e0176311af98f3ffaeeccf7e363914760
Author
Vayun Mathur <[email protected]>
When
2026-12-01 04:23 UTC (5 days ago)
Parents
3411d27
SnapshotStore's own doc promises LWW merge input — 'newer
local edits win, nothing is force-overwritten' — but
writeRecords replayed every snapshot envelope through upsert
unconditionally. A note edited at 2000 restored from a 1000
snapshot came back as the old text locally; worse, the next
merge then read that as localDirty && !remoteDirty and
pushed the stale version to the relay over the newer synced
edit. The same flaw resurrected records deleted locally
after the snapshot (newer tombstone).

recordsToRestore now applies a snapshot record only when no
local row exists or its stamp is >= the local row's;
equal stamps still restore (preserving resurrection after
merge-GC deletes). All five record types plus note blobs
(blobs modified after takenAtMs are kept), fail-closed
local-read health checks, and the restore count reports only
records actually applied. No envelope keys renamed, no merge
semantics changed. Three new tests failed pre-fix on the
returned count for note/tombstone/passwords-todos cases.
RelayMerge folds, cursors and vault roster were audited and
cleared. Verified: :everysync:testDevUnitTest 189 tests
pass; lint errors are pre-existing on untouched files.

Diff

everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.ktindex 6913cb6e54..688e02cb2a 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/SnapshotStore.kt@@ -215,7 +215,7 @@ object SnapshotStore {             }.getOrNull() ?: return@withContext null             val count = writeRecords(context, snapshot.vaultId, snapshot.dataType, payload.records)                 ?: return@withContext null-            writeBlobs(context, snapshot.vaultId, snapshot.dataType, payload.blobs)+            writeBlobs(context, snapshot.vaultId, snapshot.dataType, payload.blobs, snapshot.takenAtMs)             Log.status(TAG, "restored ${snapshot.vaultId}/${snapshot.dataType} @${snapshot.dayEpochMs}: $count records")             count         }@@ -319,6 +319,29 @@ object SnapshotStore {         }?.filterValues { it.isNotEmpty() } ?: emptyMap()     } +    /**+     * The subset of [incoming] that may be written over [current]: a local+     * row stamped strictly after the snapshot record — a newer edit, or a+     * newer tombstone — wins by LWW and is never force-overwritten by a+     * restore; without this filter the restored stale row looked like the+     * only local change to the next merge and was pushed to the relay over+     * the newer edit. Equal stamps go to the snapshot: an explicit restore+     * is the tiebreaker, and a tombstone stamped no newer than the snapshot+     * (e.g. a merge garbage-collection delete) does not block resurrection.+     */+    private fun <T> recordsToRestore(+        incoming: List<T>,+        current: List<T>,+        id: (T) -> String,+        updatedAt: (T) -> Long,+    ): List<T> {+        val localById = current.associateBy(id)+        return incoming.filter { record ->+            val local = localById[id(record)]+            local == null || updatedAt(record) >= updatedAt(local)+        }+    }+     private fun writeRecords(         context: Context,         vaultId: String,@@ -329,24 +352,35 @@ object SnapshotStore {             when (dataType) {                 "passwords" -> {                     val parsed = records.mapNotNull { PasswordKind.fromJson(it) }-                    PasswordSink.upsertAll(context, vaultId, parsed)-                    parsed.size+                    val current = PasswordSink.listLocalOrThrow(context, vaultId)+                    val toRestore = recordsToRestore(parsed, current, { it.uid }, { it.updatedAt })+                    PasswordSink.upsertAll(context, vaultId, toRestore)+                    toRestore.size                 }                 "notes" -> {                     val parsed = records.mapNotNull { NoteKind.fromJson(it) }-                    NoteSink.upsertAll(context, vaultId, parsed)-                    parsed.size+                    val current = NoteSink.listLocal(context, vaultId)+                    check(NoteSink.lastListLocalOk) { "note provider read failed for vault $vaultId" }+                    val toRestore = recordsToRestore(parsed, current, { it.uid }, { it.updatedAt })+                    NoteSink.upsertAll(context, vaultId, toRestore)+                    toRestore.size                 }                 "todos" -> {                     val parsed = records.mapNotNull { TodoKind.fromJson(it) }-                    TodoIpcSink.upsertAll(context, vaultId, parsed)-                    parsed.size+                    val current = TodoIpcSink.listLocal(context, vaultId)+                    check(TodoIpcSink.lastListLocalOk) { "todo provider read failed for vault $vaultId" }+                    val toRestore = recordsToRestore(parsed, current, { it.uid }, { it.updatedAt })+                    TodoIpcSink.upsertAll(context, vaultId, toRestore)+                    toRestore.size                 }                 "contacts" -> {                     val account = accountForVault(context, vaultId) ?: return null                     val parsed = records.mapNotNull { ContactKind.fromJson(it) }-                    for (item in parsed) ContactsSink.upsert(context, account, item)-                    parsed.size+                    val current = ContactsSink.listLocal(context, account)+                    check(ContactsSink.lastListLocalOk) { "contacts provider read failed for $account" }+                    val toRestore = recordsToRestore(parsed, current, { it.uid }, { it.updatedAt })+                    for (item in toRestore) ContactsSink.upsert(context, account, item)+                    toRestore.size                 }                 "calendar" -> {                     val account = accountForVault(context, vaultId) ?: return null@@ -355,20 +389,39 @@ object SnapshotStore {                     )                     if (calendarId == -1L) return null                     val parsed = records.mapNotNull { CalendarKind.fromJson(it) }-                    for (item in parsed) CalendarSink.upsertEvent(context, account, calendarId, item)-                    parsed.size+                    val current = CalendarSink.listLocal(context, calendarId)+                    check(CalendarSink.lastListLocalOk) { "calendar provider read failed for $calendarId" }+                    val toRestore = recordsToRestore(+                        parsed, current, { CalendarKind.syncId(it) }, { it.updatedAt },+                    )+                    for (item in toRestore) CalendarSink.upsertEvent(context, account, calendarId, item)+                    toRestore.size                 }                 else -> null             }         }.getOrNull()     } -    private fun writeBlobs(context: Context, vaultId: String, dataType: String, blobs: Map<String, String>) {+    private fun writeBlobs(+        context: Context,+        vaultId: String,+        dataType: String,+        blobs: Map<String, String>,+        takenAtMs: Long = 0L,+    ) {         if (dataType != "notes" || blobs.isEmpty()) return         blobs.forEach { (name, b64) ->             if (name.isNotBlank()) {                 runCatching { Base64.decode(b64) }.getOrNull()?.let { bytes ->-                    RelayBlobStore.writeLocal(context, vaultId, name, bytes)+                    // Same LWW rule as records: a blob file changed after the+                    // snapshot was taken is newer local state, not restore input.+                    val local = RelayBlobStore.readLocal(context, vaultId, name)+                    val localFile = File(File(context.filesDir, "relay_blobs/$vaultId"), name)+                    val localIsNewer = takenAtMs > 0L && local != null &&+                        localFile.lastModified() > takenAtMs && !local.contentEquals(bytes)+                    if (!localIsNewer) {+                        RelayBlobStore.writeLocal(context, vaultId, name, bytes)+                    }                 }             }         }
everysync/src/test/java/com/vayunmathur/everysync/SnapshotRestoreNewerEditTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/SnapshotRestoreNewerEditTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/SnapshotRestoreNewerEditTest.ktnew file mode 100644index 0000000000..4a105e8135--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/SnapshotRestoreNewerEditTest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.everysync++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.TokenStore+import com.vayunmathur.everysync.data.RemoteNote+import com.vayunmathur.everysync.data.RemotePassword+import com.vayunmathur.everysync.data.RemoteTodo+import com.vayunmathur.everysync.data.VaultMeta+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.readKey+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.provider.E2eeProvider+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.sync.SnapshotKeyStore+import com.vayunmathur.everysync.sync.SnapshotStore+import com.vayunmathur.everysync.sync.adapters.NoteKind+import javax.crypto.spec.SecretKeySpec+import kotlin.io.encoding.Base64+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Regression: restoring a daily snapshot must not overwrite a newer local+ * edit (SnapshotStore documents restore as LWW merge input: "newer local+ * edits win ... nothing is force-overwritten"). Before the fix, restore+ * replayed the snapshot through the sink upserts unconditionally, so the+ * older snapshot row replaced the newer local row, and the following sync+ * then saw the restored row as the only local change and pushed the stale+ * version to the relay over the newer edit.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class SnapshotRestoreNewerEditTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val relay get() = RelaySuccessTest.sharedRelay++    @BeforeTest fun setUp() {+        relay.install()+        FakeIpcProvider.install(NoteSink.AUTHORITY, PasswordSink.AUTHORITY, TodoIpcSink.AUTHORITY)+        val softwareKey = SecretKeySpec(ByteArray(32) { (it * 7 + 1).toByte() }, "AES")+        com.vayunmathur.everysync.data.VaultKeyStore.secretKeyForTest = softwareKey+        SnapshotKeyStore.secretKeyForTest = softwareKey+        TokenStore.getInstance(ctx).secretKeyForTest = softwareKey+    }++    private suspend fun makeVault(type: String, vaultId: String): VaultMeta {+        val key = RelaySync.newVaultKey()+        val meta = VaultMeta(+            vaultId = vaultId, dataType = type, title = "T-$type",+            keyB64 = Base64.encode(key), ownerDeviceId = RelaySync.deviceId,+            ownerKeyB64 = Base64.encode(RelaySync.publicBundle), isOwner = true,+        )+        VaultStore.upsert(ctx, meta)+        com.vayunmathur.everysync.provider.SyncState.set(ctx, ACCOUNT, "e2ee_vault_$type", vaultId)+        return VaultStore.get(ctx, vaultId)!!+    }++    @Test fun restoreDoesNotOverwriteNewerNoteEditOrPushStaleCopyToRelay() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val meta = makeVault("notes", "v-restore-newer-note")+        val vaultKey = meta.readKey()!!+        NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "rn1", title = "Old", content = "v1", updatedAt = 1_000))+        assertTrue(SnapshotStore.snapshotVault(ctx, meta.vaultId, "notes"))+        val snapshot = SnapshotStore.listForVault(ctx, meta.vaultId).single()++        // Newer local edit, already synced so the relay + baseline hold it.+        NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "rn1", title = "New", content = "v2", updatedAt = 2_000))+        val config = AccountConfig(ACCOUNT, "e2ee", setOf(DataType.NOTES))+        E2eeProvider().sync(ctx, config, SyncDirection.BOTH)+        val channel = RelaySync.recordChannel("notes", meta.vaultId)+        assertEquals(+            "New",+            RelaySync.pullRecords(channel, vaultKey, 0)!!.items+                .mapNotNull { NoteKind.fromJson(it) }.last { it.uid == "rn1" }.title,+        )++        // Restoring the older snapshot must leave the newer edit alone.+        assertEquals(0, SnapshotStore.restore(ctx, snapshot))+        assertEquals("New", NoteSink.listLocal(ctx, meta.vaultId).single { it.uid == "rn1" }.title)++        // And the post-restore reconcile must not push the stale copy over it.+        E2eeProvider().sync(ctx, config, SyncDirection.BOTH)+        assertEquals(+            "New",+            RelaySync.pullRecords(channel, vaultKey, 0)!!.items+                .mapNotNull { NoteKind.fromJson(it) }.last { it.uid == "rn1" }.title,+        )+        assertEquals("New", NoteSink.listLocal(ctx, meta.vaultId).single { it.uid == "rn1" }.title)+    } }++    @Test fun restoreDoesNotResurrectANewerLocalTombstone() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val meta = makeVault("notes", "v-restore-newer-tombstone")+        NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "rn2", title = "Gone", updatedAt = 1_000))+        assertTrue(SnapshotStore.snapshotVault(ctx, meta.vaultId, "notes"))+        val snapshot = SnapshotStore.listForVault(ctx, meta.vaultId).single()++        // Deleted locally after the snapshot, with a newer stamp.+        NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "rn2", title = "Gone", updatedAt = 2_000))+        NoteSink.delete(ctx, meta.vaultId, "rn2")+        assertTrue(NoteSink.listLocal(ctx, meta.vaultId).single { it.uid == "rn2" }.deleted)++        assertEquals(0, SnapshotStore.restore(ctx, snapshot))+        assertTrue(NoteSink.listLocal(ctx, meta.vaultId).single { it.uid == "rn2" }.deleted)+    } }++    @Test fun restoreDoesNotOverwriteNewerPasswordOrTodoEdits() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val pwMeta = makeVault("passwords", "v-restore-newer-pw")+        PasswordSink.upsert(ctx, pwMeta.vaultId, RemotePassword(uid = "rp1", name = "Mail", password = "old-pw", updatedAt = 1_000))+        assertTrue(SnapshotStore.snapshotVault(ctx, pwMeta.vaultId, "passwords"))+        val pwSnapshot = SnapshotStore.listForVault(ctx, pwMeta.vaultId).single()+        PasswordSink.upsert(ctx, pwMeta.vaultId, RemotePassword(uid = "rp1", name = "Mail", password = "new-pw", updatedAt = 2_000))+        assertEquals(0, SnapshotStore.restore(ctx, pwSnapshot))+        assertEquals("new-pw", PasswordSink.listLocal(ctx, pwMeta.vaultId).single { it.uid == "rp1" }.password)++        val todoMeta = makeVault("todos", "v-restore-newer-todo")+        TodoIpcSink.upsert(ctx, todoMeta.vaultId, RemoteTodo(uid = "rt1", title = "Old task", updatedAt = 1_000))+        assertTrue(SnapshotStore.snapshotVault(ctx, todoMeta.vaultId, "todos"))+        val todoSnapshot = SnapshotStore.listForVault(ctx, todoMeta.vaultId).single()+        TodoIpcSink.upsert(ctx, todoMeta.vaultId, RemoteTodo(uid = "rt1", title = "New task", updatedAt = 2_000))+        assertEquals(0, SnapshotStore.restore(ctx, todoSnapshot))+        assertEquals("New task", TodoIpcSink.listLocal(ctx, todoMeta.vaultId).single { it.uid == "rt1" }.title)+    } }++    private companion object { const val ACCOUNT = "restore-alice" }+}