Modern Apps git

← Modern-Apps.git

everysync: envelopes from clients without sync ids are adopted, not dropped

Commit
1e399d33d41486ccf1c8d92878c96bb89767d6da
Author
Vayun Mathur <[email protected]>
When
2026-11-30 21:53 UTC (5 days ago)
Parents
6d09a06
Every production RelayStore.parseRemote filtered out blank-uid
envelopes, so a record written by a client that doesn't know
EverySync's sync ids (RelayMerge.adoptUnidentified's documented
input) never reached the merge at all — pulled from 0 and
re-dropped forever. The merge-level adoption tests only passed
because their fake store lacked the filter: a wiring mismatch
between the store and merge layers.

All six stores now return the parsed envelope even with a blank
uid (corrupt JSON still returns null), and adoptUnidentified
skips an unidentified envelope whose content hash already exists
identified in the same fold — otherwise the blank original
sitting beside its identified re-append in the append-only log
minted a fresh identity every cycle. No envelope keys renamed.
New store/E2E/merge regression tests failed pre-fix (E2E showed
the per-cycle duplication after the store fix alone); three
assertions encoding the old drop behaviour were updated.
Verified: :everysync:testDevUnitTest 186 tests pass; lint errors
are pre-existing on untouched files.

Diff

everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.ktindex b8647a4cd9..51e9d97494 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt@@ -272,8 +272,17 @@ object RelayMerge {         // copy still lacks it).         val adoptableByContentKey = local.values.filter { kind.syncId(it) !in remote }             .associateBy({ kind.contentKey(it) }, { kind.syncId(it) })+        // The original blank envelope stays in the append-only log after its+        // identified re-append, so on later cycles it folds in beside that+        // copy. Re-adopting it then would mint a fresh id and duplicate the+        // record every cycle: an unidentified envelope whose content already+        // exists identified in this fold is that pre-adoption original, not+        // a new record. (Distinct blanks in the same fold are unaffected:+        // only ids identified before adoption count.)+        val identifiedHashes = remote.values.map { kind.contentHash(it) }.toSet()         val claimed = mutableSetOf<String>()         for (entity in unidentified) {+            if (kind.contentHash(entity) in identifiedHashes) continue             val match = adoptableByContentKey[kind.contentKey(entity)]             val id = match?.takeIf { it !in claimed && it !in remote } ?: newRelaySyncId()             claimed += id
everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.ktindex f710dc72a9..15786c7620 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/VaultRelayStores.kt@@ -35,6 +35,13 @@ import com.vayunmathur.everysync.sync.adapters.TodoListKind  *    (vault, kind) — never the app-side snapshot tables, which belong to the  *    app processes.  *+ * `parseRemote` in every store below must NOT drop an envelope for a blank+ * `uid`: records written by a client that does not know our sync ids carry+ * no identity, and [RelayMerge] adopts them (content-key match or a fresh+ * id, then a re-append identified). Filtering blank ids here would silently+ * lose those records before the merge ever sees them. Corrupt JSON still+ * parses to null and is skipped.+ *  * Contacts/calendar identity notes:  *  - contacts key on [RemoteContact.uid] ↔ RawContacts.SOURCE_ID (see  *    `ContactKind`); the calendarId field is unused.@@ -89,7 +96,7 @@ class ContactRelayStore(     }      override fun parseRemote(json: String): RemoteContact? =-        ContactKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }+        ContactKind.fromJson(json)      override fun serializeForRemote(entity: RemoteContact): String =         ContactKind.toJson(entity)@@ -132,7 +139,7 @@ class CalendarRelayStore(     }      override fun parseRemote(json: String): RemoteEvent? =-        CalendarKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }+        CalendarKind.fromJson(json)      override fun serializeForRemote(entity: RemoteEvent): String =         CalendarKind.toJson(entity)@@ -178,7 +185,7 @@ class PasswordRelayStore(     }      override fun parseRemote(json: String): RemotePassword? =-        PasswordKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }+        PasswordKind.fromJson(json)      override fun serializeForRemote(entity: RemotePassword): String =         PasswordKind.toJson(entity)@@ -223,7 +230,7 @@ class NoteRelayStore(     }      override fun parseRemote(json: String): RemoteNote? =-        NoteKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }+        NoteKind.fromJson(json)      override fun serializeForRemote(entity: RemoteNote): String =         NoteKind.toJson(entity)@@ -265,7 +272,7 @@ class TodoRelayStore(     }      override fun parseRemote(json: String): RemoteTodo? =-        TodoKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }+        TodoKind.fromJson(json)      override fun serializeForRemote(entity: RemoteTodo): String =         TodoKind.toJson(entity)@@ -302,7 +309,7 @@ class TodoListRelayStore(     }      override fun parseRemote(json: String): RemoteTodoList? =-        TodoListKind.fromJson(json)?.takeIf { it.uid.isNotBlank() }+        TodoListKind.fromJson(json)      override fun serializeForRemote(entity: RemoteTodoList): String =         TodoListKind.toJson(entity)
everysync/src/test/java/com/vayunmathur/everysync/BlankUidEnvelopeAdoptionTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/BlankUidEnvelopeAdoptionTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/BlankUidEnvelopeAdoptionTest.ktnew file mode 100644index 0000000000..e5d8450bed--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/BlankUidEnvelopeAdoptionTest.kt@@ -0,0 +1,123 @@+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.VaultMeta+import com.vayunmathur.everysync.data.VaultStore+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.NoteRelayStore+import com.vayunmathur.everysync.sync.SnapshotKeyStore+import com.vayunmathur.everysync.sync.TodoRelayStore+import com.vayunmathur.everysync.sync.adapters.NoteKind+import com.vayunmathur.everysync.sync.adapters.TodoKind+import com.vayunmathur.everysync.data.RemoteTodo+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.assertNotNull+import kotlin.test.assertTrue++/**+ * Regression: relay envelopes written by a client that does not know our+ * sync ids carry a blank `uid`. [com.vayunmathur.everysync.sync.RelayMerge]+ * is designed to adopt them (assign/adopt an identity, pull, and re-append+ * identified), but the production [NoteRelayStore]/[TodoRelayStore]+ * `parseRemote` used to drop blank-uid envelopes before the merge ever saw+ * them, so such records were silently lost on every sync cycle.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class BlankUidEnvelopeAdoptionTest {+    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): Pair<VaultMeta, ByteArray> {+        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)!! to key+    }++    @Test fun storeParseRemoteKeepsBlankUidForMergeAdoption() {+        val noteStore = NoteRelayStore(ctx, "v-blank-parse")+        val parsedNote = noteStore.parseRemote(NoteKind.toJson(RemoteNote(uid = "", title = "blank", updatedAt = 5L)))+        assertNotNull(parsedNote)+        assertEquals("", parsedNote.uid)+        val todoStore = TodoRelayStore(ctx, "v-blank-parse")+        val parsedTodo = todoStore.parseRemote(TodoKind.toJson(RemoteTodo(uid = "", title = "blank", updatedAt = 5L)))+        assertNotNull(parsedTodo)+        assertEquals("", parsedTodo.uid)+    }++    @Test fun blankUidNoteEnvelopeIsAdoptedPulledAndReappendedIdentified() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val (meta, key) = makeVault("notes", "v-blank-adopt")+        val channel = RelaySync.recordChannel("notes", meta.vaultId)+        // A client that does not know our sync ids appends a note with uid="".+        RelaySync.appendRecords(+            channel, key,+            listOf(NoteKind.toJson(RemoteNote(uid = "", title = "Legacy note", content = "body", updatedAt = 1_000))),+        )+        assertEquals(1, relay.channel(channel).size)+        E2eeProvider().sync(ctx, AccountConfig(ACCOUNT, "e2ee", setOf(DataType.NOTES)), SyncDirection.BOTH)+        // The record is pulled locally under a freshly assigned identity...+        val local = NoteSink.listLocal(ctx, meta.vaultId)+        assertEquals(1, local.size)+        assertEquals("Legacy note", local.single().title)+        assertTrue(local.single().uid.isNotBlank())+        // ...and re-appended to the relay identified with that same identity.+        val relayNotes = RelaySync.pullRecords(channel, key, 0)!!.items.mapNotNull { NoteKind.fromJson(it) }+        assertEquals(local.single().uid, relayNotes.last().uid)+        // A second cycle is a clean no-op: no duplicate is created.+        E2eeProvider().sync(ctx, AccountConfig(ACCOUNT, "e2ee", setOf(DataType.NOTES)), SyncDirection.BOTH)+        assertEquals(1, NoteSink.listLocal(ctx, meta.vaultId).size)+        assertEquals(2, relay.channel(channel).size)+    } }++    @Test fun blankEnvelopeAlreadyAdoptedInFoldIsNotReadopted() {+        // Cycle 2 fold: the original blank envelope beside its identified+        // re-append, with the adopted copy already local. It must not mint+        // another identity or duplicate the record.+        val adopted = RemoteTodo(uid = "adopted1", title = "Shop", createdAt = 7L, updatedAt = 100L)+        val blankOriginal = RemoteTodo(uid = "", title = "Shop", createdAt = 7L, updatedAt = 100L)+        val plan = com.vayunmathur.everysync.sync.RelayMerge.merge(+            TodoKind, listOf(adopted), listOf(blankOriginal, adopted), emptyMap(), 1000L,+        )+        assertTrue(plan.localUpserts.isEmpty())+        assertTrue(plan.remoteOut.isEmpty())+        assertEquals(1, plan.snapshots.size)+        assertEquals("adopted1", plan.snapshots.single().syncId)+    }++    private companion object { const val ACCOUNT = "blankuid-alice" }+}
everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.ktindex c5f2bf7176..acacece143 100644--- a/everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.kt+++ b/everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.kt@@ -1,5 +1,7 @@ package com.vayunmathur.everysync +// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+ import android.app.Application import android.content.Context import androidx.test.core.app.ApplicationProvider@@ -206,7 +208,8 @@ class E2eeDriveTest {         val (meta, _) = makeVault("notes", "v-store1")         val store = NoteRelayStore(ctx, meta.vaultId)         assertNull(store.parseRemote("not json"))-        assertNull(store.parseRemote(NoteKind.toJson(RemoteNote(uid = "", title = "blank"))))+        // Blank uid is kept: RelayMerge adopts unidentified envelopes.+        assertEquals("", store.parseRemote(NoteKind.toJson(RemoteNote(uid = "", title = "blank")))!!.uid)         val note = RemoteNote(uid = "s1", title = "Stored", updatedAt = 7)         assertEquals(note, store.parseRemote(store.serializeForRemote(note)))         store.upsertLocal(listOf(note))
everysync/src/test/java/com/vayunmathur/everysync/PlatformTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/PlatformTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/PlatformTest.ktindex 6a30d58e7c..ce34dfb472 100644--- a/everysync/src/test/java/com/vayunmathur/everysync/PlatformTest.kt+++ b/everysync/src/test/java/com/vayunmathur/everysync/PlatformTest.kt@@ -100,7 +100,8 @@ class PlatformTest {     @Test fun relayStoresParseAndBaseline() { runBlocking {         val contact = ContactRelayStore(ctx, "acc", "v1")         assertNull(contact.parseRemote("bad")); assertTrue(contact.parseRemote("""{"uid":"c1","displayName":"Ann"}""") != null)-        assertNull(contact.parseRemote("""{"uid":""}""")); assertTrue(contact.serializeForRemote(contact.parseRemote("""{"uid":"c1"}""")!!).contains("c1"))+        // Blank uid is kept: RelayMerge adopts unidentified envelopes.+        assertTrue(contact.parseRemote("""{"uid":""}""") != null); assertTrue(contact.serializeForRemote(contact.parseRemote("""{"uid":"c1"}""")!!).contains("c1"))         assertTrue(contact.loadBaseline().isEmpty()); contact.saveSnapshots(emptyList()); contact.removeSnapshots(emptyList())         // listLocal via sinks without providers: empty but callable         contact.listLocal(); contact.upsertLocal(emptyList()); contact.deleteLocal(emptyList())
everysync/src/test/java/com/vayunmathur/everysync/Wave3DeepTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/Wave3DeepTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/Wave3DeepTest.ktindex 805bdc5762..ec83326435 100644--- a/everysync/src/test/java/com/vayunmathur/everysync/Wave3DeepTest.kt+++ b/everysync/src/test/java/com/vayunmathur/everysync/Wave3DeepTest.kt@@ -311,7 +311,8 @@ class Wave3DeepTest {         val contact = RemoteContact(uid = "sc1", displayName = "Store Contact")         assertEquals(contact, contacts.parseRemote(contacts.serializeForRemote(contact)))         assertNull(contacts.parseRemote("not json"))-        assertNull(contacts.parseRemote(ContactKind.toJson(RemoteContact(uid = "", displayName = "x"))))+        // Blank uid is kept: RelayMerge adopts unidentified envelopes.+        assertEquals("", contacts.parseRemote(ContactKind.toJson(RemoteContact(uid = "", displayName = "x")))!!.uid)         contacts.upsertLocal(listOf(contact))         contacts.saveSnapshots(listOf(RelaySnapshot("sc1", ContactKind.kind, "h1", 1, 1, 1)))         assertEquals("h1", contacts.loadBaseline()["sc1"]?.contentHash)