design: record the explored persistence decisions (#21)
Step 5 DDL, the 64x64/512 B chunk format with its pinned bit layout, the write policy (dirty chunks only, whole-chunk encoding, NORMAL durability, one transaction with a move and a separate one after GM authoring), the startup restore and the measured costs, all tagged FIXED (owner-delegated, #21), plus what slice 6 built in 10.3.
This commit is contained in:
+7
-3
@@ -254,12 +254,14 @@ entity_status(entity_id FK, status, source, PRIMARY KEY(entity_id, status, sourc
|
||||
explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, scene_id, cx, cy))
|
||||
```
|
||||
- Exactly one scene in v1 (Q3): `scene_id` keys stay in the schema.
|
||||
- Prototype stores one row per explored cell (`exp(role, c)`, one INSERT per new cell, `HANDOFF.md`); real build stores **chunked bitmaps**: a chunk is e.g. 64x64 cells = 512 B; dirty chunks upserted per mutation [PROPOSED]. Sizes [INFERRED]: 4096 px map / 32 px cell = 16 384 cells = 2 KB bitmap; 16384 px map = 262 144 cells = 32 KB.
|
||||
- Prototype stores one row per explored cell (`exp(role, c)`, one INSERT per new cell, `HANDOFF.md`); the real build stores **chunked bitmaps** [FIXED (owner-delegated, 2026-11-15, #21)]: a chunk is 64x64 cells = 512 B, upserted per mutation and only when the mutation dirtied it. Sizes: 4096 px map / 32 px cell = 16 384 cells = 2 KB (2x2 chunks); 16384 px map = 262 144 cells = 32 KB (8x8 chunks). Measured cost of one mutation-scale write (BEGIN; 512 B upsert; COMMIT): avg 0.015 ms, p99 0.035 ms (4.3's accepted commit tail is ~20 ms), and a real move's ack stays at avg 0.7 ms / p99 1-2 ms with explored writes on (`tests/texplored.nim`, `tools/persistence.test.mjs`).
|
||||
- Entity move = one UPSERT of x,y (prototype: `INSERT OR REPLACE INTO tok`).
|
||||
- Migrations: `PRAGMA user_version` + forward-only migration list; startup refuses to run on a newer DB [PROPOSED]. Detail [FIXED (owner-delegated, 2026-11-14, #16)]: `schema_migration(version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)` is the history; `user_version` carries the same latest version, and startup refuses when the two disagree or the history is not contiguous from 1. One transaction per step (DDL + history row + `user_version`); a failing step rolls back completely, and an up-to-date DB is not written at all (re-open is a no-op). Step 1 (M3 slice 1) creates `meta(k TEXT PRIMARY KEY, v TEXT NOT NULL)`. Step 2 (M3 slice 2, `auth`) creates `player(id, name TEXT UNIQUE NULL until first sign-in, role 'gm'|'player', colour, created_at)`, a partial unique index `player_single_gm` on `role='gm'`, `player_key(player_id PK FK ON DELETE CASCADE, secret TEXT plaintext, created_at)`, and `session(id, player_id FK ON DELETE CASCADE, token_hash TEXT UNIQUE, created_at, last_seen)` plus `session_player`; removing a player therefore removes its key and sessions. `session.last_seen` exists but is not updated in M3 (sessions never expire, Q10). A step may hold several statements; the runner executes them in order inside the step's transaction (db_connector prepares one statement per call).
|
||||
- Step 3 (M3 slice 4, `world`) [FIXED (owner-delegated, 2026-11-15, #19)]: creates `scene` and `wall` and seeds the single v1 scene. `scene(id PK, name, w REAL, h REAL, tile_size INT, cell INT, grid_size REAL, vision_radius_default REAL, token_radius_default REAL, art_version INT, active INT, next_wall_id INT, extra TEXT)`; the seeded row is `id 1, name 'Scene', 4096x4096, tile_size 32, cell 32, grid_size 0 (no grid), vision_radius_default 400, token_radius_default 20, art_version 1, active 1, next_wall_id 1, extra '{}'` (the prototype's world and radii, Q4's 32 px cell). `wall(scene_id FK ON DELETE CASCADE, id, ax, ay, bx, by REAL, kind TEXT CHECK (kind IN ('wall','door')), open INT CHECK (open IN (0,1)), flags TEXT JSON DEFAULT '{}', PRIMARY KEY (scene_id, id))`. Two consequences: (a) M3 has a scene without waiting for the M6 import CLI, so `wall.*` and `door.set` work in slice 4; `w, h, tile_size, cell, art_version` stay off the wire (6.1 `scene.set`). (b) The scene row carries `next_wall_id`, so wall ids survive restarts, removals and re-imports of the same scene (#3). Seeding in the migration rather than at startup keeps the scene identical on every start and lets the migration test assert it (10.3).
|
||||
- Step 4 (M3 slice 5, `tokens`) [FIXED (owner-delegated, 2026-11-15, #20)]: creates `entity`, the map figures (`id TEXT PK`, `scene_id FK ON DELETE CASCADE`, `kind`, `descriptive_name`, `actual_name`, `x`, `y`, `radius REAL NULL`, `owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL`, `gm_only`, `vision_radius REAL NULL`, `flags TEXT` default `'{}'`, `created_at`). `owner_player_id` NULL is GM-controlled, so `player.remove` hands that player's tokens to the GM through the FK alone (3.2) and memory (`0` = GM-controlled) mirrors it. `radius`, the three property buckets, `character_id` and `reveal_all` are NOT columns yet: slices 7 (#22, `token.resize` and props) and 8 (#23, characters and names) own them, and `entity_status` / `explored_chunk` arrive with slice 7 and slice 6. Ids are 12 random characters, so no counter column is needed (8).
|
||||
- Startup: load everything into memory, recompute vision for all players (prototype does, in one transaction) so `vision` is never stale vs walls. Slice 5 loads the scene and its tokens; a player's sight state (`PlayerVision`) is created on that player's first connection and recomputed from the current walls, so nothing is stale after a restart. Explored persistence (slice 6, #21) is what will make the reloaded grid survive.
|
||||
- Step 5 (M3 slice 6, `explored`) [FIXED (owner-delegated, 2026-11-15, #21)]: creates `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, cy INTEGER NOT NULL, bits BLOB NOT NULL CHECK (length(bits) = 512), PRIMARY KEY (player_id, scene_id, cx, cy))`. `(cx, cy)` are **chunk** coordinates (`cell div 64`), not cell coordinates; `bits` is a 512-byte bitmap of 64x64 cells, row-major inside the chunk, least-significant bit first (cell `(cx, cy)` is bit `(cy mod 64) * 64 + (cx mod 64)`, byte `bit div 8`, mask `1 shl (bit mod 8)`). Cells outside the scene stay 0, so a map whose cell count is not a multiple of 64 needs no special case; the v1 scene is 128x128 cells = 2x2 chunks, a 16384 px map 8x8. Both FKs cascade, so `player.remove` and a scene delete take the explored rows with them. The layout is pinned by `tests/texplored.nim` (exact byte/bit positions) and re-read independently by `tools/persistence.test.mjs`, so a refactor cannot silently swap axes or bit order.
|
||||
- Step 5 write policy [FIXED (owner-delegated), #21]: a mutation persists **only the chunks its refresh dirtied**, and each of those 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. A `token.move` writes the position and its chunks in **one** transaction (both NORMAL); a GM authoring write (`wall.*`, `door.set`, `token.create`/`update`/`remove`) keeps its own `FULL` row transaction and writes the chunks in a second `NORMAL` transaction, both inside the global lock and before the ack, so no ack precedes the cells it reports and no lock hold grows beyond one extra 512 B upsert. Those two commits are not atomic with each other; a crash between them loses explored cells the client was never told about, and the next refresh re-adds any the token can still see (explored never un-explores).
|
||||
- Startup: load everything into memory, recompute vision for all players (prototype does, in one transaction) so `vision` is never stale vs walls. Slice 5 loads the scene and its tokens; a player's sight state (`PlayerVision`) is created on that player's first connection and recomputed from the current walls, so nothing is stale after a restart. Slice 6 (#21) restores every stored `explored_chunk` row into that player's set before the first connection (`explored.restore`), so a reloaded grid is the grid the player had; polygons are never stored (they are recomputed, 8).
|
||||
- Shutdown: install a SIGTERM handler [prototype has only SIGINT, `HANDOFF.md`]: stop accepting, close sockets, final `wal_checkpoint(TRUNCATE)`, exit. Durability does not depend on it (WAL commit before ack).
|
||||
|
||||
---
|
||||
@@ -669,7 +671,7 @@ Principles carried from the prototype: the checker must be independent of the co
|
||||
- **Probing test (T8)**: M2, in-process against the move-rules module (5.5): arbitrary far moves; assertion: facts about walls/doors beyond LOS recoverable from replies <= a bounded amount (step cap), and uniform nack shape. M3: same test over WS with a hostile client (moved from M2).
|
||||
- **Auth tests**: key replace (old key invalid, sessions revoked, live connections closed), remove player (key invalid, characters and tokens pass to GM), one key reused on several devices (Q10 FIXED), Origin mismatch rejected, cookie flags present.
|
||||
- **Protocol tests** (#18, `tools/protocol.test.mjs`): proto missing/non-integer (HTTP 400) and mismatch (`closing` 4003, no `hello`); unknown intent type (`unknown-type`) with unknown fields ignored; exactly one `ack` per `reqId` (reqId 0 and 2^31-1 included); `hello` first with `n = 1` and a per-connection `n` thereafter; `error malformed` for unreadable frames; the malformed flood (nine tolerated, the tenth closes 1008); the intent bucket (burst then `rate-limited`, connection stays open, a refused intent applies nothing, `error rate-limited` for an unreadable frame on an empty bucket); the 64 KB inbound boundary (exactly 64 KB is a message, 64 KB + 1 drops the TCP connection with no close frame); unmasked and bad-opcode frames; the server Ping and the Pong answer to a client Ping; the connection cap (503 + `Retry-After: 5`); and every server-initiated close as `closing` then 1005.
|
||||
- **Persistence**: migration tests (old DB -> new), chunked explored round trip, restart test extended to wall CRUD and entity props.
|
||||
- **Persistence**: migration tests (old DB -> new), chunked explored round trip, restart test extended to wall CRUD and entity props. **Slice 6 built** the explored half: `tests/texplored.nim` (chunk layout pinned, whole-chunk encoding, upsert replacement, per-player keying, restore, write cost) and `tools/persistence.test.mjs` (round trip through a fresh resync, per-player isolation, SIGTERM and SIGKILL restart equality, a wall removal's revealed cells after the wall returns, chunk rows decoded independently, move-ack timing, and a fixture schema-4 DB migrated by the real binary).
|
||||
- **Slow client** (Q13, 4.3): a client that stops reading; outbox stays under cap, no further state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the dead `/ws` socket within its configured timeout.
|
||||
- **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype already drives devbox chromium, `prototype-pixi-perf/bench.mjs`; SwiftShader is fine for correctness, not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect restores view; drag moves token and rollback works.
|
||||
- **Independent traffic audit in e2e**: record all WS frames and HTTP responses seen by a player browser and run the leak checker's (a)(e) assertions over them.
|
||||
@@ -857,3 +859,5 @@ Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #19)]: walls
|
||||
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #16)]: M3 slice 1 groundwork ("bare server"). Config keys, defaults, precedence and the canonical origin: 11.1. Migration history DDL, the agreement/contiguity rule and one-transaction-per-step: 4.4. Secret redaction (value registry plus sensitive field names, minimum secret length 8): 11.3. `GET /healthz` answers `200 {"status":"ok"}` from slice 1; the lock-bounded health check stays M5: 6.6, 11.3. `devbox run test` runs `nimble test` first and only then `node --test tools/*.test.mjs` (10.4); both logs land in `results/`. The server's listen address is the constant `config.BindAddress` = `127.0.0.1`, not a config key (T15). Dependencies: `fff_vtt.nimble` requires `mummy == 0.4.8` and `db_connector == 0.1.0`; devbox adds nodejs 26 and sqlite (`out`+`bin`, with `LD_LIBRARY_PATH=$DEVBOX_PACKAGES_DIR/lib` for the dlopen). Node 26 `{headers}` re-check: 10.4.
|
||||
|
||||
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #20)]: tokens and sight (M3 slice 5). Schema is migration step 4 (`tokens`): `entity` as listed in 4.4, no `radius`/props/`character_id` columns yet (slices 7-8 add them, `entity_status` with slice 7, `explored_chunk` with slice 6). Token ids are 12 random characters from `[A-Za-z0-9_-]` (a 64-symbol alphabet, so 6 uniform bits per character, 72 bits) from `std/sysrand`, collision-checked against every loaded token. The token payload rules 6.1 left open are fixed in 6.1 ("Token payload rules"); the load-bearing ones are: plain tokens only, `radius`/`props`/`character_id` refused `invalid` rather than dropped, effective radius = the scene default, the wire `name` is always the descriptive name, `controller: null` is the only GM spelling, and `explored` on connect is RLE rows. **Modules**: `server/tokens.nim` (records, validation, write-through persistence with FULL for GM authoring and NORMAL for moves), `server/vision.nim` (per-player polygons, explored set, the one copy of the visibility rule), `server/views.nim` (the single egress: typed `GmView`/`PlayerView`, then frames, then the per-connection diff), `server/worldmap.nim` (records -> geometry/move-rule inputs), `server/faults.nim` (test-only hook). `main.nim` holds the state (`tokens`, `visions` per player, `known` per connection keyed by app connId) and never builds a state frame itself, so raw world state has no path to a socket outside the egress (2, 10.1). **Egress timing**: a mutation's ack and its per-recipient diffs are enqueued under the global lock, in that order, and every frame is built from the state at enqueue time (mummy's `send` only appends to its deque, 4.3). Exact per-connection ordering between two concurrent mutations, and the coalescing that keeps that cheap, stay the M5 outbox. **Runtime rules**: polygons exist only for tokens a player controls that carry the `vision` flag, with the token's `vision_radius` or the scene default; only their token centres count for visibility; explored is the union of `cellsTouched` over history, only grows, drops cells outside the world, and the `fresh` set is cleared after one egress fan-out. A door closing pushes tokens aside (5.5) and persists the new positions; `stuck`/`squeezed` are slice 7's status model, so a failed push leaves the token overlapped and unflagged for now. `token.move` maps the move rules to the wire exactly: `ack {pos}`, the uniform nack for locked/over-cap/collision and for an out-of-bounds GM move, and `not-allowed` (players, one code for unknown and not-yours) or `not-found` (GM) before any geometry runs; accepted moves are persisted with NORMAL durability. `hello` carries the scene block for every named recipient and `extra` for the GM; an unnamed player still gets only `proto, role, me` and is not fed any state at all (6.3), so slice 5's player-side acceptance is reached through a harness fixture that writes the name into the DB before connecting: `player.setname` is slice 8 (#23) and the unnamed gate itself is pinned by `tools/tokens.test.mjs`. **Tests** (10.1, 10.3): `tools/leak.mjs` builds a 27-group scene over the real wire (enter/leave by movement, a closed door, create/remove, `gm_only`, a controller hand-over, another player walking in and out, a wall added and removed, a door push) and records every frame; `tools/leakcheck.nim` replays it with the GM socket as truth, recomputes polygons from `geometry.nim`, and checks explored against both that recomputation and an independent clear-segment sampler; A and B both pass with zero failures. `tools/fault.test.mjs` catches `hidden`, `gmOnly`, `walls`, `withhold`, `otherOwner`, `otherVision`, `otherExplored`, `noremove` and `explored` under their exact class sets and asserts the shipped binary contains no `LEAK_FAULT` string. `tools/probing.test.mjs` re-runs T8/H26 over WS: over-cap probes give the one uniform nack, two scenes differing only beyond cap + token radius produce identical reply sequences over 90 hostile probes inside the 6.4 burst, and a wall inside that bound does change the replies. Nim units: `tests/ttokens.nim`, `tests/tvision.nim`, `tests/tviews.nim`. Mutations aa-af pin the view rule, the egress `token_gone`, the absence of GM-only fields in a player frame and the "explored only grows" rule.
|
||||
|
||||
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #21)]: explored persistence (M3 slice 6). Schema is migration step 5 (`explored`): `explored_chunk` keyed by `(player_id, scene_id, cx, cy)` with a 512-byte blob, both FKs cascading (4.4). Chunk format and size are fixed at 64x64 cells = 512 B, row-major LSB-first bits, `(cx, cy)` = chunk coordinates; the layout is pinned by tests and re-read independently by the Node harness. **Write timing**: a mutation writes only the chunks its refresh dirtied, each encoded from the whole explored set, with `NORMAL` durability; a move writes position and chunks in one transaction, a GM authoring write adds a second `NORMAL` chunk transaction under the same lock, both before the ack — the two commits are deliberately not atomic with each other, and the only loss they can cause after a crash is cells no client was acked about, which the next refresh re-adds. Measured: 0.015 ms avg / 0.035 ms p99 per chunk write, 0.7 ms avg / 1-2 ms p99 per move ack (4.3's budget is untouched). **Load**: `explored.restore` fills every player's set at startup from the chunk rows and logs `explored_loaded players= chunks=`; polygons stay recomputed (8). **Tests** (10.1, 10.3): `tests/texplored.nim` (format, whole-chunk encoding, upsert replacement, per-player keying, restore, cost) and `tools/persistence.test.mjs` (fresh-resync round trip, per-player isolation, SIGTERM and SIGKILL restart equality, wall-removal cells surviving after the wall returns, chunk rows decoded independently, move-ack timing, and a schema-4 fixture DB migrated by the real binary). Mutations ag-al pin the bit layout, the chunk coordinate, the restore, the per-player key, the upsert and the dirty-chunk dedupe. See 4.4, 8, 10.3.
|
||||
|
||||
Reference in New Issue
Block a user