## Chunked explored persistence (DESIGN 4.4, 8; M3 slice 6, issue #21). Pins the on-disk chunk ## format (64x64 cells = 512 B, row-major LSB-first bits), the "a bitmap is a value, not a delta" ## write rule, the upsert (a rewrite replaces the chunk), the per-player keying, the startup restore ## and the cost of a mutation-scale write against the 4.3 commit budget. import std/[algorithm, monotimes, os, sets, strutils, tables, times, unittest] import db_connector/db_sqlite import db, explored, vision, world proc testScene(w = 4096.0, h = 4096.0, cell = 32): SceneRec = ## The v1 scene shape (migration step 3): 128x128 explored cells, so 2x2 chunks. SceneRec(id: 1, name: "Scene", w: w, h: h, tileSize: int(cell), cell: int(cell), gridSize: 0, visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1, nextWallId: 1) var tmpCount = 0 proc tmpDir(): string = inc tmpCount result = getTempDir() / "fffexplored-" & $getCurrentProcessId() & "-" & $tmpCount removeDir(result) createDir(result) proc openMigrated(dir: string): DbConn = ## A DB at this build's schema with two players (the FK target of `explored_chunk`). result = openDatabase(dir / "state.db") discard migrate(result) result.exec(sql"INSERT INTO player (id, name, role, colour, created_at) VALUES (1, 'GM', 'gm', '#111', 'x')") result.exec(sql"INSERT INTO player (id, name, role, colour, created_at) VALUES (2, 'Alice', 'player', '#222', 'x')") result.exec(sql"INSERT INTO player (id, name, role, colour, created_at) VALUES (3, 'Bob', 'player', '#333', 'x')") proc idxSet(sc: SceneRec, cells: openArray[(int, int)]): HashSet[int] = for (cx, cy) in cells: result.incl sc.cellIndex(cx, cy) suite "chunk format": test "the chunk bitmap layout is pinned": let sc = testScene() var ex = idxSet(sc, [(0, 0), (1, 0), (63, 0), (0, 1), (63, 63)]) let bits = encodeChunk(sc, ex, 0, 0) check bits.len == ChunkBytes check bits.len == 512 # row-major inside the chunk, least-significant bit first: the bytes below are the format. check bitOf(0, 0) == 0 check bitOf(1, 0) == 1 check bitOf(63, 0) == 63 check bitOf(0, 1) == 64 check bitOf(63, 63) == 4095 check bits[0] == 0b0000_0011'u8 check bits[7] == 0b1000_0000'u8 check bits[8] == 0b0000_0001'u8 check bits[511] == 0b1000_0000'u8 var setBits = 0 for b in bits: for k in 0 ..< 8: if (b and byte(1 shl k)) != 0: inc setBits check setBits == 5 check decodeChunk(sc, 0, 0, bits) == @[sc.cellIndex(0, 0), sc.cellIndex(1, 0), sc.cellIndex(63, 0), sc.cellIndex(0, 1), sc.cellIndex(63, 63)] test "one chunk covers 64x64 cells": let sc = testScene() check sc.cols == 128 and sc.rows == 128 check sc.chunkCols == 2 and sc.chunkRows == 2 check sc.chunkRows * ChunkCells >= sc.rows check chunkCoord(0) == 0 check chunkCoord(63) == 0 check chunkCoord(64) == 1 check chunkCoord(127) == 1 # the same local bit position in two different chunks is two different cells var ex = idxSet(sc, [(0, 0), (64, 0)]) let c00 = encodeChunk(sc, ex, 0, 0) let c10 = encodeChunk(sc, ex, 1, 0) check decodeChunk(sc, 0, 0, c00) == @[sc.cellIndex(0, 0)] check decodeChunk(sc, 1, 0, c10) == @[sc.cellIndex(64, 0)] test "a dirty chunk carries the whole chunk, not just the new cells": let sc = testScene() var ex = idxSet(sc, [(0, 0), (3, 2)]) let chunks = dirtyChunks(sc, 2, ex, @[(3, 2)]) check chunks.len == 1 check chunks[0].playerId == 2 check chunks[0].cx == 0 and chunks[0].cy == 0 check chunks[0].bits.len == ChunkBytes check decodeChunk(sc, 0, 0, chunks[0].bits) == @[sc.cellIndex(0, 0), sc.cellIndex(3, 2)] test "a chunk of a map edge keeps out-of-scene cells at zero": # 100 px at 32 px cells = 4 columns, 3 rows: one partial chunk, bits only inside the map let sc = testScene(w = 100, h = 70) check sc.cols == 4 and sc.rows == 3 var ex = idxSet(sc, [(3, 2)]) let bits = encodeChunk(sc, ex, 0, 0) check decodeChunk(sc, 0, 0, bits) == @[sc.cellIndex(3, 2)] suite "store": test "two chunks in one chunk row are both written": let d = tmpDir() let db = openMigrated(d) defer: close(db) removeDir(d) let sc = testScene() var ex = idxSet(sc, [(0, 0), (64, 5)]) let chunks = dirtyChunks(sc, 2, ex, @[(0, 0), (64, 5)]) check chunks.len == 2 check writeChunks(db, sc.id, chunks) == 2 let back = restore(db, sc) check back.hasKey(2) check back[2].explored == ex test "a second write to the same chunk replaces the bitmap": let d = tmpDir() let db = openMigrated(d) defer: close(db) removeDir(d) let sc = testScene() var ex = idxSet(sc, [(0, 0), (1, 0)]) discard writeChunks(db, sc.id, dirtyChunks(sc, 2, ex, @[(0, 0)])) ex.incl sc.cellIndex(5, 5) discard writeChunks(db, sc.id, dirtyChunks(sc, 2, ex, @[(5, 5)])) check chunkCount(db, sc.id) == 1 check restore(db, sc)[2].explored == ex # the stored row is one 512-byte bitmap, not a cell list let row = db.getAllRows(sql"SELECT typeof(bits), length(bits) FROM explored_chunk") check row.len == 1 check row[0][0] == "blob" check row[0][1] == "512" test "a chunk row of the wrong size is refused by the schema": let d = tmpDir() let db = openMigrated(d) defer: close(db) removeDir(d) var raised = false try: db.exec(sql"INSERT INTO explored_chunk (player_id, scene_id, cx, cy, bits) VALUES (2, 1, 0, 0, x'00')") except DbError: raised = true check raised suite "restore": test "restore: the stored cells come back exactly": let d = tmpDir() let db = openMigrated(d) defer: close(db) removeDir(d) let sc = testScene() var ex = idxSet(sc, [(0, 0), (1, 0), (63, 63), (64, 0), (127, 127)]) discard writeChunks(db, sc.id, dirtyChunks(sc, 2, ex, [(0, 0), (1, 0), (63, 63), (64, 0), (127, 127)])) let back = restore(db, sc) check back.len == 1 check back[2].explored == ex # polygons are never stored (8): a restored player has history and no sight until a refresh check back[2].polys.len == 0 check back[2].fresh.len == 0 # the RLE payload a resync would send covers the same cells, sorted by row then column let full = back[2].exploredFull(sc) check full.len == ex.len check full == @[(0, 0), (1, 0), (64, 0), (63, 63), (127, 127)] test "restore: two players' explored never mix": let d = tmpDir() let db = openMigrated(d) defer: close(db) removeDir(d) let sc = testScene() var alice = idxSet(sc, [(0, 0)]) var bob = idxSet(sc, [(127, 127)]) discard writeChunks(db, sc.id, dirtyChunks(sc, 2, alice, @[(0, 0)])) discard writeChunks(db, sc.id, dirtyChunks(sc, 3, bob, @[(127, 127)])) let back = restore(db, sc) check back.len == 2 check back[2].explored == alice check back[3].explored == bob check back[2].explored.len == 1 check back[3].explored.len == 1 test "restore: an empty store restores nothing and a removed player takes its chunks": let d = tmpDir() let db = openMigrated(d) defer: close(db) removeDir(d) let sc = testScene() check restore(db, sc).len == 0 var ex = idxSet(sc, [(0, 0)]) discard writeChunks(db, sc.id, dirtyChunks(sc, 2, ex, @[(0, 0)])) check chunkCount(db, sc.id) == 1 db.exec(sql"DELETE FROM player WHERE id = 2") # player.remove: the FK cascade takes the chunks check chunkCount(db, sc.id) == 0 suite "cost": test "a mutation-scale chunk write stays inside the 4.3 commit budget": let d = tmpDir() let db = openMigrated(d) defer: close(db) removeDir(d) let sc = testScene() var ex = idxSet(sc, [(10, 10), (11, 10), (12, 11)]) var samples: seq[float] let rounds = 200 for i in 0 ..< rounds: ex.incl sc.cellIndex(20 + i mod 40, 20) let chunks = dirtyChunks(sc, 2, ex, @[(20 + i mod 40, 20)]) let t0 = getMonoTime() db.withTransaction: discard writeChunks(db, sc.id, chunks) samples.add float((getMonoTime() - t0).inMicroseconds) / 1000.0 samples.sort() var total = 0.0 for s in samples: total += s let avg = total / float(samples.len) let p99 = samples[int(float(samples.len) * 0.99)] echo " chunk write: avg ", formatFloat(avg, ffDecimal, 3), " ms, p99 ", formatFloat(p99, ffDecimal, 3), " ms over ", rounds, " commits" # DESIGN 4.3: the commit is the tail of every mutation (worst ~20 ms accepted). One 512 B upsert # must not approach that; the bound is deliberately loose so a loaded machine cannot flake. check avg < 5.0 check p99 < 50.0