Modern Apps git

← Modern-Apps.git

everysync: the relay fold keeps the last-writer-wins winner, not the log tail

Commit
d852a588738782f0aee3cafb573c8c35b55df086
Author
Vayun Mathur <[email protected]>
When
2026-12-01 09:09 UTC (5 days ago)
Parents
b9d4a54
indexRemote folded the append-only relay log with
unconditional last-in-log-wins. Log position is not write
order: two devices editing offline append in whichever
order they reconnect, and the slower-clock device can append
last. A remote log of ['Newer edit'@200, 'Stale edit'@100]
folded to the stale copy, and the merge then locked it in
(hash aligned to the stale baseline) โ€” the @200 edit was
shadowed on every later cycle, permanently lost despite
being in the log. The symmetric case kept a live copy over
its @200 tombstone (the delete never applied), and equal
stamps resolved by log position instead of the documented
contentHash tiebreak devices rely on to converge. The fold
discarded the winner before reconcilePresent/
resolveTombstone ever saw it.

indexRemote now keeps, per sync id, the envelope winning the
merge's own LWW rule (foldWins): higher updatedAt; on tie a
tombstone beats live (matching resolveTombstone), then
higher contentHash (matching reconcileDiverged); fully-equal
envelopes still take the later copy, preserving duplicate/
adoption behaviour. No envelope fields renamed or added โ€”
relay/hash compatibility with todo untouched (the standing
constraint). Three regression tests failed pre-fix (3/6 in
the class). Envelope integrity, vault isolation, the offline
queue and restore were audited and cleared. Verified:
:everysync:testDevUnitTest passes in full; 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 51e9d97494..9adaf2d1f3 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayMerge.kt@@ -243,13 +243,17 @@ object RelayMerge {         for (entity in remoteEntities) {             val id = kind.syncId(entity).takeIf { it.isNotBlank() }             if (id != null) {-                // The relay log is append-only: a later envelope for the same-                // id is the newer state of that record, so the fold is-                // latest-wins. (First-wins would shadow every edit and-                // tombstone behind the original append, and route the newer-                // envelope into the blank-id adoption path, duplicating the-                // record under a fresh random id.)-                remote[id] = entity+                // The relay log is append-only, but log position is not write+                // order: two devices editing the same record while offline+                // append in whichever order they reconnect, and the device+                // with the slower clock can append last. The fold therefore+                // keeps the envelope that wins the merge's own LWW rule+                // (updatedAt, tombstone on an equal stamp, then contentHash)+                // instead of the last one in the log โ€” otherwise the winning+                // edit or tombstone is shadowed by a stale envelope on every+                // cycle and never reaches the local side.+                val current = remote[id]+                if (current == null || foldWins(kind, entity, current)) remote[id] = entity             } else {                 unidentified += entity             }@@ -258,6 +262,16 @@ object RelayMerge {         return remote     } +    /** True when [candidate] beats [current] for the same id under the merge LWW rule. */+    private fun <T> foldWins(kind: EntityKind<T>, candidate: T, current: T): Boolean {+        val candidateStamp = kind.updatedAt(candidate)+        val currentStamp = kind.updatedAt(current)+        if (candidateStamp != currentStamp) return candidateStamp > currentStamp+        val candidateDeleted = kind.isDeleted(candidate)+        if (candidateDeleted != kind.isDeleted(current)) return candidateDeleted+        return kind.contentHash(candidate) >= kind.contentHash(current)+    }+     private fun <T> adoptUnidentified(         kind: EntityKind<T>,         local: Map<String, T>,
everysync/src/test/java/com/vayunmathur/everysync/sync/RelayMergeFoldTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/sync/RelayMergeFoldTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/sync/RelayMergeFoldTest.ktindex 2257878b13..af96f3aa82 100644--- a/everysync/src/test/java/com/vayunmathur/everysync/sync/RelayMergeFoldTest.kt+++ b/everysync/src/test/java/com/vayunmathur/everysync/sync/RelayMergeFoldTest.kt@@ -39,6 +39,36 @@ class RelayMergeFoldTest {             "deletes=${plan.localDeletes} upserts=${plan.localUpserts}")     } +    @Test fun outOfOrderNewerEnvelopeWinsDespiteEarlierLogPosition() {+        // Two devices edit the same record while offline; the newer edit+        // (t=200) reconnects and appends first, the stale edit (t=100, slow+        // clock) appends last. Log position must not shadow the LWW winner.+        val v1 = todo("a", "Original", 100)+        val newer = todo("a", "Newer edit", 200)+        val stale = todo("a", "Stale edit", 100)+        val plan = RelayMerge.merge(TodoKind, listOf(v1), listOf(newer, stale), mapOf("a" to base(v1)), 1_000)+        assertEquals(1, plan.pulled)+        assertEquals(listOf(newer), plan.localUpserts)+        assertEquals(0, plan.pushed)+    }++    @Test fun outOfOrderTombstoneNotShadowedByOlderLiveEnvelope() {+        val live = todo("a", "Original", 100)+        val tomb = todo("a", "Original", 200, deleted = true)+        val plan = RelayMerge.merge(TodoKind, listOf(live), listOf(tomb, live), mapOf("a" to base(live)), 1_000)+        assertTrue(plan.localDeletes.any { it.uid == "a" } || plan.localUpserts.any { it.deleted },+            "deletes=${plan.localDeletes} upserts=${plan.localUpserts}")+    }++    @Test fun equalStampFoldKeepsDeterministicWinnerNotLastInLog() {+        val a = todo("a", "Alpha", 100)+        val b = todo("a", "Beta", 100)+        val high = maxOf(a, b, compareBy { TodoKind.contentHash(it) })+        val low = if (high == a) b else a+        val plan = RelayMerge.merge(TodoKind, emptyList(), listOf(high, low), emptyMap(), 1_000)+        assertEquals(listOf(high), plan.localUpserts)+    }+     @Test fun identicalDuplicatesStillMergeOnce() {         val a = todo("x", "One", 100)         val plan = RelayMerge.merge(TodoKind, emptyList(), listOf(a, a.copy()), emptyMap(), 1_000)