server: the chunked explored store (#21)

Migration step 5 creates explored_chunk: one 512-byte bitmap per (player, scene, 64x64-cell
chunk), both FKs cascading. server/explored.nim owns the format (row-major, LSB-first bits),
dirty-chunk detection, the upsert and the startup restore. tests/texplored.nim pins the layout,
the whole-chunk encoding, the upsert replacement, the per-player keying, the restore and the
write cost (0.015 ms avg / 0.035 ms p99); tests/tdb.nim covers step 5 and a schema-4 fixture.
This commit is contained in:
2026-11-15 09:58:16 +01:00
parent 5d38e92c03
commit 22014a36dc
4 changed files with 453 additions and 7 deletions
+27 -1
View File
@@ -12,7 +12,11 @@
## `scene.next_wall_id`, which never decreases (#3 FIXED).
## Step 4 ("tokens", M3 slice 5 / #20) creates `entity` for the map figures (DESIGN 4.4, 8). The
## character link, the name-reveal flags and the three property buckets are slices 7-8 (#22, #23) and
## are not columns yet; `entity_status` and `explored_chunk` arrive with slice 7 and slice 6.
## are not columns yet; `entity_status` arrives with slice 7.
## Step 5 ("explored", M3 slice 6 / #21) creates `explored_chunk`, the chunked explored bitmaps
## (DESIGN 4.4, 8): one row per (player, scene, 64x64-cell chunk), 512 B per row, LSB-first
## row-major bits (server/explored.nim). Both FKs cascade, so removing a player or a scene takes its
## explored cells with it.
## One connection, used under the server's global lock (4.3); this module does no locking itself.
import std/[strutils, times]
import db_connector/db_sqlite
@@ -108,6 +112,15 @@ CREATE TABLE entity (
vision_radius REAL, -- NULL = scene vision_radius_default (Q7)
flags TEXT NOT NULL DEFAULT '{}', -- JSON object; the `vision` flag lives here (8)
created_at TEXT NOT NULL
)"""]),
Migration(version: 5, name: "explored", stmts: @["""
CREATE TABLE explored_chunk (
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE,
cx INTEGER NOT NULL, -- chunk coordinate: cell div 64 (server/explored.nim)
cy INTEGER NOT NULL,
bits BLOB NOT NULL CHECK (length(bits) = 512), -- 64x64 cells, LSB-first row-major
PRIMARY KEY (player_id, scene_id, cx, cy)
)"""]),
]
LatestVersion* = migrations[^1].version
@@ -123,6 +136,19 @@ proc openDatabase*(path: string): DbConn =
proc schemaVersion*(db: DbConn): int =
parseInt(db.getValue(sql"PRAGMA user_version"))
template withTransaction*(db: DbConn, body: untyped) =
## One explicit transaction (DESIGN 4.2 step 6): COMMIT on success, ROLLBACK and re-raise on any
## failure. A template rather than a proc taking a closure: call sites run under the global lock
## inside `{.gcsafe.}` handlers, where a closure would need its own gcsafe proof.
db.exec(sql"BEGIN")
try:
body
db.exec(sql"COMMIT")
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard # the original error is the one worth reporting
raise
proc appliedMigrations*(db: DbConn): seq[MigrationRow] =
for r in db.getAllRows(sql"SELECT version, name FROM schema_migration ORDER BY version"):
result.add (version: parseInt(r[0]), name: r[1])
+150
View File
@@ -0,0 +1,150 @@
## Chunked explored persistence (DESIGN 4.4, 8; M3 slice 6, issue #21). The in-memory explored set
## lives in vision.PlayerVision; this module owns its shape on disk and nothing else: no locking, no
## wire shapes, no mutations.
##
## Format [FIXED (owner-delegated), #21]: one row per (player, scene, chunk) in `explored_chunk`
## (migration step 5). A chunk is 64x64 cells = 512 B, exactly DESIGN 4.4's size: the v1 scene is
## 4096 px / 32 px = 128x128 cells, so 2x2 chunk rows hold a whole map, and a 16384 px map is
## 8x8. Bit layout is pinned: row-major inside the chunk, least-significant bit first, so cell
## (cx, cy) is bit `(cy mod 64) * 64 + (cx mod 64)`, i.e. byte `bit div 8`, mask `1 shl (bit mod 8)`.
## Little-endian bits are what a future client-side or tool-side reader will guess from the byte
## stream; the layout test pins it so a refactor cannot silently swap axes.
##
## Write policy: only the chunks a mutation dirtied. A dirty chunk is encoded from the *whole*
## explored set (a bitmap is a value, not a delta: writing just the new cells would erase the rest).
## Durability is NORMAL (Q12): explored is derived and monotone, unlike GM-authored content, and the
## caller puts these upserts in the mutation's transaction (4.2 step 6) so an ack never precedes the
## cells it reports.
##
## Load: every chunk row of the scene goes back into its player's set at startup (4.4). Polygons are
## not stored (they are recomputed, 8), so a restored player starts with its explored history and no
## sight until the next refresh.
import std/[sets, strutils, tables]
import db_connector/db_sqlite
import vision, world
const
ChunkCells* = 64
## Cells per chunk side (DESIGN 4.4: "e.g. 64x64 cells = 512 B").
ChunkBytes* = ChunkCells * ChunkCells div 8
## 512 B per chunk.
type
Chunk* = object
## One dirty chunk ready to upsert: the player it belongs to, its chunk coordinates and the
## 512-byte bitmap. `playerId` rides along so a mutation can collect chunks for several players
## (a wall change refreshes everyone) and write them in one statement loop.
playerId*: int
cx*, cy*: int
bits*: seq[byte]
# ---------------------------------------------------------------------------------------------------
# Geometry of a chunk
proc chunkCoord*(cell: int): int {.inline.} =
## The chunk coordinate of a cell coordinate (a cell is not a chunk: 64 cells per chunk).
cell div ChunkCells
proc chunkCols*(sc: SceneRec): int =
max(1, (sc.cols + ChunkCells - 1) div ChunkCells)
proc chunkRows*(sc: SceneRec): int =
max(1, (sc.rows + ChunkCells - 1) div ChunkCells)
proc bitOf*(cx, cy: int): int {.inline.} =
## The pinned bit position of a cell inside its chunk (row-major, LSB first).
((cy mod ChunkCells) * ChunkCells) + (cx mod ChunkCells)
# ---------------------------------------------------------------------------------------------------
# Encode / decode
proc encodeChunk*(sc: SceneRec, explored: var HashSet[int], ccx, ccy: int): seq[byte] =
## The whole 512-byte bitmap of one chunk. Cells outside the scene stay 0 (the last chunk row or
## column of a map whose size is not a multiple of 64 is partial).
result = newSeq[byte](ChunkBytes)
let cols = sc.cols
let x0 = ccx * ChunkCells
let y0 = ccy * ChunkCells
for ly in 0 ..< ChunkCells:
let cy = y0 + ly
if cy >= sc.rows: break
for lx in 0 ..< ChunkCells:
let cx = x0 + lx
if cx >= cols: break
if sc.cellIndex(cx, cy) in explored:
let bit = bitOf(cx, cy)
result[bit shr 3] = result[bit shr 3] or byte(1 shl (bit and 7))
proc decodeChunk*(sc: SceneRec, ccx, ccy: int, bits: openArray[byte]): seq[int] =
## Cell indices (`cy * cols + cx`) a chunk bitmap holds, skipping anything outside the scene and
## any bit a short row cannot hold (defensive: a hand-edited DB must not crash the server).
let cols = sc.cols
for ly in 0 ..< ChunkCells:
let cy = ccy * ChunkCells + ly
if cy >= sc.rows: break
for lx in 0 ..< ChunkCells:
let cx = ccx * ChunkCells + lx
if cx >= cols: break
let bit = bitOf(cx, cy)
if bit shr 3 >= bits.len: continue
if (bits[bit shr 3] and byte(1 shl (bit and 7))) != 0:
result.add sc.cellIndex(cx, cy)
# ---------------------------------------------------------------------------------------------------
# Dirty chunks of one mutation
proc dirtyChunks*(sc: SceneRec, playerId: int, explored: var HashSet[int],
cells: openArray[(int, int)]): seq[Chunk] =
## One chunk per distinct chunk coordinate touched by `cells` (the mutation's fresh cells), each
## encoded from the whole explored set. Caller holds the lock and has already refreshed the vision.
var seen = initHashSet[int]()
for (cx, cy) in cells:
if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue
let ccx = chunkCoord(cx)
let ccy = chunkCoord(cy)
let key = ccy * sc.chunkCols + ccx
if key in seen: continue
seen.incl key
result.add Chunk(playerId: playerId, cx: ccx, cy: ccy,
bits: encodeChunk(sc, explored, ccx, ccy))
# ---------------------------------------------------------------------------------------------------
# Store and load
const UpsertSql = """INSERT INTO explored_chunk (player_id, scene_id, cx, cy, bits)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(player_id, scene_id, cx, cy) DO UPDATE SET bits = excluded.bits"""
## db_connector's exec() inlines its arguments as SQL text, so a BLOB cannot ride that path; the
## prepared form binds a real blob (last argument is openArray[byte]).
proc writeChunks*(db: DbConn, sceneId: int, chunks: openArray[Chunk]): int =
## Upserts every dirty chunk. No transaction control: the caller wraps this in the mutation's
## transaction (4.2 step 6). Returns how many rows were written.
if chunks.len == 0: return 0
let ps = db.prepare(UpsertSql)
try:
for c in chunks:
db.exec(ps, c.playerId, sceneId, c.cx, c.cy, c.bits)
inc result
finally:
finalize(ps)
proc toBytes(s: string): seq[byte] =
## A stored BLOB comes back through getAllRows as a raw byte string (db_connector copies SQLITE_BLOB
## bytes straight into the Nim string); decode wants bytes.
result = newSeq[byte](s.len)
if s.len > 0: copyMem(addr result[0], unsafeAddr s[0], s.len)
proc restore*(db: DbConn, sc: SceneRec): Table[int, PlayerVision] =
## Startup (4.4): every stored chunk of the scene back into its player's explored set. A player
## with no chunks gets no entry at all (its sight state is created on first use, as in slice 5).
for row in db.getAllRows(sql"""
SELECT player_id, cx, cy, bits FROM explored_chunk WHERE scene_id = ?""", sc.id):
let pid = parseInt(row[0])
let cells = decodeChunk(sc, parseInt(row[1]), parseInt(row[2]), toBytes(row[3]))
for idx in cells:
result.mgetOrPut(pid, PlayerVision()).explored.incl idx
proc chunkCount*(db: DbConn, sceneId: int): int =
## How many rows the scene's explored stores occupy: an O(1) startup log number (11.3).
parseInt(db.getValue(sql"SELECT count(*) FROM explored_chunk WHERE scene_id = ?", sceneId))
+55 -6
View File
@@ -38,9 +38,9 @@ suite "migrate":
check migrate(db) == LatestVersion
check LatestVersion == migrations[^1].version
check schemaVersion(db) == LatestVersion
check LatestVersion == 4
check LatestVersion == 5
let rows = appliedMigrations(db)
check rows.len == 4
check rows.len == 5
check rows[0][0] == 1
check rows[0][1] == "meta"
check rows[1][0] == 2
@@ -49,6 +49,8 @@ suite "migrate":
check rows[2][1] == "world"
check rows[3][0] == 4
check rows[3][1] == "tokens"
check rows[4][0] == 5
check rows[4][1] == "explored"
# the steps' own DDL ran: meta and the auth tables exist and are empty
check db.getValue(sql"SELECT count(*) FROM meta") == "0"
check db.getValue(sql"SELECT count(*) FROM player") == "0"
@@ -59,12 +61,14 @@ suite "migrate":
check db.getValue(sql"SELECT count(*) FROM wall") == "0"
# step 4 creates the token table (DESIGN 4.4 `entity`), empty
check db.getValue(sql"SELECT count(*) FROM entity") == "0"
# step 5 creates the explored chunk store (DESIGN 4.4), empty
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0"
test "re-open is a no-op: no step applied, history and timestamps untouched":
let d = tmpDir()
block:
let db = openFresh(d)
check migrate(db) == 4
check migrate(db) == 5
close(db)
let db = openFresh(d)
defer:
@@ -73,7 +77,7 @@ suite "migrate":
let before = appliedMigrations(db)
check migrate(db) == 0
check migrate(db) == 0
check schemaVersion(db) == 4
check schemaVersion(db) == 5
check appliedMigrations(db) == before
test "history and user_version must agree":
@@ -147,9 +151,54 @@ suite "migrate":
check schemaVersion(db) == 2
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'scene'") == "0"
check migrate(db) == 2 # steps 3 and 4 run
check schemaVersion(db) == 4
check migrate(db) == 3 # steps 3, 4 and 5 run
check schemaVersion(db) == 5
check db.getValue(sql"SELECT count(*) FROM scene") == "1"
check db.getValue(sql"SELECT next_wall_id FROM scene WHERE id = 1") == "1"
check db.getValue(sql"SELECT count(*) FROM player WHERE role = 'gm'") == "1"
check db.getValue(sql"SELECT count(*) FROM entity") == "0"
test "a slice-5 DB migrates on: explored_chunk appears and the world survives":
# A fixture DB from the previous schema version (4, the slice-5 server): scene, a player, a key
# and a token already in it. Step 5 must add the explored store and leave all of it alone.
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
db.exec(sql(MigrationHistoryDdl))
for m in migrations[0 ..< 4]:
db.exec(sql"BEGIN")
for stmt in m.stmts: db.exec(sql(stmt))
db.exec(sql"INSERT INTO schema_migration (version, name, applied_at) VALUES (?, ?, 'x')",
m.version, m.name)
db.exec(sql("PRAGMA user_version = " & $m.version))
db.exec(sql"COMMIT")
db.exec(sql"INSERT INTO player (id, name, role, colour, created_at) VALUES (1, 'GM', 'gm', '#111', 'x')")
db.exec(sql"INSERT INTO player (id, name, role, colour, created_at) VALUES (2, 'Alice', 'player', '#222', 'x')")
db.exec(sql"INSERT INTO player_key (player_id, secret, created_at) VALUES (2, 'K-1', 'x')")
db.exec(sql"""INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y,
owner_player_id, created_at)
VALUES ('tok000000001', 1, 'pc', 'Alice', 'Alice', 400, 400, 2, 'x')""")
check schemaVersion(db) == 4
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'explored_chunk'") == "0"
check migrate(db) == 1 # only step 5 runs
check schemaVersion(db) == 5
check appliedMigrations(db).len == 5
check appliedMigrations(db)[4] == (version: 5, name: "explored")
# the explored store exists, with both FKs and the 512-byte chunk invariant
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0"
check db.getValue(sql"SELECT sql FROM sqlite_master WHERE name = 'explored_chunk'").contains("length(bits) = 512")
# the previous version's data is untouched
check db.getValue(sql"SELECT name FROM player WHERE id = 2") == "Alice"
check db.getValue(sql"SELECT secret FROM player_key WHERE player_id = 2") == "K-1"
check db.getValue(sql"SELECT x || ',' || y FROM entity WHERE id = 'tok000000001'") == "400.0,400.0"
# a chunk row follows its player and its scene out (ON DELETE CASCADE)
var bits = newSeq[byte](512)
let ps = db.prepare("INSERT INTO explored_chunk (player_id, scene_id, cx, cy, bits) VALUES (2, 1, 0, 0, ?)")
db.exec(ps, bits)
finalize(ps)
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "1"
db.exec(sql"DELETE FROM player WHERE id = 2")
check db.getValue(sql"SELECT count(*) FROM explored_chunk") == "0"
+221
View File
@@ -0,0 +1,221 @@
## 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