Modern Apps git

← Modern-Apps.git

voxels: unsent world ops persist and replay instead of dropping

Commit
ee6923eda8fba29b0006caf9af6a2fc9bbe02b70
Author
Vayun Mathur <[email protected]>
When
2026-11-21 12:20 UTC (14 days ago)
Parents
e63277b
Multiplayer sent world ops fire-and-forget: a dead socket
silently dropped every edit. Outbound ops now go through a
persisted queue ported from Office's pending-ops pattern -
the merged batch is written to DataStore before any send,
cleared only on success, replayed oldest-first on reconnect,
exact duplicates deduped. The persisted unit is the
already-signed op string, replayed verbatim, so the wire
format and relay view (ciphertext only) are unchanged. The
HUD shows an unsent-changes chip while ops are pending.
Player presence stays ephemeral by design.

Verified: voxels suite passes incl. persist-before-send,
failure-keeps-ops, ordering and HUD tests.

Diff

games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.ktindex f1325ccb28..7e6dfa70a9 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt@@ -206,6 +206,7 @@ class MainActivity : ComponentActivity() {                 // Online multiplayer HUD state.                 var netStatus by remember { mutableStateOf<NetStatus>(NetStatus.Connecting) }                 var peersJson by remember { mutableStateOf("[]") }+                var unsentCount by remember { mutableStateOf(0) }                 LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson(); smeltingJson = VoxelsNative.getSmeltingJson(); blessingCatalogJson = VoxelsNative.getBlessingCatalogJson(); cutsJson = VoxelsNative.getCutsJson() } catch (_: Exception) {} }                 // World loading runs on the engine thread; poll it for the loading overlay. The phase                 // can drop back to meshing if the renderer ever has to be rebuilt.@@ -385,6 +386,7 @@ class MainActivity : ComponentActivity() {                         params = MultiplayerPump.Params(sharedWorldId, worldKeyB64, ownerDevice, netRole, worldName),                         onStatus = { netStatus = it },                         onPeers = { peersJson = it },+                        onPending = { unsentCount = it },                     )                 } @@ -591,7 +593,7 @@ class MainActivity : ComponentActivity() {                                 Modifier.align(Alignment.TopEnd).padding(top = 36.dp, end = 12.dp),                                 horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(6.dp),                             ) {-                                OnlineHud(status = netStatus, peersJson = peersJson, ownerDevice = ownerDevice, isHost = netRole == 1)+                                OnlineHud(status = netStatus, peersJson = peersJson, ownerDevice = ownerDevice, isHost = netRole == 1, unsentCount = unsentCount)                                 joinRequests.firstOrNull()?.let { req ->                                     JoinRequestChip(                                         player = req.name.ifBlank { req.requesterId.take(8) },
games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.ktindex f836b9cc30..43fa6eaadb 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt@@ -8,6 +8,8 @@ import com.vayunmathur.games.voxels.domain.NetFailure import com.vayunmathur.games.voxels.domain.NetStatus import com.vayunmathur.games.voxels.domain.netStatusOf import com.vayunmathur.games.voxels.util.VoxelsNative+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope@@ -54,6 +56,16 @@ class MultiplayerPump private constructor(     private val roster: MutableSet<String> = Collections.synchronizedSet(HashSet())     private val bundles = ConcurrentHashMap<String, ByteArray>() +    // Persisted outbound world ops (see PendingOps.kt). run() swaps in the DataStore-backed+    // store before the loop starts; the in-memory default keeps reflective/unit-constructed+    // pumps functional. liveSender is a seam so tests can drive ack/failure without a socket.+    internal var pendingStore: PendingOpsStore = InMemoryPendingOpsStore()+    internal var onPendingCount: (Int) -> Unit = {}+    internal var liveSender: suspend (List<String>) -> Boolean = { ops ->+        VoxelsSync.liveAppend(channel, key, ops)+    }+    private val outboundQueue by lazy { PendingOpQueue(pendingStore, liveSender) }+     /** Entry point and session setup. */     companion object {         private const val ROLE_HOST = 1@@ -63,7 +75,13 @@ class MultiplayerPump private constructor(         private const val ROSTER_EVERY = 125          /** Runs the pump until the calling coroutine is cancelled. */-        suspend fun run(context: Context, params: Params, onStatus: (NetStatus) -> Unit, onPeers: (String) -> Unit) {+        suspend fun run(+            context: Context,+            params: Params,+            onStatus: (NetStatus) -> Unit,+            onPeers: (String) -> Unit,+            onPending: (Int) -> Unit = {},+        ) {             onStatus(NetStatus.Connecting)             if (!runCatching { VoxelsSync.init(context) }.getOrDefault(false)) {                 onStatus(NetStatus.Failed(NetFailure.SERVER_UNREACHABLE)); return@@ -76,7 +94,10 @@ class MultiplayerPump private constructor(             val ownerBundle = if (params.role == ROLE_HOST) VoxelsSync.publicBundle             else runCatching { VoxelsSync.getKey(params.ownerDevice) }.getOrNull()             if (ownerBundle == null) { onStatus(NetStatus.Failed(NetFailure.HOST_UNVERIFIED)); return }-            MultiplayerPump(params, myId, key, ownerBundle).loop(onStatus, onPeers)+            MultiplayerPump(params, myId, key, ownerBundle).also { pump ->+                pump.pendingStore = DataStorePendingOpsStore(DataStoreUtils.getInstance(context), params.worldId)+                pump.onPendingCount = onPending+            }.loop(onStatus, onPeers)         }     } @@ -163,6 +184,10 @@ class MultiplayerPump private constructor(     }      // Ships everything the engine queued: transforms as presence, the rest as signed world ops.+    // World ops go through the persisted PendingOpQueue: signed ops are saved before the send+    // attempt and cleared only when liveAppend succeeds, so a down socket no longer drains-and-+    // drops them — the next tick (e.g. after reconnect) replays them in order. Presence stays+    // ephemeral/best-effort: a dropped transform is superseded by the next one.     private suspend fun flushOutbound() {         val out = try { VoxelsNative.netDrainOutbound() } catch (_: Exception) { "[]" }         try {@@ -176,7 +201,10 @@ class MultiplayerPump private constructor(                     ops.add(signed(o.toString()))                 }             }-            if (ops.isNotEmpty()) VoxelsSync.liveAppend(channel, key, ops)+            // Always flush (even with no new ops) so persisted ops replay on reconnect.+            onPendingCount(outboundQueue.enqueueAndFlush(ops))+        } catch (e: CancellationException) {+            throw e         } catch (_: Exception) {}     } @@ -185,6 +213,8 @@ class MultiplayerPump private constructor(         VoxelsSync.publicBundle.let { bundles[myId] = it; bundles[p.ownerDevice] = it }         if (isHost) refreshRoster()         val everConnected = AtomicBoolean(false)+        // Surface ops persisted by a previous pump/process before the first flush replays them.+        onPendingCount(outboundQueue.pendingCount())         startLive(this) { everConnected.set(true) }         var tick = 0         while (isActive) {
games/voxels/src/main/java/com/vayunmathur/games/voxels/network/PendingOps.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/PendingOps.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/PendingOps.ktnew file mode 100644index 0000000000..32718b9f12--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/PendingOps.kt@@ -0,0 +1,112 @@+package com.vayunmathur.games.voxels.network++import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.json.Json++/**+ * Persistence for outbound world ops that have been drained from the engine but not yet+ * acked by the relay — the voxels port of Office's persisted pending-ops pattern+ * (`OfficeViewModelSyncB.loadPendingOps`/`savePendingOps`, `crdtPending:<docId>`).+ *+ * Why this exists: the engine's outbound queue is drain-on-read, so once+ * [com.vayunmathur.games.voxels.util.VoxelsNative.netDrainOutbound] hands an op to Kotlin the+ * engine has forgotten it. Persisting the signed op strings *before* attempting the send,+ * and clearing them only after a successful append, means a dead socket (or a process death)+ * replays them verbatim on the next flush instead of silently dropping world edits.+ *+ * The persisted unit is the already-signed op string (`SignedOp{author,sig,ops}` JSON) —+ * exactly the string [MultiplayerPump] used to hand to `VoxelsSync.liveAppend` — so the+ * on-wire format (per-op AES-256-GCM, Base64, `AppendMsg` on `world:<id>`) is unchanged.+ * Ephemeral `PlayerTransform` presence is deliberately never persisted: it is superseded by+ * the next transform and was never part of the world log.+ */+interface PendingOpsStore {+    suspend fun load(): List<String>+    suspend fun save(ops: List<String>)+}++/** Process-local fallback (also handy in tests); production uses [DataStorePendingOpsStore]. */+class InMemoryPendingOpsStore : PendingOpsStore {+    private var ops: List<String> = emptyList()+    override suspend fun load(): List<String> = ops+    override suspend fun save(ops: List<String>) {+        this.ops = ops.toList()+    }+}++/**+ * DataStore-backed store, one key per world (`voxelsPending:<worldId>`), holding a JSON+ * list of signed-op strings in send order. Corrupt/absent data reads as empty, matching+ * Office's tolerant `loadPendingOps`.+ */+class DataStorePendingOpsStore(+    private val ds: DataStoreUtils,+    worldId: String,+) : PendingOpsStore {+    private val pendingKey = "voxelsPending:$worldId"++    override suspend fun load(): List<String> =+        ds.getStringAwait(pendingKey)+            ?.let { runCatching { JSON.decodeFromString<List<String>>(it) }.getOrNull() }+            ?: emptyList()++    override suspend fun save(ops: List<String>) {+        ds.setString(pendingKey, JSON.encodeToString(ops))+    }++    private companion object {+        val JSON = Json { ignoreUnknownKeys = true }+    }+}++/**+ * Ordered, persisted outbound queue for signed world ops.+ *+ * [enqueueAndFlush] merges previously-unacked ops (oldest first) with newly drained ones,+ * persists the merged list *before* sending, sends the whole batch in one [send] call+ * (one `liveAppend`, as before), and clears the persisted list only when [send] reports+ * success. A failed send keeps the persisted list untouched, so the next flush — e.g. the+ * pump's next 80 ms tick after the WebSocket reconnects — replays the same ops in order.+ *+ * Exact duplicate signed strings are dropped on merge (Office does the same with+ * `signed !in pending`): a signature makes each drained op unique in practice, so this+ * only guards against re-enqueueing an op that is already awaiting an ack.+ */+class PendingOpQueue(+    private val store: PendingOpsStore,+    private val send: suspend (List<String>) -> Boolean,+) {+    private val mutex = Mutex()++    /** Number of persisted, not-yet-acked ops — what the HUD surfaces as "N unsent changes". */+    suspend fun pendingCount(): Int = mutex.withLock { store.load().size }++    /** Replays persisted ops without adding new ones (reconnect path). Returns remaining count. */+    suspend fun flushPending(): Int = enqueueAndFlush(emptyList())++    /**+     * Persists [newOps] behind any unacked ops, then tries to send the merged batch.+     * Returns the number of ops still unsent after the attempt (0 on success).+     */+    suspend fun enqueueAndFlush(newOps: List<String>): Int = mutex.withLock {+        val pending = store.load()+        val merged = pending + newOps.filter { it !in pending }+        if (merged.isEmpty()) return@withLock 0+        // Persist BEFORE send: from here on a crash/socket drop cannot lose these ops.+        if (merged != pending) store.save(merged)+        val sent = try {+            send(merged)+        } catch (e: CancellationException) {+            throw e+        } catch (_: Exception) {+            false+        }+        if (!sent) return@withLock merged.size+        // Acked: only now may the persisted ops be dropped.+        store.save(emptyList())+        0+    }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.ktindex 41d6020d38..e86b1baa31 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/OnlineHud.kt@@ -41,7 +41,14 @@ internal fun peerIds(peersJson: String): Set<String> = runCatching {  * (Connecting / Reconnecting / why it failed) and short-lived "X joined" / "X left" notices.  */ @Composable-fun OnlineHud(status: NetStatus, peersJson: String, ownerDevice: String, isHost: Boolean, modifier: Modifier = Modifier) {+fun OnlineHud(+    status: NetStatus,+    peersJson: String,+    ownerDevice: String,+    isHost: Boolean,+    unsentCount: Int = 0,+    modifier: Modifier = Modifier,+) {     val peers = remember(peersJson) { peerIds(peersJson) }     val notices = remember { mutableStateListOf<Notice>() }     val previous = remember { mutableStateOf<Set<String>?>(null) }@@ -60,6 +67,9 @@ fun OnlineHud(status: NetStatus, peersJson: String, ownerDevice: String, isHost:             val here = ownerDevice in peers             Chip(stringResource(if (here) R.string.host_here else R.string.host_away), if (here) Color(0x992E7D32) else Color(0x99000000))         }+        if (unsentCount > 0) {+            Chip(pluralStringResource(R.plurals.unsent_changes, unsentCount, unsentCount), Color(0xCCB26A00))+        }         when (status) {             NetStatus.Connected -> Unit             NetStatus.Connecting -> Chip(stringResource(R.string.online_connecting), Color(0x99000000))
games/voxels/src/main/res/values/strings.xml
diff --git a/games/voxels/src/main/res/values/strings.xml b/games/voxels/src/main/res/values/strings.xmlindex 68fecbb334..a907ea09bf 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -117,6 +117,11 @@     <string name="online_connecting">Connecting…</string>     <!-- Online HUD for joiners: the host is (not) connected right now. Sentence fragment -->     <string name="host_here">Host is here</string>+    <!-- Online HUD: world changes persisted locally but not yet sent to the relay. -->+    <plurals name="unsent_changes">+        <item quantity="one">%1$d unsent change</item>+        <item quantity="other">%1$d unsent changes</item>+    </plurals>     <string name="host_away">Host isn\'t connected</string>     <!-- Online HUD notices; %1$s = player name. Sentence fragment -->     <!-- In-game host prompt; %1$s = requesting player. Sentence -->
games/voxels/src/test/java/com/vayunmathur/games/voxels/network/PendingOpsTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/PendingOpsTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/PendingOpsTest.ktnew file mode 100644index 0000000000..bf8e67d33f--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/PendingOpsTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.games.voxels.network++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json++/**+ * Persisted pending-ops for [MultiplayerPump.flushOutbound] (port of Office's+ * `crdtPending:<docId>` pattern): ops are persisted before send, kept on failure,+ * cleared only on ack, and replayed in order. The queue under test is the pump's+ * outbound engine; recreating it over the same store is pump recreation.+ */+class PendingOpsTest {+    /** Store whose backing is a single persisted string, like the DataStore value. */+    private class PersistingStore(var backing: String? = null) : PendingOpsStore {+        override suspend fun load(): List<String> =+            backing?.let { runCatching { Json.decodeFromString<List<String>>(it) }.getOrNull() } ?: emptyList()++        override suspend fun save(ops: List<String>) {+            backing = Json.encodeToString(ops)+        }+    }++    @Test fun opsPersistedBeforeSendSurvivePumpRecreation() = runBlocking {+        val store = PersistingStore()+        var atSendTime: List<String>? = null+        val firstPump = PendingOpQueue(store) { ops ->+            atSendTime = store.load() // what was persisted when the send was attempted+            false // socket down+        }+        assertEquals(2, firstPump.enqueueAndFlush(listOf("op-a", "op-b")))+        // Persisted BEFORE the (failed) send was attempted.+        assertEquals(listOf("op-a", "op-b"), atSendTime)+        assertEquals(listOf("op-a", "op-b"), store.load())++        // Recreated pump (new queue, same persisted store) replays in order, then clears.+        val replayed = mutableListOf<List<String>>()+        val secondPump = PendingOpQueue(store) { ops -> replayed += ops; true }+        assertEquals(2, secondPump.pendingCount())+        assertEquals(0, secondPump.flushPending())+        assertEquals(listOf(listOf("op-a", "op-b")), replayed)+        assertTrue(store.load().isEmpty())+    }++    @Test fun failedSendKeepsOpsAndSuccessClears() = runBlocking {+        val store = PersistingStore()+        var online = false+        val sent = mutableListOf<List<String>>()+        val queue = PendingOpQueue(store) { ops -> if (online) { sent += ops; true } else false }+        assertEquals(1, queue.enqueueAndFlush(listOf("op-1")))+        assertEquals(listOf("op-1"), store.load())+        assertTrue(sent.isEmpty())+        online = true+        assertEquals(0, queue.flushPending())+        assertEquals(listOf(listOf("op-1")), sent)+        assertTrue(store.load().isEmpty())+        assertEquals(0, queue.pendingCount())+    }++    @Test fun throwingSendKeepsOps() = runBlocking {+        val store = PersistingStore()+        val queue = PendingOpQueue(store) { throw IllegalStateException("socket closed") }+        assertEquals(1, queue.enqueueAndFlush(listOf("op-x")))+        assertEquals(listOf("op-x"), store.load())+    }++    @Test fun orderPreservedAcrossFailedBatches() = runBlocking {+        val store = PersistingStore()+        var online = false+        val sent = mutableListOf<String>()+        val queue = PendingOpQueue(store) { ops -> if (online) { sent += ops; true } else false }+        queue.enqueueAndFlush(listOf("op-1", "op-2"))+        queue.enqueueAndFlush(listOf("op-3"))+        assertEquals(listOf("op-1", "op-2", "op-3"), store.load())+        online = true+        assertEquals(0, queue.flushPending())+        assertEquals(listOf("op-1", "op-2", "op-3"), sent)+    }++    @Test fun alreadyPendingOpIsNotDuplicated() = runBlocking {+        val store = PersistingStore()+        val queue = PendingOpQueue(store) { false }+        queue.enqueueAndFlush(listOf("op-1"))+        queue.enqueueAndFlush(listOf("op-1", "op-2"))+        assertEquals(listOf("op-1", "op-2"), store.load())+    }++    @Test fun emptyFlushNeverSends() = runBlocking {+        var calls = 0+        val queue = PendingOpQueue(PersistingStore()) { calls++; true }+        assertEquals(0, queue.enqueueAndFlush(emptyList()))+        assertEquals(0, queue.flushPending())+        assertEquals(0, calls)+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.ktindex fd3cb1416b..7fdec37e0c 100644--- a/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.kt+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/ui/OnlineHudTest.kt@@ -31,6 +31,18 @@ class OnlineHudTest {         rule.onNodeWithText("2 players online").assertExists()     } +    @Test fun `unsent changes are visible only when there are any`() {+        rule.setContent {+            OnlineHud(NetStatus.Reconnecting, "[]", ownerDevice = "host", isHost = false, unsentCount = 3)+        }+        rule.onNodeWithText("3 unsent changes").assertExists()+    }++    @Test fun `no unsent indicator when everything is sent`() {+        rule.setContent { OnlineHud(NetStatus.Connected, "[]", ownerDevice = "host", isHost = false) }+        rule.onNodeWithText("0 unsent changes").assertDoesNotExist()+    }+     @Test fun `failures say why`() {         rule.setContent { OnlineHud(NetStatus.Failed(NetFailure.BAD_INVITE), "[]", ownerDevice = "h", isHost = false) }         rule.onNodeWithText("This world's invite is damaged — ask the host to invite you again.").assertExists()