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
+6 -4
View File
@@ -162,10 +162,12 @@ proc allIds(): seq[string] =
app.tokens.mapIt(it.id) & app.characters.mapIt(it.id)
proc egressContext(): views.Context =
## A read-only borrow of the world and every player's sight state. The seqs and tables are shared
## by reference and only read before egressFrames returns, so no copy is needed.
views.Context(scene: app.scene, tokens: app.tokens, characters: app.characters,
reveals: app.reveals, encountered: app.encountered, visions: app.visions)
## Six addresses, no copies (#28): the App owns the world and every player's sight state, and the
## egress borrows them for the pass. Building this used to copy `visions` (a whole explored
## `HashSet` per player) and the two-level `encountered` table on every mutation, under the global
## lock; now it cannot depend on how much a player has explored. Caller holds the lock (4.3), so
## the borrow is one consistent state for the whole fan-out.
views.contextOf(app.scene, app.tokens, app.characters, app.reveals, app.encountered, app.visions)
proc pruneKnown() =
## A closed connection's `known` table must not outlive it.
+79 -17
View File
@@ -121,8 +121,24 @@ type
fresh*: seq[(int, int)]
Context* = object
## Everything the egress needs, and nothing it may modify: the world plus every player's runtime
## sight state (read-only; the other players' entries are only reachable by a fault build).
## A read-only *borrow* of the world and every player's runtime sight state (DESIGN 4.2/4.3;
## #28). Every field is a pointer, so building a Context copies nothing: no `PlayerVision`, no
## explored `HashSet`, no `Table`, however large the explored sets grew. `main.egressContext`
## points it at the App's fields (stable for the process lifetime) while it holds the global
## lock, so the whole egress pass reads one consistent state.
##
## The templates below keep the field syntax (`ctx.tokens`, `ctx.visions[pid]`) at every use
## site; a settable template target also keeps `ctx.visions[pid].explored` an lvalue.
pScene*: ptr SceneRec
pTokens*: ptr seq[TokenRec]
pCharacters*: ptr seq[CharacterRec]
pReveals*: ptr Reveals
pEncountered*: ptr Encountered
pVisions*: ptr Table[int, PlayerVision]
ContextStore* = object
## Owning storage with the same six fields, for tests and fixtures (`borrow` hands out a
## Context over it). The server never uses it: `App` owns the world and hands out pointers.
scene*: SceneRec
tokens*: seq[TokenRec]
characters*: seq[CharacterRec]
@@ -138,6 +154,39 @@ type
vision*: string ## the last `vision` payload sent, "" = never
visionSent*: bool
template scene*(ctx: Context): untyped = ctx.pScene[]
template tokens*(ctx: Context): untyped = ctx.pTokens[]
template characters*(ctx: Context): untyped = ctx.pCharacters[]
template reveals*(ctx: Context): untyped = ctx.pReveals[]
template encountered*(ctx: Context): untyped = ctx.pEncountered[]
template visions*(ctx: Context): untyped = ctx.pVisions[]
proc contextOf*(scene: var SceneRec, tokens: var seq[TokenRec],
characters: var seq[CharacterRec], reveals: var Reveals,
encountered: var Encountered,
visions: var Table[int, PlayerVision]): Context =
## Six addresses, not six copies: this is the whole cost of building an egress context (#28).
Context(pScene: addr scene, pTokens: addr tokens, pCharacters: addr characters,
pReveals: addr reveals, pEncountered: addr encountered, pVisions: addr visions)
proc borrow*(store: ref ContextStore): Context =
## The test/fixture entry point: a heap store outlives the Context that points into it.
contextOf(store.scene, store.tokens, store.characters, store.reveals, store.encountered,
store.visions)
proc visionAt(ctx: Context, playerId: int, fallback: var PlayerVision): ptr PlayerVision =
## One player's live sight state, borrowed: never a `getOrDefault` copy (#28). A player with no
## sight state (never connected) gets `fallback`, an empty record the caller owns, so no GC'd
## global is read from a `{.gcsafe.}` handler.
if ctx.visions.hasKey(playerId): addr ctx.visions[playerId]
else: addr fallback
proc visibleIds(ctx: Context, playerId: int, pv: ptr PlayerVision): HashSet[string] =
## The visibility rule once per recipient per frame: every encountered entry's `grey` is then a
## set test, not a token scan plus a polygon test per entry (#28).
for t in ctx.tokens:
if pv[].visibleTo(t, playerId): result.incl t.id
# ---------------------------------------------------------------------------------------------------
# Typed views
@@ -157,10 +206,13 @@ proc characterOf(ctx: Context, t: TokenRec): Option[CharacterRec] =
proc greyFor*(ctx: Context, playerId: int, entityId: string): bool =
## DESIGN 8 `encountered.grey`: the token is no longer in that player's view, whether because it
## moved away, was removed, or became `gm_only`. The entry stays either way.
## moved away, was removed, or became `gm_only`. The entry stays either way. This is the
## single-entry form (tests, and a caller holding one id); a view builds `visibleIds` once instead
## of calling this per entry (#28).
let idx = tokenIndex(ctx.tokens, entityId)
if idx.isNone: return true
not ctx.visions.getOrDefault(playerId).visibleTo(ctx.tokens[idx.get], playerId)
var fallback: PlayerVision
not visionAt(ctx, playerId, fallback)[].visibleTo(ctx.tokens[idx.get], playerId)
proc gmView*(ctx: Context): GmView =
result.tokens = newSeqOfCap[GmTokenView](ctx.tokens.len)
@@ -192,15 +244,20 @@ proc gmView*(ctx: Context): GmView =
for pid in ctx.encountered.keys: pids.add pid
pids.sort()
for pid in pids:
# #28: one visibility pass per player's list, then a set test per entry.
var fallback: PlayerVision
let visible = visibleIds(ctx, pid, visionAt(ctx, pid, fallback))
var entries: seq[EncounteredView]
for eid, e in ctx.encountered[pid]:
entries.add EncounteredView(id: eid, name: e.entryName, grey: ctx.greyFor(pid, eid))
entries.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible)
result.encountered.add GmEncounteredView(player: pid, entries: entries)
proc playerView*(ctx: Context, playerId: int): PlayerView =
var pv = ctx.visions.getOrDefault(playerId)
# A borrowed pointer, not `getOrDefault`: the explored set is never copied (#28).
var noSight: PlayerVision
let pv = visionAt(ctx, playerId, noSight)
for t in ctx.tokens:
if not pv.visibleTo(t, playerId): continue
if not pv[].visibleTo(t, playerId): continue
let mine = t.owner == playerId
let ch = ctx.characterOf(t)
let names = subjectNamesOf(t, ctx.characters)
@@ -227,9 +284,11 @@ proc playerView*(ctx: Context, playerId: int): PlayerView =
actualName: c.actualName,
propsPublic: objectOf(c.props[pbPublic]),
propsOwner: objectOf(c.props[pbOwner]))
for eid, e in ctx.encountered.getOrDefault(playerId):
result.encountered.add EncounteredView(id: eid, name: e.entryName,
grey: ctx.greyFor(playerId, eid))
if ctx.encountered.hasKey(playerId):
# #28: one visibility pass for the whole list.
let visible = visibleIds(ctx, playerId, pv)
for eid, e in ctx.encountered[playerId]:
result.encountered.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible)
when defined(leakfault):
# Negative controls (DESIGN 10.3): add what the honest rule just refused, so the harness proves
# it would notice. Never a second copy of the visibility rule.
@@ -250,11 +309,11 @@ proc playerView*(ctx: Context, playerId: int): PlayerView =
else: newJObject()))
if faultActive("hidden"):
for t in ctx.tokens:
if t.owner != playerId and not t.gmOnly and not pv.insideAny(t.pos):
if t.owner != playerId and not t.gmOnly and not pv[].insideAny(t.pos):
result.tokens.add leakedView(t)
if faultActive("gmOnly"):
for t in ctx.tokens:
if t.gmOnly and t.owner != playerId and pv.insideAny(t.pos):
if t.gmOnly and t.owner != playerId and pv[].insideAny(t.pos):
result.tokens.add leakedView(t)
if faultActive("withhold") and result.tokens.len > 1:
for i in countdown(result.tokens.high, 0):
@@ -308,8 +367,8 @@ proc playerView*(ctx: Context, playerId: int): PlayerView =
if ch.isNone or ch.get.owner == playerId: continue
for v in result.tokens.mitems:
if v.id == t.id: v.cpropsPublic = objectOf(ch.get.props[pbOwner])
result.polys = pv.polys
result.fresh = pv.fresh
result.polys = pv[].polys
result.fresh = pv[].fresh
# ---------------------------------------------------------------------------------------------------
# Frames. These builders are the only producers of state frames in the server.
@@ -537,7 +596,8 @@ proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false)
var polysJson = visionPolyJson(view.polys)
when defined(leakfault):
if faultActive("otherVision"):
let other = ctx.visions.getOrDefault(ctx.otherPlayerId(r.playerId))
var otherStore: PlayerVision
let other = visionAt(ctx, ctx.otherPlayerId(r.playerId), otherStore)[]
for p in other.polys:
var pts = newJArray()
for q in p.pts: pts.add %*[int(round(q.x)), int(round(q.y))]
@@ -548,14 +608,16 @@ proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false)
result.add %*{"t": "vision", "polys": polysJson}
if resync:
result.add exploredFullFrame(ctx.visions.getOrDefault(r.playerId).exploredFull(ctx.scene))
var noSight: PlayerVision
result.add exploredFullFrame(visionAt(ctx, r.playerId, noSight)[].exploredFull(ctx.scene))
elif view.fresh.len > 0:
var fresh = view.fresh
when defined(leakfault):
if faultActive("explored"):
fresh.add (ctx.scene.cols - 1, ctx.scene.rows - 1)
if faultActive("otherExplored"):
let other = ctx.visions.getOrDefault(ctx.otherPlayerId(r.playerId))
var otherStore: PlayerVision
let other = visionAt(ctx, ctx.otherPlayerId(r.playerId), otherStore)[]
fresh.add other.exploredFull(ctx.scene)
result.add exploredFreshFrame(fresh)
+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