6ac4482f841f

expand the cross-client matrix from two scenarios to eleven

time
2026-09-10 23:33 UTC · 2 months ago
machine
koh2
agent
deepseek/deepseek-v4-flash
session
cross-client matrix
parent
ed1d47b3c8f6
1 file app/src/test/java/com/peachpasswords/sync/CrossClientSyncProcessTest.kt+146 −33
app/src/test/java/com/peachpasswords/sync/CrossClientSyncProcessTest.kt+146 −33
@@ -9,14 +9,21 @@99 import java.net.ServerSocket1010 import java.net.Socket1111 import java.util.Base6412+import kotlin.system.exitProcess1213 import kotlinx.coroutines.runBlocking1314 import org.junit.Assert.assertEquals1415 import org.junit.Test1516 1617 /**1718  * Process endpoint for scripts/check-cross-client-sync.mjs. The socket carries18- * one base64-encoded production SyncMessage frame per line; the transcript is19- * kept separately so the parent process can assert every ordered wire type.19+ * one base64-encoded, production-padded SyncMessage frame per line; the20+ * transcript is kept separately so the parent process can assert every ordered21+ * wire type.22+ *23+ * Scenario shape is supplied entirely by the parent — this endpoint reads knobs24+ * and does not know what a "scenario" is. Keeping the semantics in the harness25+ * is what lets both clients be configured identically and lets a reviewer read26+ * the matrix in one place.2027  */2128 class CrossClientSyncProcessTest {2229     @Test@@ -24,7 +31,7 @@2431         val mode = configured("PEACH_SYNC_HARNESS_MODE") ?: return2532         val portFile = File(requireConfigured("PEACH_SYNC_HARNESS_PORT_FILE"))2633         val transcriptFile = File(requireConfigured("PEACH_SYNC_HARNESS_TRANSCRIPT_FILE"))27-        val mismatch = configured("PEACH_SYNC_HARNESS_MISMATCH") == "message-order"34+        val config = HarnessConfig.read(if (mode == "initiator") "android" else "browser", ::configured)2835         val socket = if (mode == "initiator") {2936             ServerSocket(0).also {3037                 portFile.writeText(it.localPort.toString())@@ -39,49 +46,82 @@3946             val input = BufferedReader(InputStreamReader(raw.getInputStream(), Charsets.UTF_8))4047             val output = BufferedWriter(OutputStreamWriter(raw.getOutputStream(), Charsets.UTF_8))4148             val transcript = mutableListOf<String>()49+            val vault = ProcessVault(config)50+            // Simulated process death: the transcript is on disk before the51+            // process goes, so the parent can still say what the peer had seen.52+            val die: () -> Nothing = {53+                transcriptFile.writeText(renderTranscript("DIED", null, vault, transcript))54+                exitProcess(7)55+            }4256             val session = SyncSession(4357                 remoteStaticPublicKey = ByteArray(32) { 7 },4458                 send = { bytes ->4559                     val message = decodeSyncMessage(bytes)46-                    val wireMessage = if (mismatch && message is SyncMessage.Manifest) {60+                    val wireMessage = if (config.mismatch && message is SyncMessage.Manifest) {4761                         SyncMessage.Request(emptyList())48-                    } else message62+                    } else {63+                        message64+                    }4965                     transcript += "send:${messageType(wireMessage)}"50-                    val wire = wireMessage.encodeToBytes()51-                    output.write(Base64.getEncoder().encodeToString(wire))66+                    if (config.stopAfter == messageType(wireMessage)) die()67+                    val padded = SyncPadding.pad(wireMessage.encodeToBytes())68+                    output.write(Base64.getEncoder().encodeToString(padded))5269                     output.newLine()5370                     output.flush()5471                 },5572                 receive = {5673                     val line = input.readLine() ?: error("cross-client peer closed")57-                    val bytes = Base64.getDecoder().decode(line)58-                    val message = decodeSyncMessage(bytes)59-                    transcript += "recv:${messageType(message)}"60-                    bytes74+                    val payload = SyncPadding.unpad(Base64.getDecoder().decode(line))75+                    transcript += "recv:${messageType(decodeSyncMessage(payload))}"76+                    payload6177                 },6278                 close = {},6379             )64-            val vault = ProcessVault(if (mode == "initiator") "android" else "browser")6580             val outcome = runBlocking {66-                if (mode == "initiator") runSyncInitiator(session, vault, nowMs = System.currentTimeMillis())67-                else runSyncResponder(session, vault, nowMs = System.currentTimeMillis())81+                if (mode == "initiator") {82+                    runSyncInitiator(session, vault, nowMs = System.currentTimeMillis())83+                } else {84+                    runSyncResponder(session, vault, nowMs = System.currentTimeMillis())85+                }6886             }69-            transcriptFile.writeText(70-                buildString {71-                    append("{\"status\":\"").append(outcome.status.name).append("\"")72-                    outcome.error?.let { append(",\"error\":\"").append(it.replace("\"", "\\\"")) .append("\"") }73-                    append(",\"events\":[")74-                    transcript.forEachIndexed { index, event ->75-                        if (index > 0) append(',')76-                        append('\"').append(event).append('\"')77-                    }78-                    append("]}")79-                },87+            // A clean stop is only deterministic if our socket is still up when88+            // the peer writes its last frame, so hold it open until the peer89+            // goes away rather than exiting the instant the round ends.90+            if (config.drain) {91+                runCatching {92+                    raw.soTimeout = 2_00093+                    while (input.readLine() != null) Unit94+                }95+            }96+            transcriptFile.writeText(renderTranscript(outcome.status.name, outcome, vault, transcript))97+            assertEquals(98+                "Android process sync outcome",99+                config.expectStatus,100+                outcome.status,80101             )81-            assertEquals("Android process sync outcome", if (mismatch) SyncOutcomeStatus.ERRORED else SyncOutcomeStatus.COMPLETED, outcome.status)82102         }83103     }84104 105+    private fun renderTranscript(106+        status: String,107+        outcome: SyncOutcome?,108+        vault: ProcessVault,109+        transcript: List<String>,110+    ): String = buildString {111+        append("{\"status\":\"").append(status).append("\"")112+        outcome?.error?.let { append(",\"error\":\"").append(it.replace("\"", "\\\"")).append("\"") }113+        append(",\"entriesSent\":").append(outcome?.entriesSent ?: 0)114+        append(",\"entriesReceived\":").append(outcome?.entriesReceived ?: 0)115+        append(",\"applied\":").append(vault.appliedCount)116+        append(",\"staged\":").append(vault.stagedCount)117+        append(",\"events\":[")118+        transcript.forEachIndexed { index, event ->119+            if (index > 0) append(',')120+            append('"').append(event).append('"')121+        }122+        append("]}")123+    }124+85125     private fun configured(name: String): String? =86126         System.getenv(name) ?: System.getProperty(name.lowercase().replace('_', '.'))87127 @@ -99,32 +139,105 @@99139         is SyncMessage.Error -> "SYNC_ERROR"100140     }101141 102-    private class ProcessVault(private val id: String) : SyncVaultAdapter {103-        private val entries = linkedMapOf("$id-entry" to if (id == "android") 20L else 10L)104-        private val blobs = linkedMapOf("$id-entry" to if (id == "android") "android-frame" else "browser-frame")142+    /** Every knob the matrix can set, in one place. Defaults reproduce a plain round. */143+    private class HarnessConfig(144+        val id: String,145+        val parity: String,146+        val localVersion: Long,147+        val vaultId: String,148+        val manifestSupport: Boolean,149+        val entryCount: Int,150+        val expectStatus: SyncOutcomeStatus,151+        val drain: Boolean,152+        val mismatch: Boolean,153+        val locked: Boolean,154+        val stopAfter: String?,155+    ) {156+        companion object {157+            fun read(id: String, configured: (String) -> String?) = HarnessConfig(158+                id = id,159+                parity = configured("PEACH_SYNC_HARNESS_MTIME_PARITY") ?: "",160+                localVersion = configured("PEACH_SYNC_HARNESS_LOCAL_VERSION")?.toLongOrNull() ?: 7L,161+                vaultId = configured("PEACH_SYNC_HARNESS_VAULT_ID") ?: "cross-client-vault",162+                manifestSupport = configured("PEACH_SYNC_HARNESS_MANIFEST_VERSION") != "3",163+                entryCount = configured("PEACH_SYNC_HARNESS_ENTRY_COUNT")?.toIntOrNull() ?: 1,164+                expectStatus = SyncOutcomeStatus.valueOf(165+                    configured("PEACH_SYNC_HARNESS_EXPECT_STATUS") ?: "COMPLETED",166+                ),167+                drain = configured("PEACH_SYNC_HARNESS_DRAIN") == "1",168+                mismatch = configured("PEACH_SYNC_HARNESS_MISMATCH") == "message-order",169+                // A locked session may hold the transport key and stage170+                // ciphertext, but it never authors or applies a device manifest171+                // and never merges entries into the live vault (PB-26-112 C).172+                locked = configured("PEACH_SYNC_HARNESS_LOCKED") == "1",173+                stopAfter = configured("PEACH_SYNC_HARNESS_STOP_AFTER")?.takeIf(String::isNotEmpty),174+            )175+        }176+    }177+178+    private class ProcessVault(private val config: HarnessConfig) : SyncVaultAdapter {179+        private val id = config.id180+        // Entries are shared ids so a diff can actually flow. Parity decides181+        // which side is newer for a given index: the same parity on both sides182+        // means equal data versions, opposite parities means entries flow both183+        // ways. Must stay identical to the Browser endpoint's rule.184+        private val ids = (0 until config.entryCount).map { "shared-entry-$it" }185+        private val entries = linkedMapOf<String, Long>().apply {186+            ids.forEachIndexed { index, entryId -> put(entryId, mtimeFor(index)) }187+        }188+        private val blobs = linkedMapOf<String, String>().apply {189+            ids.forEachIndexed { index, entryId -> put(entryId, "$id-frame-${index % 8}") }190+        }191+192+        private fun mtimeFor(index: Int): Long {193+            if (config.parity.isEmpty()) return 10L194+            return if (index % 2 == config.parity.toInt()) 15L else 10L195+        }105196         private val tombstones = emptyMap<String, Long>()106197         private val manifest = SignedDeviceManifest(107198             DeviceManifestBody(DEVICE_MANIFEST_VERSION, id, 1_700_000_000_000L, emptyList()),108199             "11".repeat(64),109200         )110201 111-        override suspend fun computeVaultId() = "cross-client-vault"202+        /** Entries this side merged into its live vault. */203+        var appliedCount = 0204+            private set205+206+        /** Entries this side only staged because the vault is locked. */207+        var stagedCount = 0208+            private set209+210+        private val staged = linkedMapOf<String, String>()211+212+        override suspend fun computeVaultId() = config.vaultId112213         override suspend fun getOurDeviceId() = id113-        override suspend fun getLocalVersion() = 7L214+        override suspend fun getLocalVersion() = config.localVersion114215         override suspend fun buildEntryManifest() = entries.toMap()115216         override suspend fun buildTombstoneManifest() = tombstones217+116218         override suspend fun getEncryptedEntries(entryIds: List<String>) =117219             entryIds.mapNotNull { key -> blobs[key]?.let { key to it } }.toMap()220+118221         override suspend fun applyEntries(entries: Map<String, String>, remoteManifest: Map<String, Long>) {222+            if (config.locked) {223+                staged.putAll(entries)224+                stagedCount += entries.size225+                return226+            }227+            appliedCount += entries.size119228             this.entries.putAll(entries.mapValues { remoteManifest[it.key] ?: 0L })120229             blobs.putAll(entries)121230         }231+122232         override suspend fun applyTombstones(tombstones: Map<String, Long>) = Unit123-        override suspend fun buildOutgoingDeviceManifest() = manifest233+234+        override suspend fun buildOutgoingDeviceManifest() =235+            if (config.manifestSupport && !config.locked) manifest else null124236         override suspend fun applyIncomingDeviceManifest(125237             manifest: SignedDeviceManifest,126238             authenticatedRemoteStaticPublicKey: ByteArray,127239         ) = Unit128-        override val supportsDeviceManifest = true240+241+        override val supportsDeviceManifest = config.manifestSupport && !config.locked129242     }130243 }

view file