Modern Apps git

← Modern-Apps.git

games-logicgate: fix cross-level draft loss in CircuitStore debounced saves

Commit
eec32440659edd53f9c4c56038f538842a3911c7
Author
Vayun Mathur <[email protected]>
When
2026-11-08 02:43 UTC (28 days ago)
Parents
04f6998
CircuitStore debounced each save through a single shared pending Job, so calling save() for level B while level A's write was still inside its 400 ms debounce window cancelled A's job and A's draft was silently lost. The same single slot also let a debounced save overwrite a rewriteAll remap with a stale circuit, and load() could not see drafts before they flushed.

Root cause is app-side, not in shared code: DataStoreUtils.updateString is an atomic read-modify-write (single dataStore.edit, which serializes concurrent edits), so the loss came purely from CircuitStore cancelling the in-flight job. Fix stays app-side.

The store now keeps one pending draft per level in a latest map guarded by a lock. save() only replaces that level's slot and re-arms a single debounced flush that drains and writes every pending draft atomically. load() overlays the pending drafts so it always returns the newest state. rewriteAll() cancels any debounce, joins an already-writing flush, drains the pending drafts, and applies the transform to saved plus pending drafts in one atomic update, so a stale save can never clobber a rewrite. Joining a cancelled flush rethrows its CancellationException, which belongs to the flush and must not cancel the caller, so the join swallows it (re-checking our own coroutine with ensureActive). The flush body runs under NonCancellable past the snapshot point so a racing cancel cannot drop drafts it already drained.

Adds two regression tests: back-to-back saves of two levels both reach the DataStore (read through a fresh store so the in-memory overlay cannot mask a lost flush), and a rewriteAll issued inside the debounce window keeps the rewrite instead of throwing.

Verified with ./gradlew :games:logicgate:testDevUnitTest (BUILD SUCCESSFUL, all StoresTest cases pass).

Diff

