Files
FFF_vtt_frozen/tools/bench.nim
T
SirStone 2727617db9 feat: session cache, explored bitmap and lock-free tile gate (#65)
The tile gate no longer takes dbLock or runs a SQL session JOIN per tile: a published
in-memory view (server/sessions.nim) holds token hashes -> player/role and one explored
bitmap per player. Sessions load from the DB at startup and are updated by join, key
replacement and player removal in the same lock as the write; refreshed cells publish
before the ack. The gate is one snapshot read (parse + session + bit test + redirect)
over scalar data only, so a tile burst is answered while a mutation holds dbLock.

Evidence: tests/tsessions.nim pins the cache/bitmap lifecycle and gate rule; tiles.test
adds the lock-held burst and the revocation/restart seam; auth.test adds the
LEAK_FAULT=sessioncache negative control (a stale entry makes the auth group fail);
mutation c5 keeps the cache drop load-bearing. Explored wire and persistence untouched.

Bench (devbox run bench, in-process): tile gate old 0.006 ms -> new 0.001 ms per
request; incremental explored mark 0.001 ms; snapshot build 2.0 ms at 262144 cells
(startup only).
2026-11-21 00:10:39 +01:00

151 lines
8.6 KiB
Nim

## Vision and egress microbench: devbox run bench (nim c -d:release -r tools/bench.nim; log: results/bench.log).
## No timing code lives in server/: this harness times from outside with O(1) accumulators (sum, worst), no sample arrays.
## Targets (DESIGN 5.3 / 13 M2, PROPOSED): polygon + cells <= 0.451 ms avg on the prototype scene; polygon < 1 ms avg on 5k walls.
## The egress rows record the absolute averages the in-process gate (tests/tviews.nim, TESTING 5.3) deliberately does not assert.
import std/[json, monotimes, times, strformat, os, math, options, sets, tables]
import db_connector/db_sqlite
import geometry, moverules
import auth, characters, crypto, db, explored, props, sessions, tiles, tokens, views, vision, world
import scenegen
import ../tests/[refold, testutil]
let root = currentSourcePath().parentDir.parentDir
let j = parseFile(root / "tests" / "fixtures" / "scene.json")
var proto: seq[Wall]
for w in j["walls"]:
proto.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
door: w["door"].getBool, open: w["open"].getBool)
let radius = j["visionRadius"].getFloat
let cell = j["exploredCell"].getFloat
var toks: seq[Vec]
for t in j["tokens"]: toks.add (t["pos"][0].getFloat, t["pos"][1].getFloat)
var sink = 0
var misses = 0
proc bench(name: string, n: int, f: proc(i: int)): float =
for i in 0 ..< 50: f(i) # warm-up
var sum, worst = 0.0
for i in 0 ..< n:
let t0 = getMonoTime(); f(i)
let ms = (getMonoTime() - t0).inNanoseconds.float / 1e6
sum += ms; worst = max(worst, ms)
result = sum / n.float
echo &"{name}: n={n} avg={result:.3f}ms worst={worst:.3f}ms"
proc target(name: string, got, limit: float) =
let ok = got <= limit
if not ok: inc misses
echo &"TARGET {name}: {got:.3f} ms vs <= {limit} ms: {(if ok: \"PASS\" else: \"MISS\")}"
echo "== prototype scene (60 walls, 8 tokens, radius 400, cell 32) =="
discard bench("1 poly (jittered start positions)", 2000, proc(i: int) =
let p = toks[i mod 8]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius).len)
discard bench("6 polys (one 6-token party)", 500, proc(i: int) =
for k in 0 ..< 6:
let p = toks[k + 2]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius).len)
let pc = bench("1 poly + cellsTouched (scanline)", 2000, proc(i: int) =
let p = toks[i mod 8]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius), cell).len)
discard bench("6 polys + cellsTouched (scanline)", 300, proc(i: int) =
for k in 0 ..< 6:
let p = toks[k + 2]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius), cell).len)
discard bench("1 poly + cellsTouchedOld (prototype reference)", 500, proc(i: int) =
let p = toks[i mod 8]; sink += cellsTouchedOld(visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius), cell).len)
target("polygon+cells, prototype scene (prototype baseline 0.451)", pc, 0.451)
proc big(label: string, world: float) =
let walls = genScene(world, 5000, 1)
var inBox, nn = 0
var r = Rng(s: 7)
for k in 0 ..< 200: # density: walls whose bbox meets the 800x800 vision box
let o: Vec = (r.uni(400, world - 400), r.uni(400, world - 400))
for w in walls:
if not (max(w.a.x, w.b.x) < o.x - radius or min(w.a.x, w.b.x) > o.x + radius or
max(w.a.y, w.b.y) < o.y - radius or min(w.a.y, w.b.y) > o.y + radius): inc inBox
inc nn
echo &"== {label}: genScene(world={world:.0f}, n=5000, seed=1), avg walls in vision bbox {inBox.float / nn.float:.1f} =="
var rng = Rng(s: 99)
let po = bench(&"1 poly, {label}", 2000, proc(i: int) =
let o: Vec = (rng.uni(400, world - 400), rng.uni(400, world - 400))
sink += visibilityPolygon(o, walls, radius).len)
discard bench(&"1 poly + cellsTouched, {label}", 2000, proc(i: int) =
let o: Vec = (rng.uni(400, world - 400), rng.uni(400, world - 400))
sink += cellsTouched(visibilityPolygon(o, walls, radius), cell).len)
discard bench(&"1 move check (pathClear, cap-length step), {label}", 20000, proc(i: int) =
let o: Vec = (rng.uni(400, world - 400), rng.uni(400, world - 400))
sink += int(pathClear(walls, o, (o.x + 300, o.y), 20)))
if label == "5k sparse": target("polygon, 5k-wall scene", po, 1.0)
big("5k sparse", 16384)
big("5k dense", 4096)
echo "== egress (#28: 6 players x 40 encountered entries, 262144 explored cells) =="
proc egressStore(cells: int): ref ContextStore =
var tokens: seq[TokenRec]
for i in 0 ..< 6:
tokens.add TokenRec(id: "t" & $(i + 2), scene: 1, kind: "npc", descriptiveName: "t",
actualName: "T", pos: (400.0 + float(i) * 10, 400), owner: i + 2,
flags: %*{"vision": true}, props: newProps())
for e in 0 ..< 40:
tokens.add TokenRec(id: "e" & $e, scene: 1, kind: "npc", descriptiveName: "a thing",
actualName: "Thing", pos: (3000.0 + float(e) * 30, 3000), owner: 0,
flags: %*{}, props: newProps())
result = (ref ContextStore)(scene: SceneRec(id: 1, name: "Scene", w: 4096, h: 4096, tileSize: 32,
cell: 32, visionRadiusDefault: 400,
tokenRadiusDefault: 20, artVersion: 1, nextWallId: 1,
extra: newJObject()), tokens: tokens)
for pid in 2 .. 7:
var pv: PlayerVision
pv.refresh(result.scene, result.tokens, pid)
result.visions[pid] = pv
for k in 0 ..< cells: result.visions[pid].explored.incl k
result.encountered[pid] = initTable[string, EncounteredEntry]()
for e in 0 ..< 40:
result.encountered[pid]["e" & $e] =
EncounteredEntry(entityId: "e" & $e, descriptiveName: "a thing")
let egressLarge = egressStore(262144)
discard bench("GM egress pass (fresh diff base)", 200, proc(i: int) =
var known: Known
sink += egressFrames(Recipient(isGm: true, playerId: 1), egressLarge.borrow, known).len)
discard bench("player egress pass (fresh diff base)", 200, proc(i: int) =
var known: Known
sink += egressFrames(Recipient(isGm: false, playerId: 2), egressLarge.borrow, known).len)
echo "== tile gate (#65): old SQL-under-lock path vs published snapshot =="
let gateScene = SceneRec(id: 1, name: "Scene", w: 4096, h: 4096, tileSize: 32, cell: 32,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1,
nextWallId: 1, extra: newJObject())
# The "before" side: a real (in-memory) SQLite session table and the explored HashSet the old gate
# read under dbLock. The SELECT is the same `session JOIN player` auth.sessionPlayer runs.
let mem = openDatabase(":memory:")
mem.exec(sql"CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, role TEXT, colour TEXT)")
mem.exec(sql"""CREATE TABLE session (id INTEGER PRIMARY KEY, player_id INTEGER,
token_hash TEXT, created_at TEXT, last_seen TEXT)""")
mem.exec(sql"INSERT INTO player (id, name, role, colour) VALUES (2, 'Alice', 'player', '#222')")
let benchToken = "bench-session-token"
mem.exec(sql"INSERT INTO session (player_id, token_hash) VALUES (2, ?)", sha256Hex(benchToken))
var exploredSet = initHashSet[int]()
var gateCells: seq[(int, int)]
for cx in 8 .. 12:
for cy in 8 .. 12:
exploredSet.incl gateScene.cellIndex(cx, cy)
gateCells.add (cx, cy)
let gc = newGateCache(gateScene)
gc.putSession(sha256Hex(benchToken), 2, false)
gc.markExplored(2, gateScene, gateCells)
discard bench("tile gate old: parse + SHA-256 + session JOIN + HashSet", 2000, proc(i: int) =
let h = sha256Hex(benchToken)
let parsed = parseTileRequest("1", "v1", "9_9.png", gateScene)
if parsed.outcome == toTileOk and sessionPlayer(mem, h).isSome:
if tileCoveredByExplored(gateScene, exploredSet, parsed.req.x, parsed.req.y): inc sink)
discard bench("tile gate new: parse + SHA-256 + cache lookup + bitmap", 2000, proc(i: int) =
let h = sha256Hex(benchToken)
if gc.gateTile(h, "1", "v1", "9_9.png").allowed: inc sink)
# Explored ops: the snapshot build at the 16384 px size (512x512 cells) and the incremental mark.
let bigScene = SceneRec(id: 1, name: "Scene", w: 16384, h: 16384, tileSize: 32, cell: 32,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1,
nextWallId: 1, extra: newJObject())
var bigSet = initHashSet[int]()
for k in 0 ..< 262144: bigSet.incl k
discard bench("explored snapshot build (262144 cells)", 20, proc(i: int) =
sink += bitMapOf(bigScene, bigSet).bitCount)
discard bench("explored incremental mark (16 fresh cells)", 5000, proc(i: int) =
gc.markExplored(2, gateScene, @[(9, 9), (10, 9), (11, 9), (12, 9)]))
echo "(sink ", sink, ")"
quit(if misses == 0: 0 else: 1)