Files

406 lines
26 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# FFF_vtt: an outside analysis of requirements, design and engine
Written 2026-11-17 against `main` at `409d2c8` (DESIGN draft v0.27, M1 to M3 done, M4 client not
started). I read the design, glossary, research notes, prototype reports and the whole server, and
skimmed the tests, tools and committed gate logs. I did not run anything. The numbers come from
the committed logs in `results/` and from the research notes.
Evidence tags used below:
- **[measured]**: a number from a committed log or research note.
- **[read]**: I saw it in the code or the docs.
- **[inferred]**: my estimate. Treat it as a hypothesis to measure, not a fact.
---
## 1. Verdict in one page
**The core idea is right, and it is rare.** "The server alone decides what each player sees", with
one egress path and typed per-recipient views, is the correct architecture for a VTT that really
hides information. Most VTTs send everything and hide it in the client. This project doesn't, and
it has built the tests to prove it: an independent leak checker, fault-injection builds and 63
mutations. That is the strongest part of the project, and it is better engineered than most
commercial VTTs on this specific point.
**The compute engine is not the problem.** One visibility polygon costs about 0.04 ms, and a whole
mutation about 0.7 ms [measured]. One GM and six players produce a few intents per second. The CPU
has a margin of three to four orders of magnitude. For this load, "the most efficient engine" does
not mean faster geometry. It means:
1. lower tail latency (the slowest acks come from SQLite COMMIT and lock queueing, not from vision),
2. fewer wire bytes and fewer tile requests on a phone,
3. no latent concurrency bugs,
4. less code and fewer documents for one person to carry.
**The three biggest problems, in order:**
1. **There is still no client, and the design keeps growing.** Six milestones of server work, then
eight design decisions (#41 to #48: heights, thick walls, one-way walls, windows, presets,
markers) were added before anyone has played a session in a browser. The riskiest unknowns are
all on the client side: cold tile load on the phone, iOS Safari, real map sizes. None of them is
retired.
2. **A real data race in the threading model** (section 4.1). The server runs mummy's worker
threads over shared ORC-managed `JsonNode`s that are not protected by the lock. Reference counts
in Nim's ORC are not atomic, so this can corrupt memory. It is rare and hard to reproduce, and it
is exactly the kind of bug that shows up once in a live session and never in tests.
3. **The design document has outgrown its author.** `docs/DESIGN.md` is 270 KB of layered,
partly superseded decisions, with no ADRs. It is now the main cost of every change, and that
includes changes made by agents.
**My recommendation, short form:** freeze the wall-feature scope at what thin-segment geometry can
do cheaply. Fix the threading model by moving to a single world thread. Make the vision pass
incremental and cheaper using the known algorithmic fixes. Then build the M4 client and measure on
the phone before designing anything else.
---
## 2. What the project is, as I understand the requirements
- Self-hosted browser VTT for **one table**: 1 GM and up to 6 players, one scene in v1.
- **Server-authoritative sight.** Walls and doors are GM-only data. Each player receives only the
tokens inside their vision polygons, their own polygons, and their own explored cells. Map art is
served as 32 px tiles, gated per player by explored cells. No secret ever reaches a client
"hidden".
- Movement is validated on the server (swept circle, step cap, uniform nack) so that players cannot
map walls by probing.
- Stack, marked [FIXED] in the design: Nim 2.2 + mummy 0.4.8 + db_connector/SQLite WAL on the
server; TypeScript + PixiJS v8 on the client; nginx in front (TLS, `X-Accel-Redirect` tiles);
NixOS/devbox.
- The target device includes a 5-year-old Android phone (Note 10), which sets the client budget.
These requirements are coherent. The single-table scale is the most important one and it should
drive every trade-off. Several parts of the design read as if they were sized for a bigger system
than this.
---
## 3. What is good (keep it)
| Idea | Why it is good |
|---|---|
| **Single egress, typed views** (`views.nim`: `GmView`/`PlayerView`, the `Known` diff) | A forbidden field cannot leak because it does not exist in the player type. This is the right way to enforce "the server decides". |
| **State-based diffs, not event replay** | Frames describe the current state, so reordering, dropped frames and a resync all converge. This choice already saves the current threading model from its ordering gaps (section 4.2). |
| **Independent leak checker + fault builds + mutation testing** | Proof that the rule holds, not just a belief. Fault injection is compiled out of shipped binaries. Few projects of any size do this. |
| **Measured-evidence discipline** ([MEASURED]/[INFERRED] tags, prototypes, research notes) | Decisions are traceable. Several research notes caught real errors in the design. |
| **Uniform move nack + step cap** | Closes the "probe the walls with moves" channel at low cost. 24/24 probing runs are identical [measured]. |
| **Explored stored as 64×64-cell chunk bitmaps** | Compact, bounded writes, simple to restore. |
| **Random 72-bit token ids** | Counted ids would leak hidden tokens through the gaps. A small detail, and it is right. |
| **Scanline `cellsTouched`** | About 10× faster than the prototype and differential-tested against it [measured]. |
| **Switch-based wall model (#42/#48)** backed by a survey of other VTTs | The model is right. The scope built on top of it is the problem (section 5). |
| **nginx serves tile bytes, Nim only authorises** | Correct split. Nim never reads image files. |
| **Glossary** | Short, precise, useful. Keep it as the vocabulary anchor. |
---
## 4. What is bad or risky (the critique)
Ordered by how much it matters, not by how easy it is to fix.
### 4.1 Data race: shared `JsonNode`s across mummy worker threads [read, not reproduced]
`main.nim` casts the `App` out of a raw pointer so that mummy's worker-thread handlers count as
`{.gcsafe.}`. That silences the compiler check that would have caught the following.
In `wall.add` (`server/main.nim:1846-1872`):
- `flags` is a subtree of `env.node`, the JSON parsed on the worker thread.
- Under the lock, it is stored into `app.scene.walls`, so the global world now references that
node.
- After the lock is released, `wallObjectOf(added.get)` builds a frame that references the same
`flags` node (reference count +1). At the end of `dispatch`, `env`, `candidate` and `added` are
destroyed (reference count −1). Both happen **outside the lock**.
- At the same time, another worker thread can be inside the lock, walking `app.scene.walls` for a
GM resync or `wallsSnapshot`, which touches the same node's reference count.
With `--mm:orc` (`nim.cfg`), reference counting is **not atomic**. Atomic counts exist only under
`--mm:atomicArc`. Two threads updating the same count without synchronisation can lose an update.
The result is a premature free (use-after-free) or a leak. The same pattern applies to `token.*`
flags and props, `scene.set` `extra`, and any `JsonNode` from an intent that ends up in the world.
The probability is low (GM edits are rare and the windows are short). The cost when it happens is a
crash or silent corruption mid-session that no test reproduces. **Fix options**, from quickest to
best:
- Quick: `copy()` every `JsonNode` taken from an intent before it enters the world, and build every
frame that references world state inside the lock.
- Cheap and broad: compile with `--mm:atomicArc`. `JsonNodeObj` is `{.acyclic.}`, so ORC's cycle
collector gives nothing here. Measure the cost first; it is probably small at this load
[inferred].
- Structural (recommended, section 6.1): one world thread owns all ref-managed state, and worker
threads pass it only plain strings.
Related: mummy defaults to `10 × CPU cores` worker threads (`mummy.nim:1476`), and `newServer` is
called without `workerThreads`. On a 16-core machine that is 160 threads competing for one global
lock to serve seven people.
### 4.2 One global lock, two critical sections, two to three transactions per mutation [read]
A mutation runs the handler under `withLock app.dbLock`, releases it, then `settle` takes it again
for encounters, the ack and egress. Between the two sections, another mutation can run in full.
Each section opens its own transactions (`persistExplored`, `recordEncounters`, the row write).
Correctness is saved by the state-based diff, and the design admits the exact ordering is deferred
to the M5 outbox.
- The measured tail is intent→ack p99 4.58 ms, worst ~20 ms, with an unexplained 583 ms spike
earlier [measured]. The research attributes the tail to COMMIT and queueing, not to compute.
- More transactions mean more fsync-shaped tail. One mutation should be one transaction.
- `tileGate` takes the **same global lock** and runs a SQLite session lookup plus SHA-256 **per
tile request** (`main.nim:614-625`). A connect burst is 292 tile requests [measured]. Each one
competes with gameplay mutations for the lock.
- Several paths query the DB under the lock for data that is already in memory (`rosterFrames` →
`allPlayers`, `resyncEveryone` → `playerById`).
### 4.3 The vision pass does far more work than it needs to [read + measured]
None of this matters for latency today (0.27 ms for six polygons [measured]). It matters for thick
walls and dense maps, where the research measured **12.8 ms per polygon and 75.6 ms for a six-token
party** with thick walls on a dense scene [measured].
- **Every ray is tested against all 64 circle segments as well as the walls**
(`geometry.nim:46-68`). The ray's angle tells you which single segment of the 64-gon it can hit,
so one test is enough. That gives the same output and removes most of the work on sparse scenes.
The research estimated a 5-9× saving [inferred there].
- The algorithm is **rays × segments**: 3 rays per endpoint × all walls in the box. Thick walls
multiply both factors (4 edges each), which is why they blow up. An **angular sweep** (sort
endpoints, keep the active walls ordered by distance) is O(n log n) and is the standard solution.
For the dense case (~200 walls in the box) I would expect about 0.1 ms instead of 1.3 ms
[inferred].
- **No caching.** `vision.refresh` recomputes **every** polygon of the player and re-rasterises all
of them, even if only one token moved. `geometryWalls(sc)` copies all walls on every
`computePolys`. `moveScene` copies all walls and tokens on every move and wall edit [read].
- **A wall edit refreshes everyone.** `refreshAll()` recomputes every token of every player,
including tokens 3000 px away from the edited wall.
- Explored is an in-memory `HashSet[int]`, although it is persisted as bitmaps. The tile gate's
"is any cell explored" check would be one bit test on a bitmap.
### 4.4 Egress rebuilds everything, every time [read]
`egressAll` rebuilds the full typed view and every JSON frame for every connection on every
mutation. It compares `JsonNode` trees against `Known`, compares vision as a serialised string, and
resends the **full polygon** on any change (3.4-3.7 KB per move [measured]). `withN` deep-copies
each frame per connection.
At seven users this is affordable. It is still the main cost after COMMIT, and it grows with thick
walls (2.5-3.7× more polygon vertices [measured]). The cheap wins:
- Send integer coordinates (or 0.1 px fixed point), not 17-digit floats. That cuts vision frames
roughly 3-4× [inferred].
- Diff on typed values or a per-entity version counter, not on JSON trees.
- Recompute only the recipients the mutation can affect.
### 4.5 Scope grew before the product exists [read]
v1 started with `wall` | `door`. Decisions #41-#48 add wall heights with see-over, a switch-based
wall model with presets, thick walls, secret and locked doors, windows, one-way walls and player
markers. #49 (wire/schema/migration) and #50 (thick doors and push) are still open.
My honest opinion, per feature:
| Feature | Opinion |
|---|---|
| Secret / locked doors (#46) | **Good.** Cheap (a flag plus the egress rule) and high table value. |
| Windows, one-way walls (#47) | **Good and cheap, if** the vision code is a sweep: they become per-wall predicates (blocks sight from this side / blocks movement but not sight). Expensive in the current ray fan. |
| Presets / switch model (#42/#48) | **Good** as the data model. Keep the preset list short. |
| Player marker | Fine. |
| Thick walls (#45) | **Doubtful for v1.** Highest cost in algorithm, wire bytes and leak-checker rework (its zero-width `clearLine` oracle does not cover thick walls). Most tables are served by thin walls that follow the art. If kept, model them as closed polygons inside a sweep, not as four independent segments in a ray fan. |
| Heights / see-over low walls (#41) | **Bad idea for v1.** No surveyed VTT puts wall height into the sight polygon (Foundry explicitly refused it in core), the semantics are disputed at the table, it needs UI on a phone, and it doubles the leak-oracle burden. Defer it until people have played without it and asked for it. |
UVTT 0.3 import cannot express movement blocking, secret, locked, one-way or windows [read], so
every advanced feature is GM hand-authoring on a phone or desktop client that does not exist yet.
### 4.6 The design document [read]
`docs/DESIGN.md` is 270 KB, draft v0.27. It has lines over 4000 characters, superseded decisions
kept inline next to their replacements, and no `docs/adr/` directory although the agent docs
expect one. The research notes found factual errors in it (mummy "has no upstream tags", and
"close when lag exceeds bound" is impossible at the pin). A document this large is no longer
reliably read in full, by a person or by an agent. That defeats its purpose as the source of truth.
### 4.7 Smaller issues [read]
- **`db_connector` limitations leak into the code:** no NULL binding (so `sqlLitId`/`sqlLit` build
SQL literals, guarded by an alphabet check), no prepared-statement reuse, no transaction API. A
~200-line wrapper over the sqlite3 C API (bind_null, a cached statement table, busy_timeout)
would remove the literals and save CPU on every write.
- **`PRAGMA synchronous` toggled FULL↔NORMAL around each authoring transaction.** It is defensible,
but it adds code and tests for a small difference: in WAL mode, NORMAL only risks the last commits
on power loss, not on a process crash. Low priority. Consider simply FULL everywhere and measure.
- **`dispatch` is one ~1300-line `case`** with field validation written by hand for each intent. A
table-driven schema (field name, type, required, range) would remove most of it and the class of
bugs where one intent forgets a check.
- **The leak checker is less independent than it says.** Its polygon "truth" calls the server's own
`visibilityPolygon`, and its explored check calls the server's `cellsTouched`. Only the
clear-segment sanity check is independent. A wrong polygon would agree with itself. (Section 6.2
turns this into an opportunity.)
- **`walls`-sourced statuses** tell a player that a wall touches a token (leak note 6, still open).
It is minor, but it is a leak by the project's own definition, so either accept it explicitly or
show players a source-free status.
- **mummy 0.4.8:** unbounded send queue, no backpressure, no close codes, no timeouts. The design
knows this; M5 must handle it (section 6.4).
- **Unknowns not retired:** phone cold viewport < 1 s at zoom 1 (unproven; the worst measured cold
load is 3.3 s at zoom 0.5 over HTTP/1.1 [measured]), iOS Safari, real map size and wall count
(Q2), the 583 ms spike, the T11 timing/size side channel (accepted, untested), and where the FFF
rules engine will live.
### 4.8 Tiles at zoom-out [read + measured]
The 32 px tile is the right leak granularity: tile = cell, so an allowed tile shows exactly
explored ground. But the request count grows with 1/zoom²: about 1.3k tiles at zoom 0.5 and about
5k at zoom 0.25 [inferred from the measured 1.3k]. A 16384 px map is 262,144 files, about 1.06 GB
[measured]. There is no lower-resolution pyramid, and a normal one would leak, because a coarse
tile would cover unexplored cells.
---
## 5. Requirements I would challenge
- **"Thick walls and heights in v1"**: covered in 4.5. Defer them.
- **"Close a slow client when lag exceeds a bound"**: impossible as an immediate close at the mummy
pin [research]. Replace it with "stop feeding, then resync" (section 6.4), which the state-based
diff makes easy.
- **"Durability FULL for authoring, NORMAL for the rest"**: correct in spirit, but the
implementation cost is out of proportion to the risk for a home server. Make it one setting.
- **mummy and db_connector as [FIXED]**: keep mummy, since replacing the HTTP layer gains little.
db_connector is worth replacing with a thin direct binding (4.7). Flagging this because it
touches a [FIXED] item.
---
## 6. The engine I would build
This is not a rewrite. Most of the modules are good: `moverules`, `views`, `explored`, `tiles`,
`characters`, `tokens`, `world`. What changes is the plumbing around them in `main.nim`, the vision
algorithm, and how state is published to the tile gate.
### 6.1 Concurrency: one world thread, no global lock
```
mummy workers (few: 4-8) world thread (owns ALL game state)
───────────────────────── ──────────────────────────────────────────────
ws text ─► rate limit ─► (connId, raw string) ──► inbox (MPSC channel, plain strings)
│
├─ parse + validate (table-driven schema)
├─ apply to in-memory world (moverules, …)
├─ ONE SQLite transaction for the whole batch
├─ incremental vision + explored (6.2)
├─ egress diff per affected recipient (6.3)
└─ ws.send(bytes) per connection outbox (6.4)
tile gate (worker) ─► session cache + per-player explored bitmap snapshot
(plain bits, no refs; published by the world thread under a tiny lock
or as an immutable seq swapped atomically)
```
Why this design:
- **No shared refs between threads.** Workers hand over only `string`s. Every `JsonNode` lives and
dies on the world thread. The data race in 4.1 disappears as a category, not as one patched
instance.
- **Ordering is exact by construction.** One thread applies one intent after another, so the M5
"exact per-connection ordering" problem goes away.
- **Group commit.** Intents that arrive while a COMMIT is running are applied together and
committed in one transaction. This attacks the measured tail (COMMIT + queueing) directly. Under a
burst, several acks share one fsync.
- **The tile gate never touches the world or the DB.** It reads a bitmap and an in-memory session
table. Revocation updates the cache from the world thread.
- **The mutation path is easier to reason about**: one loop instead of two critical sections, three
transactions and a borrow-the-world context.
Cost: rewriting `settle`/`egressAll`/`dispatch` plumbing in `main.nim`. Handler bodies move almost
unchanged. Nim's built-in `Channel[string]` or `threading/channels` is enough for the inbox, and
mummy's `ws.send` can be called from any thread.
### 6.2 Vision: sweep, cache, incremental
1. **Now, same output:** test each ray against only the one circle segment in its sector. All
existing geometry tests and the bench still apply unchanged.
2. **Angular sweep** replacing the ray fan: O(n log n) in walls in range. Windows, one-way walls and
secret doors become a per-wall predicate inside the sweep. If thick walls survive, they enter as
closed polygons (only the near face matters for sight, and the research found the near-face
variant costs about the same as thin walls [measured]).
3. **Keep the old ray fan as the leak checker's oracle.** That turns the checker's weakness in 4.7
into real independence: two different algorithms must agree. A single change both speeds up the
engine and strengthens the proof.
4. **Cache per token:** polygon and cell set keyed by `(pos, range, wallsVersion)`. A move
recomputes one polygon, not the player's whole party.
5. **Incremental wall edits:** recompute only tokens whose vision circle overlaps the edited wall's
bounding box.
6. **Uniform grid for walls** (for example 256 px buckets) only if Q2 says maps exceed about 1000
walls. Below that, the bbox cull is enough [measured: 5k sparse is 0.08 ms].
7. **Explored as the bitmap it already is on disk**, not a `HashSet[int]`. Restore is a memcpy, the
tile check is a bit test, and dirty-chunk tracking falls out naturally.
### 6.3 Egress: smaller, cheaper frames
- Integer or fixed-point coordinates on the wire.
- Per-entity version counters. Diff by comparing versions, build JSON only for what changed, and
build each shared frame once, not once per connection.
- Vision: keep full-polygon replacement (it is simple and safe) but quantised. A delta encoding is
not worth the complexity at this scale.
- Only recipients whose view the mutation can affect are visited: the mover's player plus anyone
who could see the token's old or new position.
### 6.4 Slow clients (M5)
mummy gives no queue depth. Use **pong lag** (already recorded) as the signal. When a connection's
lag exceeds a bound, **stop feeding it** and mark it dirty. When it recovers, send `hello` and a
full resync from its `Known` reset. The state-based diff makes the dropped frames harmless. This is
simpler than any outbox with byte accounting and fits the pin's limits.
### 6.5 Persistence
- A thin direct SQLite binding: prepared-statement cache, real NULL binding, `busy_timeout`, one
`transaction` helper.
- One transaction per batch (6.1), and one durability setting.
- Session lookups served from memory, written through.
### 6.6 Tiles
- Keep 32 px tiles and the explored gate.
- **Clamp the minimum zoom in v1** (for example 0.5). That alone bounds the request count.
- Later, if needed: a **per-player overview image** (for example 512 px for a 4096 px map), rendered
from the art and masked by that player's explored bitmap, regenerated when explored grows by more
than N cells. It is leak-free by construction and turns thousands of requests into one.
- Make sure nginx actually runs HTTP/2 to the browser before the phone gate. The h2 benefit is only
inferred so far, and HTTP/1.1 limits a browser to six connections per host.
### 6.7 Expected effect [all inferred, to be measured]
| Metric | Today | After |
|---|---|---|
| Ack p99 | 4.6 ms (worst ~20 ms) | ≈ one COMMIT; bursts share it |
| Polygon, dense 5k | 1.28 ms | ~0.1 ms (sweep) |
| Thick, dense, 6-token party | 75.6 ms | a few ms (sweep, near faces) |
| Vision frame per move | 3.4-3.7 KB | ~1 KB (quantised) |
| Tile request cost | global lock + DB + SHA-256 | `dbLock`-free map lookup + bit test (private mutex) |
| Data-race class | present | gone |
---
## 7. What I would do next, in order
| # | Action | Why now | Size |
|---|---|---|---|
| 1 | Patch the `JsonNode` race: `copy()` intent JSON before storing it, and build frames under the lock (or `--mm:atomicArc`). Set `workerThreads` small. | Memory safety, cheap | S |
| 2 | **Freeze wall scope:** keep secret/locked doors, windows and one-way walls. Defer heights (#41) and thick walls (#45, #50) to after M4 playtests. | Stop growth before the client | decision |
| 3 | Circle-segment fix plus per-token polygon cache. | Same output, big cut | S |
| 4 | Session cache; tile gate off the global lock. | Connect burst vs gameplay | S |
| 5 | **Build M4 client**; run the phone and iOS gates over real nginx h2; clamp the minimum zoom. | Biggest unretired risk | L |
| 6 | World-thread refactor with group commit. | Tail latency, ordering, removes M5 ordering work | M |
| 7 | Angular sweep; keep the ray fan as the leak-checker oracle. | Needed if windows/one-way stay; makes thick walls possible later | M |
| 8 | Split DESIGN.md: a short current spec, ADRs for decisions, and history moved out. | Every future change gets cheaper | M |
| 9 | Thin SQLite binding; table-driven intent schema. | Removes workarounds and repeated validation | M |
| 10 | Slow-client "stop feeding + resync" (M5). | Robustness | S |
---
## 8. Final honest opinion
This is a serious, carefully built server, more rigorous about information leaks than the VTTs
people pay for. The author's instinct to measure before deciding is the project's greatest asset.
The weakness is the mirror image of that strength. Rigor is applied to the server and the design
document, while the thing that decides whether the project succeeds, a playable client on a real
phone at a real table, has not been started. Every week spent designing wall heights or thick-wall
push rules is a week of decisions made without player feedback. Every decision also lands in a
document that is already too large to hold in one head.
The engine needs no heroic optimisation. It needs one structural fix (the world thread, which also
removes a real memory-safety bug), three or four textbook algorithmic fixes it already knows about,
and a scope freeze. After that, the fastest way to make it better is to play with it.