views: borrow the world in egress instead of copying it (#28)

views.Context held copies of scene, tokens, characters, reveals, encountered
and visions, so every mutation deep-copied each player's explored HashSet under
the global lock; playerView then copied its own PlayerVision again and greyFor
copied one per encountered entry. Context now holds six pointers
(contextOf/borrow), playerView/gmView read a ptr PlayerVision and a view builds
each player's visible-id set once per frame, so grey is a set test.

Measured on this build's types (debug, 6 players, 40 encountered entries, 40
world tokens, 16384 / 262144 explored cells): context construction 0.227 ms /
4.87 ms -> 0.008 us; one getOrDefault of a PlayerVision 28.8 us / 591 us -> gone;
GM egress pass 8.0 ms / 142.8 ms -> 0.79 ms / 0.80 ms; player pass 1.45 ms /
25.7 ms -> 0.32 ms. Behaviour is unchanged (leak/fault suites and tviews green);
tviews pins the borrow by identity, the six-pointer size and both sizes inside
the M5 7.5 ms budget.
This commit is contained in:
2026-11-15 14:26:11 +01:00
parent 8e045b0ac8
commit e9d5f6815a
3 changed files with 193 additions and 39 deletions
+108 -18
View File
@@ -2,7 +2,8 @@
## per-connection diff that produces `token`/`token_gone`/`vision`/`explored`, and the field rules
## that keep GM-only data out of a player's frames. The black-box proof over a real socket is
## tools/leak.test.mjs with tools/leakcheck.nim.
import std/[algorithm, json, options, sequtils, sets, tables, unittest]
import std/[algorithm, json, monotimes, options, sequtils, sets, strformat, tables,
times, unittest]
import characters, props, tokens, views, vision, world
const Pid = 2 # the subject player
@@ -18,22 +19,32 @@ proc tok(id: string, x, y: float, owner: int, gmOnly = false, visionFlag = true)
pos: (x, y), owner: owner, gmOnly: gmOnly,
flags: (if visionFlag: %*{"vision": true} else: %*{}))
proc ctxOf(sc: SceneRec, tokens: seq[TokenRec], players: seq[int]): Context =
result = Context(scene: sc, tokens: tokens)
proc ctxOf(sc: SceneRec, tokens: seq[TokenRec], players: seq[int]): ref ContextStore =
## The fixture owns the state (as `App` does) and the egress borrows it (#28). A heap store, so
## the addresses a Context holds stay valid for the whole test.
result = (ref ContextStore)(scene: sc, tokens: tokens)
for pid in players:
var pv: PlayerVision
pv.refresh(sc, tokens, pid)
pv.refresh(result.scene, result.tokens, pid)
result.visions[pid] = pv
proc refreshAll(ctx: var Context) =
proc refreshAll(ctx: ref ContextStore) =
## What main.refreshAll does: recompute every player's sight in place, keeping explored cells.
for pid in ctx.visions.keys.toSeq: ctx.visions[pid].refresh(ctx.scene, ctx.tokens, pid)
proc pass(ctx: var Context, known: var Known, resync = false, player = Pid): seq[JsonNode] =
proc pass(ctx: ref ContextStore, known: var Known, resync = false, player = Pid): seq[JsonNode] =
## One egress pass exactly as main runs it: build, diff, then clear the fresh cells (4.2 step 8).
result = egressFrames(Recipient(isGm: false, playerId: player), ctx, known, resync)
result = egressFrames(Recipient(isGm: false, playerId: player), ctx.borrow, known, resync)
for pid in ctx.visions.keys.toSeq: ctx.visions[pid].clearFresh()
# The tests keep calling the view procs with their store; the egress itself only ever sees the
# borrowed Context (six addresses).
proc gmView(ctx: ref ContextStore): GmView = views.gmView(ctx.borrow)
proc playerView(ctx: ref ContextStore, playerId: int): PlayerView =
views.playerView(ctx.borrow, playerId)
proc greyFor(ctx: ref ContextStore, playerId: int, entityId: string): bool =
views.greyFor(ctx.borrow, playerId, entityId)
proc typesOf(frames: seq[JsonNode]): seq[string] = frames.mapIt(it["t"].getStr)
proc keysDeep(node: JsonNode): HashSet[string] =
@@ -75,7 +86,9 @@ suite "GM view (3.1: everything, with the GM-only extras)":
test "the GM never gets vision polygons or explored cells":
let sc = sceneWith(@[])
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctxOf(sc, @[tok("a", 100, 100, Pid)], @[Pid]), known, resync = true)
let frames = egressFrames(Recipient(isGm: true, playerId: 1),
ctxOf(sc, @[tok("a", 100, 100, Pid)], @[Pid]).borrow, known,
resync = true)
check typesOf(frames) == @["token"]
suite "player view (3.1: controlled always, LOS + not gm_only otherwise)":
@@ -119,7 +132,7 @@ suite "player view (3.1: controlled always, LOS + not gm_only otherwise)":
tok("secret", 500, 500, 0, gmOnly = true)]
var known: Known
let ctx = ctxOf(sc, tokens, @[Pid])
for f in egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true):
for f in egressFrames(Recipient(isGm: false, playerId: Pid), ctx.borrow, known, resync = true):
for key in ForbiddenToPlayers:
check key notin keysDeep(f)
@@ -304,7 +317,7 @@ suite "props and statuses (#22, 6.1: the bucket and the source are per-recipient
proc charOf(id: string, owner: int, dname = "a grumpy man", actual = "Lord Vex"): CharacterRec =
CharacterRec(id: id, owner: owner, descriptiveName: dname, actualName: actual, props: newProps())
proc withChar(ctx: var Context, c: CharacterRec): int =
proc withChar(ctx: ref ContextStore, c: CharacterRec): int =
ctx.characters.add c
ctx.characters.len - 1
@@ -321,7 +334,7 @@ suite "characters in the egress (3.1, 6.1, 8)":
discard ctx.withChar(c)
ctx.reveals.withReveal(Other, "c1")
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx, known, resync = true)
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx.borrow, known, resync = true)
check frames.len == 1
let f = frames[0]
check f["t"].getStr == "character"
@@ -337,7 +350,7 @@ suite "characters in the egress (3.1, 6.1, 8)":
discard ctx.withChar(charOf("mine", Pid))
discard ctx.withChar(charOf("theirs", Other))
var known: Known
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true)
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx.borrow, known, resync = true)
let chars = frames.filterIt(it["t"].getStr == "character")
check chars.len == 1
check chars[0]["id"].getStr == "mine"
@@ -350,16 +363,16 @@ suite "characters in the egress (3.1, 6.1, 8)":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
let idx = ctx.withChar(charOf("c1", Other))
var known: Known
check typesOf(egressFrames(Recipient(isGm: false, playerId: Other), ctx, known, resync = true))
check typesOf(egressFrames(Recipient(isGm: false, playerId: Other), ctx.borrow, known, resync = true))
.contains("character")
var otherKnown: Known
check not typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx, otherKnown))
check not typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx.borrow, otherKnown))
.contains("character")
ctx.characters[idx].owner = Pid
let otherFrames = egressFrames(Recipient(isGm: false, playerId: Other), ctx, known)
let otherFrames = egressFrames(Recipient(isGm: false, playerId: Other), ctx.borrow, known)
check typesOf(otherFrames) == @["character_gone"]
check otherFrames[0]["id"].getStr == "c1"
check typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx, otherKnown))
check typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx.borrow, otherKnown))
.contains("character")
test "a linked token's name follows the character, and the owner sees the actual one":
@@ -451,7 +464,7 @@ suite "the encountered list (8)":
ctx.encountered[Other]["theirs"] = EncounteredEntry(entityId: "theirs",
descriptiveName: "a theirs")
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx, known, resync = true)
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx.borrow, known, resync = true)
let lists = frames.filterIt(it["t"].getStr == "encountered")
check lists.len == 2
check lists[0]["player"].getInt == Pid
@@ -466,7 +479,84 @@ suite "the encountered list (8)":
ctx.encountered[Other]["theirs"] = EncounteredEntry(entityId: "theirs",
descriptiveName: "a theirs")
var known: Known
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true)
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx.borrow, known, resync = true)
for f in frames.filterIt(it["t"].getStr == "encountered"):
check f["set"].len == 0
check not f.hasKey("player")
suite "egress borrows the world instead of copying it (#28)":
const Pids = [2, 3, 4, 5, 6, 7]
proc bigStore(cells: int): ref ContextStore =
## A realistic worst case: six players, each with one vision token, `cells` explored cells and
## 40 encountered entries (the issue's 6 x 40 egress measurement).
var tokens: seq[TokenRec]
for i, pid in Pids: tokens.add tok("t" & $pid, 400.0 + float(i) * 10, 400, pid)
# 40 tokens that still exist in the world: an entry is only an expensive lookup while its
# token is there (a removed token short-circuits), so this is the shape the issue measured.
for e in 0 ..< 40: tokens.add tok("e" & $e, 3000.0 + float(e) * 30, 3000, 0)
result = ctxOf(sceneWith(@[]), tokens, @Pids)
for pid in Pids:
for k in 0 ..< cells: result.visions[pid].explored.incl k
result.encountered[pid] = initTable[string, characters.EncounteredEntry]()
for e in 0 ..< 40:
result.encountered[pid]["e" & $e] =
EncounteredEntry(entityId: "e" & $e, descriptiveName: "a thing")
proc gmPass(store: ref ContextStore): int =
## One GM egress pass with a fresh diff base (the expensive shape: every frame is built).
var known: Known
egressFrames(Recipient(isGm: true, playerId: 1), store.borrow, known).len
proc playerPass(store: ref ContextStore, playerId: int): int =
## A mutation's pass, not a connect: no `resync`, so the payload is vision + tokens + the 40
## encountered entries. (`resync = true` additionally serialises the whole explored grid as RLE,
## which is a per-connection cost and would measure the RLE writer, not the egress copies.)
var known: Known
egressFrames(Recipient(isGm: false, playerId: playerId), store.borrow, known).len
test "a Context is six addresses: in-place changes are visible through the borrow":
var store = (ref ContextStore)(scene: sceneWith(@[]), tokens: @[tok("a", 400, 400, Pid)])
store.visions[Pid] = PlayerVision()
let ctx = store.borrow
check ctx.tokens.len == 1
# No snapshot: a later mutation of the owner is what the borrow sees.
store.tokens.add tok("b", 3000, 3000, 0)
check ctx.tokens.len == 2
store.visions[Pid].explored.incl 42
check 42 in ctx.visions[Pid].explored
store.encountered[Pid] = initTable[string, characters.EncounteredEntry]()
store.encountered[Pid]["a"] = EncounteredEntry(entityId: "a", descriptiveName: "an a")
check ctx.encountered[Pid].hasKey("a")
# And the type itself carries no container: no Table, no HashSet, no seq (six pointers).
check sizeof(Context) <= 6 * sizeof(pointer) + 8
test "building a Context and egressing does not scale with the explored sets":
var small = bigStore(16384) # 128 x 128 cells: the v1 map at cell 32
var large = bigStore(262144) # 512 x 512 cells: a 16384 px map at cell 32
# A build is six addresses. Before the fix, one Context construction cost ~0.19 ms at 16384
# cells and ~4.44 ms at 262144 (the issue's measurement on this build's types).
var sink = 0
var t0 = getMonoTime()
for i in 0 ..< 1000: sink += large.borrow.pTokens[].len
let buildMs = float((getMonoTime() - t0).inNanoseconds) / 1e6 / 1000.0
echo &"#28 context build, 262144 cells x 6 players: {buildMs * 1000.0:.3f} us"
check buildMs < 0.01 # 10 us; a copy of one explored set is already ~0.55 ms
# Egress for 6 x 40 entries: the M5 p99 budget is 7.5 ms per mutation (DESIGN 13 M5).
t0 = getMonoTime()
for i in 0 ..< 20: sink += gmPass(large)
let gmMs = float((getMonoTime() - t0).inNanoseconds) / 1e6 / 20.0
t0 = getMonoTime()
for i in 0 ..< 20: sink += playerPass(large, Pid)
let playerMs = float((getMonoTime() - t0).inNanoseconds) / 1e6 / 20.0
echo &"#28 egress, 262144 cells x 6 players x 40 entries: GM {gmMs:.3f} ms, player {playerMs:.3f} ms"
check gmMs <= 7.5
check playerMs <= 7.5
# The same pass at the v1 size must be cheaper still, never a cliff: the cost follows the
# frames, not the explored cells (before the fix the two sizes differed by ~20x).
t0 = getMonoTime()
for i in 0 ..< 20: sink += gmPass(small)
let smallMs = float((getMonoTime() - t0).inNanoseconds) / 1e6 / 20.0
echo &"#28 egress, 16384 cells x 6 players x 40 entries: GM {smallMs:.3f} ms"
check smallMs <= gmMs * 3.0 + 0.5
check sink >= 0