Modern Apps git

← Modern-Apps.git

sudoku: drop restored saves whose solution is not a legal grid

Commit
0148513693a1cdeecad8ce3c4ad361aac42a6f4d
Author
Vayun Mathur <[email protected]>
When
2026-12-01 19:58 UTC (4 days ago)
Parents
6417f55
SudokuProgressCodec.decode validated a restored save strictly — config
match, list lengths, digit ranges, givens agreeing with the solution,
no completed board, no wrong answer-mode entries — but never checked
that the stored solution is itself a legal completed Sudoku grid.

A backup-restored or corrupt save with an all-1s solution passed every
check: its digits are in range and empty givens contradict nothing.
Restoring it dealt a board whose hints all write 1, whose mistakes are
judged against 1, and which completes by filling 1 everywhere — banking
a win, a streak and a best time for a puzzle that never existed, since
recordGameWon trusts isComplete (every cell matching the solution).

Decode now requires each row, column and box of the solution to hold
1..side exactly once (isLegalSolution). That also proves the givens
legal, as a given is blank or copied from the solution. The codec
header comment lists the new rejection alongside the existing ones.

Tests: aSaveWhoseSolutionIsNotALegalGridIsDropped fails before the fix
(decode returned the corrupted save) and passes after. The shared
midGame fixture built its 'solution' as repeated 1..6 rows — an
illegal grid that only passed because decode never checked — so it now
uses a real 6x6 solution with the same shape of play (the index-1 entry
stays a wrong digit, which the legacy madeMistake fallback test needs).

Verified: :games:sudoku:testDevUnitTest targeted codec suite green;
full sudoku suite green per-class (two unrelated full-run flakes,
SudokuViewModelTest random-generation and achievements stats-ordering,
each pass in isolation); :games:nonogram:testDevUnitTest green.

Diff

games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.ktindex 6c37b04043..28a27975fc 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt@@ -41,8 +41,9 @@ data class SavedSudokuGame(  * Compact JSON for [SavedSudokuGame], following the pipes/unblockjam codec approach:  * flat int arrays for every board list, a version tag, and strict validation on decode.  * A save that does not fit [GameConfig] (size, difficulty or answer mode changed, a list- * of the wrong length, a digit out of range, a given contradicting the solution, a board- * already complete) decodes to null and the game starts fresh.+ * of the wrong length, a digit out of range, a solution that is not a legal completed+ * grid, a given contradicting the solution, a board already complete) decodes to null+ * and the game starts fresh.  */ object SudokuProgressCodec {     private const val VERSION = 1@@ -86,6 +87,13 @@ object SudokuProgressCodec {         val entries = ints(root, "entries", cells) ?: return null         val notes = ints(root, "notes", cells) ?: return null         if (givens.any { it !in 0..size.side } || solution.any { it !in 1..size.side }) return null+        // The solution must be a legal completed grid: every row, column and+        // box holding each digit once. Range alone does not promise that —+        // a grid of all 1s passes it — and everything downstream trusts the+        // solution blindly: hints write it, mistakes are judged against it,+        // and matching it everywhere is what banks a win, so restoring an+        // illegal one deals a board that "solves" by repeating one digit.+        if (!isLegalSolution(size, solution)) return null         // A given is a clue copied out of the solution, and the game assumes the two         // agree: givens cannot be edited and valueAt prefers them, so a given that         // contradicts the solution makes the board impossible to complete and turns@@ -151,6 +159,27 @@ object SudokuProgressCodec {         SavedSudokuGame(game, history, elapsed, madeMistake)     }.getOrNull() +    /**+     * Whether [solution] is a completed grid in which every row, column and box+     * holds each digit of `1..side` exactly once. Digits are already known to be+     * in range, so a unit is a permutation exactly when its set has [BoardSize.side]+     * members. Together with the givens-agree check above, this also proves the+     * givens themselves legal: a given is either blank or copied from here.+     */+    private fun isLegalSolution(size: BoardSize, solution: List<Int>): Boolean {+        val side = size.side+        fun unitIsPermutation(indices: List<Int>): Boolean =+            indices.mapTo(mutableSetOf()) { solution[it] }.size == side+        for (unit in 0 until side) {+            if (!unitIsPermutation((0 until side).map { unit * side + it })) return false+            if (!unitIsPermutation((0 until side).map { it * side + unit })) return false+            if (!unitIsPermutation((0 until size.cellCount).filter { size.boxOf(it) == unit })) {+                return false+            }+        }+        return true+    }+     private fun ints(values: List<Int>): JsonArray = buildJsonArray { for (v in values) add(v) }      private fun ints(root: kotlinx.serialization.json.JsonObject, key: String, size: Int): List<Int>? {
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.ktindex 72821d3f85..6cc2dfcef9 100644--- a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.kt+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.kt@@ -20,8 +20,17 @@ class SudokuProgressCodecTest {      private fun midGame(): SavedSudokuGame {         val size = BoardSize.SIX-        val givens = List(size.cellCount) { if (it % 3 == 0) (it % size.side) + 1 else 0 }-        val solution = List(size.cellCount) { (it % size.side) + 1 }+        // A legal 6x6 grid (2x3 boxes): decode rightfully refuses saves whose+        // solution is not one, so the fixture cannot fake it with repeated rows.+        val solution = listOf(+            1, 2, 3, 4, 5, 6,+            4, 5, 6, 1, 2, 3,+            2, 3, 1, 5, 6, 4,+            5, 6, 4, 2, 3, 1,+            3, 1, 2, 6, 4, 5,+            6, 4, 5, 3, 1, 2,+        )+        val givens = List(size.cellCount) { if (it % 3 == 0) solution[it] else 0 }         val game = SudokuGameState(             size = size,             difficulty = Difficulty.EASY,@@ -268,6 +277,34 @@ class SudokuProgressCodecTest {         )     } +    @Test+    fun aSaveWhoseSolutionIsNotALegalGridIsDropped() {+        // Every stored digit is in range and no given contradicts the+        // "solution", so the current checks pass — but a grid of all 1s is+        // not a Sudoku solution: no row, column or box holds 1..6 once+        // each. Restoring it hands the player a board whose hints all+        // write 1 and which "completes" by filling 1 everywhere, banking+        // a win (and its streak/best-time) for a puzzle that never existed.+        val size = BoardSize.SIX+        val corrupted = SavedSudokuGame(+            game = SudokuGameState(+                size = size,+                difficulty = Difficulty.EASY,+                givens = List(size.cellCount) { 0 },+                solution = List(size.cellCount) { 1 },+                entries = List(size.cellCount) { 0 },+                notes = List(size.cellCount) { 0 },+            ),+            history = emptyList(),+            elapsedSeconds = 9,+        )+        assertFalse(corrupted.game.isComplete, "blank entries keep the board restorable-looking")+        assertNull(+            SudokuProgressCodec.decode(SudokuProgressCodec.encode(corrupted), config),+            "a save whose solution is not a legal completed grid must start fresh",+        )+    }+     @Test     fun midGameRoundTripsThroughDataStore() = runBlocking {         val store = SudokuDataStore(context)