games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.ktindex 11af08f1e2..a84c2ab68c 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt@@ -12,12 +12,17 @@ import com.vayunmathur.games.logicgate.domain.model.PinSide import com.vayunmathur.games.logicgate.domain.model.Point import com.vayunmathur.games.logicgate.domain.model.Wire import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job+import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay+import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlin.coroutines.coroutineContext import kotlinx.serialization.SerializationException import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json@@ -49,28 +54,62 @@ data class CircuitDto(val nodes: List<NodeDto>, val wires: List<WireDto>, val ne  * Per-level circuit drafts, as one JSON map in the shared DataStore. Saves are debounced on the  * store's own scope rather than the ViewModel's, so the last edit still lands after the screen  * closes.+ *+ * Unsaved drafts wait in [latest], one slot per level: a save for one level must never cancel+ * another level's draft, [load] must see the newest state even before it is flushed, and+ * [rewriteAll] must transform unsaved drafts too, so a debounced save can never overwrite a+ * rewrite with a stale circuit.  */ class CircuitStore(context: Context, dispatcher: CoroutineDispatcher) {     private val ds = DataStoreUtils.getInstance(context)     private val scope = CoroutineScope(SupervisorJob() + dispatcher)     private val json = Json { ignoreUnknownKeys = true }-    private var pending: Job? = null+    private val lock = Any()+    private val latest = mutableMapOf<String, CircuitDto>()+    private var flush: Job? = null -    suspend fun load(levelId: String): Circuit? = decode(ds.getStringAwait(KEY))[levelId]?.toDomain()+    suspend fun load(levelId: String): Circuit? =+        synchronized(lock) { latest[levelId] }?.toDomain()+            ?: decode(ds.getStringAwait(KEY))[levelId]?.toDomain()      fun save(levelId: String, circuit: Circuit) {-        pending?.cancel()-        pending = scope.launch {+        synchronized(lock) { latest[levelId] = circuit.toDto() }+        flush?.cancel()+        flush = scope.launch {             delay(SAVE_DEBOUNCE_MS)-            val dto = circuit.toDto()-            ds.updateString(KEY) { old -> json.encodeToString(decode(old) + (levelId to dto)) }+            writePending()         }     }      /** Applies [transform] to every saved draft, e.g. to follow a component whose pins moved. */     suspend fun rewriteAll(transform: (Circuit) -> Circuit) {+        // Let a flush that already started writing finish first, so its drafts land before the+        // rewrite reads them; a flush still inside its debounce is cancelled and drained below.+        // Joining a cancelled flush rethrows its CancellationException, which belongs to the+        // flush and must not cancel this coroutine: swallow it unless we are cancelled ourselves.+        flush?.cancel()+        try {+            flush?.join()+        } catch (_: CancellationException) {+            coroutineContext.ensureActive()+        }+        val snapshot: Map<String, CircuitDto> = synchronized(lock) {+            latest.toMap().also { latest.clear() }+        }         ds.updateString(KEY) { old ->-            json.encodeToString(decode(old).mapValues { (_, dto) -> transform(dto.toDomain()).toDto() })+            val merged = decode(old) + snapshot+            json.encodeToString(merged.mapValues { (_, dto) -> transform(dto.toDomain()).toDto() })+        }+    }++    private suspend fun writePending() {+        val snapshot: Map<String, CircuitDto> = synchronized(lock) {+            if (latest.isEmpty()) return+            latest.toMap().also { latest.clear() }+        }+        // Past this point the snapshot lives only in this job: a cancel must not drop it.+        withContext(NonCancellable) {+            ds.updateString(KEY) { old -> json.encodeToString(decode(old) + snapshot) }         }     } 
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/data/StoresTest.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/data/StoresTest.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/data/StoresTest.ktindex d7eb04d31d..d5dab21e8c 100644--- a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/data/StoresTest.kt+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/data/StoresTest.kt@@ -37,6 +37,39 @@ class StoresTest {         assertNull(store.load("and"))     } +    @Test fun `back to back saves keep both levels drafts`() = runBlocking {+        val store = CircuitStore(ctx, Dispatchers.IO)+        val a = ReferenceCircuits.build("not")+        val b = ReferenceCircuits.build("and")+        store.save("race-a", a)+        store.save("race-b", b)+        // Before the fix the second save cancelled the first level's debounced write, so the+        // "race-a" draft never reached the DataStore and this timed out. Read through a fresh+        // store so the in-memory overlay cannot mask a lost flush.+        await("both drafts saved") {+            val fresh = CircuitStore(ctx, Dispatchers.IO)+            runBlocking { fresh.load("race-a") } != null &&+                runBlocking { fresh.load("race-b") } != null+        }+        val fresh = CircuitStore(ctx, Dispatchers.IO)+        assertEquals(a.nodes.size, fresh.load("race-a")!!.nodes.size)+        assertEquals(b.nodes.size, fresh.load("race-b")!!.nodes.size)+    }++    @Test fun `rewrite during debounce keeps the rewrite`() = runBlocking {+        val store = CircuitStore(ctx, Dispatchers.IO)+        val circuit = ReferenceCircuits.build("not")+        store.save("race-rw", circuit)+        // The save is still inside its debounce here, so the rewrite must absorb the pending+        // draft instead of throwing the cancelled flush's CancellationException into the caller.+        store.rewriteAll { it.copy(nextId = it.nextId + 100) }+        val fresh = CircuitStore(ctx, Dispatchers.IO)+        await("rewrite landed") {+            runBlocking { fresh.load("race-rw") }?.nextId == circuit.nextId + 100+        }+        assertEquals(circuit.nextId + 100, fresh.load("race-rw")!!.nextId)+    }+     @Test fun `component store round trips custom chips`() = runBlocking {         val store = ComponentStore(ctx, Dispatchers.IO)         store.save(emptyList())