docs: add Q13/Q20 research notes
Q13: mummy slow WebSocket clients (pin 01deb1f), option analysis. Q20: Nix packaging of the Nim server (buildNimPackage, nim_lk lock, NixOS module). Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
# Q13: mummy slow WebSocket clients (pin 01deb1f)
|
||||
|
||||
Question (docs/DESIGN.md §4.3, Q13): how mummy queues WebSocket sends per connection; whether app code can see queue depth, get backpressure, close slow clients; ping/pong and timeouts; thread model; hooks; what later mummy commits change; feasibility of an app-level bounded per-client outbox with coalescing vs patching mummy vs other. Also checks the HANDOFF "mummy: unbounded send queue" note.
|
||||
|
||||
Pin: `guzba/mummy` `01deb1ff694988635c7bf0f24f6088a0bdf6db5d` (2026-04-29, "Revert ..."). Read from a fresh clone of `https://github.com/guzba/mummy` at that commit. All line numbers below refer to that commit. Base link: `https://github.com/guzba/mummy/blob/01deb1ff694988635c7bf0f24f6088a0bdf6db5d/`. Local copy: `/tmp/claude-1000/-home-davide-Projects-GDR-FFF-vtt/fb922d93-7ea6-4746-9a92-5070f98248eb/scratchpad/mummy/pin/src/mummy.nim`. Nim 2.2.12 stdlib used to check `==`/`hash` and epoll error mapping.
|
||||
|
||||
## TL;DR
|
||||
|
||||
1. Send path: `WebSocket.send` appends to one server-wide `sendQueue` (`src/mummy.nim` L262-291, L105). The IO thread drains that whole deque in one step into a per-socket `DataEntry.outgoingBuffers` (L1230-1250, L133). That per-socket deque is unbounded and is where backlog actually accumulates.
|
||||
2. App code cannot read per-socket queue depth or bytes pending. The exported API is `send`, `close(ws)`, `respond`, `upgradeToWebSocket`, `serve`, `close(server)`, `newServer`, `waitUntilReady`, `responded`, and nothing else (grep of `^proc .*\*`).
|
||||
3. No backpressure. `send` never blocks or fails. Nothing reports writable state to the handler (PR 146 adds this only for response streams, not WebSockets).
|
||||
4. Slow clients cannot force-close. `close(ws)` only appends a Close frame to the same per-socket FIFO (L293-311, L1248), so a stuck client never receives it. The socket closes only on: peer Close reply, EOF/send error/`Error` event (L1317, L1336, L1358-1362), or a 10 s "close timeout" check that runs only when the socket receives data (L596-597).
|
||||
5. Slow clients do not block other clients. Writes are non-blocking, one `send()` per writable event per socket in a single select loop (L1340-1362). The cost of a slow client is its own memory.
|
||||
6. Ping/pong: mummy never sends a Ping and never auto-replies to one. Ping/Pong arrive at the app as `MessageEvent` with `kind` Ping/Pong (L734-736, L752). `send(..., kind = Ping/Pong)` exists (L262-281). There are no timers, idle timeouts, or connection caps. `maxMessageLen` = 64 KB (L1479) is the only size bound on inbound frames.
|
||||
7. Thread model: one IO thread runs `loopForever` (L1150, select at L1164, `-1` timeout). Workers number `countProcessors()*10` (L1476, L1534). WebSocket events are serialized per connection by `websocketClaimed` (L107, L464-520). The inbound per-socket event queue is also unbounded (L108, L551-573).
|
||||
8. Hooks: `handler`, `websocketHandler`, `logHandler` (L1472-1480). No per-socket hooks, no metrics, no close-reason callback. `CloseEvent` fires on every socket teardown (L1393-1404), which is enough to count connections.
|
||||
9. Later commits: none on `master` after the pin (origin/master = 01deb1f, 2026-04-29). `src/` is byte-identical to tag `0.4.8`. Open PR #146 (2026-05-19) adds response-stream writable backpressure and explicitly leaves WebSocket internals alone. Issue #141 (Slowloris) was closed as "non-issue ... used behind a reverse proxy".
|
||||
10. Feasible without patching mummy: an app-level, per-connection outbox that caps bytes in flight. Use server-solicited Ping(seq) and client Pong echoes (RFC 6455 §5.5.2/5.5.3, WHATWG "Ping and Pong frames") as acks, coalesce latest state per key, and stop feeding a lagging client. Not achievable without a patch: a deterministic forced disconnect, or a visible per-socket queue depth. The HANDOFF note is correct in substance but overstated in location (see Corrections).
|
||||
|
||||
## Findings with sources (pin 01deb1f)
|
||||
|
||||
### A. Data structures
|
||||
- `WebSocket` = `{server: Server, clientSocket: SocketHandle, clientId: uint64}` (L63-66). Identity is (ptr, fd, random id).
|
||||
- `clientId = server.rand.next()` per accepted socket (L1312). Fd reuse is guarded by comparing `clientId` (L1193, L1242).
|
||||
- `ServerObj`: `sendQueue: Deque[OutgoingBuffer]` + `sendQueueLock` (L105-106); `websocketClaimed`, `websocketQueues: Table[WebSocket, Deque[WebSocketUpdate]]`, `websocketQueuesLock` (L107-109).
|
||||
- `DataEntry` (per socket, IO-thread owned): `outgoingBuffers: Deque[OutgoingBuffer]` (L133), `sendsWaitingForUpgrade: seq[OutgoingBuffer]` (L136), `closeFrameQueuedAt: float64`, `closeFrameSent`, `upgradedToWebSocket` (L120-137).
|
||||
- `OutgoingBuffer` = header + payload string + `bytesSent` (L157-162).
|
||||
- Hashing: `WebSocket` is a Table key (L107-108) and is hashed in `$` (L179). Nim 2.2 `std/hashes` provides a generic `hash[T: tuple|object]` (`nim/lib/pure/hashes.nim` L666) and `system.==` is generic for objects (`nim/lib/system.nim` L1981). So the pinned type hashes and compares field-wise. This contradicts the HANDOFF/README/DESIGN claim "no ==/hash, keyed by raw bytes" (see Corrections).
|
||||
|
||||
### B. Send path (app -> wire)
|
||||
- `send*` builds the frame (Text/Binary/Ping/Pong opcode, L268-280) and does `addLast` on the global `sendQueue` under `sendQueueLock`. It triggers the IO select event only when the queue was empty (L285-291). No size check, no return value, no failure mode.
|
||||
- `close*(ws)` appends a Close frame to the same queue (L293-311). Messages queued before it are not discarded.
|
||||
- IO loop drain: `if sendQueuedTriggered` moves every frame from `sendQueue` into the target socket's `outgoingBuffers` (L1230-1250). Frames for a socket that is not upgraded yet go to `sendsWaitingForUpgrade` (L1257). Frames for a socket that already sent a Close go to "Dropped message after WebSocket close" (L1246, `closeFrameQueuedAt > 0`).
|
||||
- Write path: on `Write` readiness, one `send()` of the head buffer (buffer1 then buffer2) per select iteration (L1340-1362). `bytesSent > 0` is required; otherwise the socket is marked for closing (L1358-1362). Interest is `{Read, Write}` while buffers exist and `{Read}` otherwise (L1109).
|
||||
- `afterSend` pops fully-sent buffers (L1091-1110). Its `isCloseFrame` branch sets `closeFrameSent`.
|
||||
- Reads are never paused. Interest for upgraded sockets is always `Read` (L1315, L1109).
|
||||
|
||||
Conclusion: the "one server-wide deque" in HANDOFF/README is only the entry point. The IO thread empties it every iteration, so backlog grows in per-socket `outgoingBuffers` (L1248), which app code cannot see.
|
||||
|
||||
### C. Backpressure and slow-client control
|
||||
- None to the app. `send` cannot block, fail, or report depth. No writable callback for WebSockets. No API to drop by key or cap bytes.
|
||||
- `close(ws)` is not forced. It queues a Close frame behind the backlog (L1248 / L1220). The socket is closed only when:
|
||||
- the client's Close reply arrives while `closeFrameQueuedAt > 0` (`afterRecvWebSocket`, opcode 0x8 branch, L729-730);
|
||||
- recv returns 0 or send returns <= 0, or the selector reports `Error` (EPOLLERR/EPOLLHUP, nim stdlib `ioselectors_epoll.nim` L400-411) (L1317-1318, L1336-1337, L1358-1362);
|
||||
- a frame arrives more than 10 s after the Close was queued (L596-597). This check runs only when the socket receives data.
|
||||
- Consequence: a client that stops reading and stops sending keeps its socket and its whole backlog until the kernel reports a TCP error. Nothing in mummy times this out. Upstream explicitly declines to add timeouts (issue #141, below).
|
||||
- Connection cap: none. `clientSockets` is only tracked (L1309, L1392). An app-level counter is needed (count `OpenEvent` L1213 and `CloseEvent` L1402).
|
||||
- Inbound: `postWebSocketUpdate` appends every decoded message to an unbounded per-socket deque (L551-573, L108). Frame size is capped by `maxMessageLen` = 64 KB (L658, L1479). Message count is not capped, so a flooding client grows server memory on the inbound side too.
|
||||
|
||||
### D. Ping/pong and timeouts
|
||||
- No automatic Pong reply and no server-initiated Ping. Ping/Pong frames are decoded and delivered to the app as `MessageEvent` (L734-736, L752). The app must reply to client Pings itself.
|
||||
- Control-frame payload > 125 bytes is rejected on receive (L654). `send(kind=Ping)` does not check the 125-byte limit, so the app must keep ping payloads <= 125 bytes (RFC 6455 §5.5).
|
||||
- Pong from peer is a normal message with `kind == Pong` and the echoed payload. Usable as an ack, see Options.
|
||||
- No idle, read, header, body, or keep-alive timeouts (issue #141 confirms; maintainer closed it as non-issue because mummy sits behind a reverse proxy).
|
||||
- `waitUntilReady` only waits for startup (L1546-1560). No timer facility exists anywhere in the module.
|
||||
|
||||
### E. Thread model
|
||||
- One IO thread: `serve()` runs `loopForever` on the calling thread (L1414-1470, L1150). All socket IO, accept, framing decode, and the `sendQueue` drain happen there. Upstream README says the same (`README.md` L35 at pin).
|
||||
- Worker threads: `countProcessors()*10` by default (L1476, L1534-1535). They run HTTP handlers and WebSocket handlers (L464-545). WebSocket handlers for one connection never run concurrently (`websocketClaimed`, L481-495, L508).
|
||||
- `send`, `close(ws)` and `respond` are safe from any thread: they take a lock and call `trigger` (L286-291, L306-311). An app timer thread can call `send(kind=Ping)` directly.
|
||||
- Sends to a closed connection are silently dropped (L1260-1262 "Dropped message to disconnected client", debug log only).
|
||||
|
||||
### F. Hooks
|
||||
- `newServer(handler, websocketHandler, logHandler, workerThreads, maxHeadersLen=8 KB, maxBodyLen=1 MB, maxMessageLen=64 KB, tcpNoDelay=true)` (L1472-1480).
|
||||
- Events: `OpenEvent` after the 101 is queued (L1213), `MessageEvent`, `ErrorEvent` (only if no Close was sent, L1399-1400), `CloseEvent` (L1402).
|
||||
- `logHandler` receives debug messages such as "Dropped message after WebSocket close" and "Dropped message to disconnected client" (L1218, L1260-1262). Usable as a crude drop signal, not a metric.
|
||||
- No per-socket hooks, no queue metrics, no write-ready callback.
|
||||
|
||||
## Later commits and related upstream work
|
||||
|
||||
- Upstream `master` tip = `01deb1f` (2026-04-29). There are 0 commits on `master` after the pin. The 7 commits between tag `0.4.8` (`77a7563`) and the pin are "whatever / noise / revert" and do not change `src/`. `git diff 0.4.8 01deb1f -- src` is empty.
|
||||
- Tags `0.4.6`, `0.4.7`, `0.4.8` exist upstream. `docs/DESIGN.md` L48 says "no upstream tags", which is wrong. The pin's `src/` equals tag `0.4.8`.
|
||||
- Experiment branches `experiments1/2/4` (Nov-Dec 2022, pre-0.4) are not relevant to current code. Checked by subject line only.
|
||||
- PR #146 (open, not merged, head `be6bbfa9de9ff6033845ee6fd8b52ef29696a490`, 2026-05-19) https://github.com/guzba/mummy/pull/146 adds response streaming with "writable-event backpressure" (`StreamWritable`, one chunk in flight). Its body says WebSocket internals are "intentionally left close to upstream". `send`/`close(ws)` are unchanged in its diff. It does not give WebSocket backpressure.
|
||||
- Issue #141 https://github.com/guzba/mummy/issues/141 (Slowloris, closed 2026-03-10). Maintainer comment (guzba, 2026-03-10): "Non-issue. Mummy is used behind a reverse proxy for TLS termination which is concerned with the above." Implies upstream expects timeouts from a proxy.
|
||||
- Issue #142 (pipelined HTTP responses out of order) is closed and HTTP-only; not relevant.
|
||||
|
||||
## Standards (for the design)
|
||||
|
||||
- RFC 6455 §5.5.2: "Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response"; §5.5.3: the Pong must echo the Ping's application data. https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2 (text checked at `https://www.rfc-editor.org/rfc/rfc6455.txt` L2036-2062).
|
||||
- WHATWG WebSocket Standard, "Ping and Pong frames": pings/pongs "are not currently exposed in the API"; "servers will solicit pongs whenever appropriate for the server's needs". https://websockets.spec.whatwg.org/#ping-and-pong-frames
|
||||
- WHATWG exposes `WebSocket.bufferedAmount` in the browser (client side only). It gives the client no server-side signal. https://websockets.spec.whatwg.org/#dom-websocket-bufferedamount
|
||||
|
||||
Consequence: browsers answer server Pings with Pongs in the network stack, without JS. A server-solicited Ping/Pong echo is a valid ack channel for current browsers without any client code change.
|
||||
|
||||
## Corrections to repo docs
|
||||
|
||||
- `prototype-server-vision/HANDOFF.md` L29 and `prototype-server-vision/README.md` L110-114: "one unbounded server-wide deque" is the entry point only. The backlog is per socket (`outgoingBuffers`, pin L133, L1248). The "no ==/hash, keyed by raw bytes" caveat is stale at this pin (generic field-wise `hash`/`==` apply).
|
||||
- `docs/DESIGN.md` L48: "no upstream tags" is wrong. Tags `0.4.6`-`0.4.8` exist, and the pin's `src/` equals `0.4.8`.
|
||||
- `docs/DESIGN.md` L192 and H18 (L500): the mitigation "close when sent - acked-by-pong exceeds a bound" cannot be executed as an immediate close at this pin. `close(ws)` queues behind the backlog. The workable action is to stop feeding the client and close once the peer responds or sends data.
|
||||
- `docs/DESIGN.md` L192: "per-connection byte counter we maintain ourselves" is fine, but acks must come from server-solicited Pings. WHATWG says user agents must not use pings or unsolicited pongs to aid the server, so the server must solicit every Pong it relies on. JS cannot send or observe Pongs.
|
||||
|
||||
## Options
|
||||
|
||||
Each option is judged on the owner's requirements: bounded per-client memory, latest-state-wins for vision/positions, no slow client hurting others, and the ability to disconnect. Effort figures are rough estimates, not measured.
|
||||
|
||||
### Option A: app-level bounded outbox + ping-acked send window (no mummy patch)
|
||||
Design:
|
||||
- Per connection (app-assigned `connId` at upgrade; app table keyed by `connId`, not by `WebSocket`): `inFlightBytes`, a FIFO `mustQueue` of bytes-capped messages, and a `latest: Table[key, state]` map for state messages.
|
||||
- Send window: call `ws.send` only while `inFlightBytes < W` (e.g. 64 KB). Timer thread sends `Ping(seq)` (<= 125 B payload) every T (e.g. 250 ms to 1 s). On `Pong(seq)` from the peer, subtract the bytes sent before that ping. Mummy's per-socket FIFO makes this exact.
|
||||
- Coalescing: vision, position and fog state are keyed by (player, token). Keep only the latest per key. The prototype's current diff-at-send-time (`known` map) must change to diff-at-flush-time against last-delivered state. Otherwise dropping a queued delta silently diverges the client.
|
||||
- Overflow: if `mustQueue` exceeds its cap, or no Pong for X s, stop feeding that client (keep the connection). On recovery send a full snapshot. The prototype already resets on `hello`.
|
||||
- Disconnect: call `close(ws)`. It takes effect only when the peer reads or sends data. A dead peer that also sends nothing keeps its FD until the kernel reports a TCP error (not measured here).
|
||||
- Connection cap: count OpenEvent/CloseEvent; reject at upgrade.
|
||||
- Inbound: app must rate-limit messages per connection in `websocketHandler` (count on enqueue). Mummy's inbound queue is unbounded.
|
||||
|
||||
Trade-offs: no mummy patch, no fork; the thread-safety contract holds (`send` is locked, L286-291). Costs: an ack timer thread, ~2-byte-plus overhead per ping, and no forced disconnect (FD may linger). Works with unmodified browsers. Non-browser clients that ignore Pings just get throttled (safe default). Estimate: ~150-250 lines plus tests. Does not add visibility into mummy's real queue (the app's window bounds it instead).
|
||||
|
||||
### Option B: fork mummy at the pin and add a small hook set
|
||||
Needed changes (all in `src/mummy.nim`):
|
||||
- Per-socket pending-bytes counter, updated on enqueue (L286-291, L306-311) and on fully-sent in `afterSend` (L1091-1110). Expose `pendingBytes(ws)`.
|
||||
- `send` returns `bool` or drops above `maxPendingBytes`.
|
||||
- `forceClose(ws)`: enqueue an IO-thread event (same pattern as `sendQueued`) that sets `needClosing` for that socket. CloseEvent already fires from the teardown path (L1393-1404).
|
||||
- Optional: inbound cap per socket (L551-573).
|
||||
|
||||
Trade-offs: fixes the real gaps (forced close, visible depth, hard cap). Costs: changes the IO loop (L1150-1410), the riskiest code in the library; fork maintenance and a nimble URL pin in place of a bare commit; a regression surface for everything mummy does. Upstream PR #146 shows writable-backpressure is acceptable upstream for streams, but WebSockets were left out on purpose, so upstream acceptance is uncertain. Estimate: ~100-200 lines plus tests. Use Option A's `connId`/outbox API so the patch can be swapped in later.
|
||||
|
||||
### Option C: rely on a front proxy for slow-client enforcement
|
||||
Upstream's position (issue #141) assumes a reverse proxy handles timeouts. A proxy with per-client write/send timeouts could close stuck clients. Not evaluated here: no nginx WebSocket config was read, and whether the WS path goes through nginx is an open question (DESIGN has nginx for static and tiles only). Needs its own research.
|
||||
|
||||
### Option D: switch WebSocket library
|
||||
Not evaluated. Would need a separate research pass against each candidate's pinned source. Not recommended before A is tried, because A removes the risk that motivates the switch.
|
||||
|
||||
### Option E: caps only (DESIGN v1 mitigations, no slow-client logic)
|
||||
Connection cap, size limits, pong timeout detection without enforcement. Memory per stuck client grows until the process restarts or the kernel errors the socket. Illustrative arithmetic only: the prototype's ~3.4-3.7 KB per vision delivery (`prototype-server-vision/HANDOFF.md`, README) at an assumed 10 deliveries/s is ~2 MB per minute per stuck client. The 10/s is an assumption, not measured.
|
||||
|
||||
## Recommendation
|
||||
|
||||
Option A for M5, with a `connId` + outbox module behind a narrow interface. Move to Option B only if forced disconnect or visible depth proves necessary in load tests (the prototype's leak harness can measure `outgoingBuffers` growth via RSS). Update DESIGN H18/L192 and the HANDOFF/README wording per Corrections. Do not patch mummy before measuring A.
|
||||
|
||||
## Not verified / open
|
||||
|
||||
- No code was compiled or run against mummy. Claims come from reading the pinned source, the Nim 2.2.12 stdlib, and the RFC/WHATWG text.
|
||||
- Browser behaviour (automatic Pong) is taken from RFC 6455 and the WHATWG text, not tested in a browser.
|
||||
- TCP error timing for dead peers (kernel retransmit limits) not measured.
|
||||
- Option C (nginx) and D (other libraries) not researched.
|
||||
- Upstream issues/PRs were searched via `gh api` for "backpressure", "slow client", "ping", "send queue", "timeout websocket". Results listed above; not exhaustive.
|
||||
- Not committed, not pushed, DESIGN.md not edited.
|
||||
Reference in New Issue
Block a user