diff --git a/docs/DESIGN-history.md b/docs/DESIGN-history.md index 0b2fb26..aad7e8f 100644 --- a/docs/DESIGN-history.md +++ b/docs/DESIGN-history.md @@ -75,6 +75,9 @@ same numbering. playtest, minimum zoom 0.5, walls statuses accepted, slow-client close superseded by stop-feed + resync, and the DESIGN split note) in 1, 4.3, 5.10, 6.1, 7.4, 13, 14 +- v0.31 records #32 (the dispatch guard: the `internal` refusal code and unconditional rollback on + every unwind path) in 4.2, 6.2, 6.5, 14 + All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN. ## B. HANDOFF traceability (old DESIGN ยง12) @@ -844,6 +847,14 @@ recovery**; only nginx proxy timeouts close a dead peer (4.3). See 1, 4.3, 5.5, +## E. Owner decisions after the split + +Owner also decided 2026-11-20 [FIXED (owner-delegated, 2026-11-20, #32)]: a readable intent that +fails in handling is answered `ack {ok:false, code:"internal"}`, with no detail, and the transaction +helpers roll back on every unwind path (`Defect` included) so the shared connection stays usable. If +the handler's own ack was already enqueued, it stands and no second ack is appended. `internal` is +additive in proto 2. A `Defect` is bounded damage, not a restart policy. See current 4.2, 6.2, 6.5. + ## D. Superseded statements removed from the current spec Each entry quotes the superseded statement (excerpt) and names the surviving rule. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 29d1923..d1712d8 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -402,7 +402,9 @@ Invariants (carry from prototype): relative to other messages is flush order, not mutation order. - Ack after COMMIT (a client never sees a state that a crash can undo, except under `synchronous=NORMAL` power loss, 4.4). -- A failed validation mutates nothing, bumps nothing, persists nothing. +- A failed validation mutates nothing, bumps nothing, persists nothing. A mutation that raises + after its transaction began rolls back on every unwind path, `Defect` included, so the shared + connection never keeps an open transaction (6.5 step 10, #32). - Refusals never echo state: only a refused move of a controlled token acks with its old position (uniform nack, 5.5); every other refusal is an `ack` with a static `code` and no position (6.5). Each intent gets exactly one `ack` (6). @@ -1710,7 +1712,8 @@ view), so deletion and moving away look identical to the player. - Within one proto version: additive only (new optional fields, new message types). The client ignores unknown server message types and unknown fields; the server ignores unknown fields in intents and answers an unknown `t` with `ack {ok:false, code:"unknown-type"}` (or `error - {code:"malformed"}` if there is no `reqId`). + {code:"malformed"}` if there is no `reqId`). A new static refusal code is additive too: a client + that does not know it treats it as a generic refusal (`internal`, 6.5, is the first, #32). - Breaking change -> bump `proto`, document in `docs/` changelog. - **Proto history.** `1` (M3, 2026-11-15): 29 intents, 15 server messages, `wall` records as `kind` + `open` + `flags`. `2` (#49, 2026-11-17): the wall record's typed fields (`thickness`, @@ -1788,6 +1791,12 @@ on any failure. 8. Target lookup. Player senders: a target that is not theirs or does not exist is one and the same `not-allowed` (no existence oracle, T9). GM senders: missing target -> `not-found`. 9. Semantic validation (GM: `invalid`; player move: the uniform nack, 5.5). +10. Handling raises after step 4 (any unwind path, `Defect` included): `ack internal`, unless the + handler's own ack for that `reqId` was already enqueued, in which case that ack stands and no + second one is appended [FIXED (owner-delegated), 2026-11-20, #32]. The failure is logged once with + the intent, `reqId` and error class; no payload, name, key, session or SQL text. A `Defect` does + not require a restart in v1: the transaction helpers roll back on every unwind path, so the shared + connection stays usable. **Ack codes (static strings, never carry state).** @@ -1802,6 +1811,7 @@ on any failure. | `cap-reached` | `key.create` would exceed 6 players (3.2) | | `in-use` | `character.remove` while a token links the character | | `no-rules` | `act.do` (reserved, 9) | +| `internal` | the server failed while handling a readable intent; nothing was applied [FIXED (owner-delegated), 2026-11-20, #32] | Player name text: trimmed, NFC, 1 to 32 code points, no control characters. Deviation [FIXED (owner-delegated), #23]: Nim 2.2.12's stdlib has no Unicode normalisation (it lives in a package the diff --git a/server/db.nim b/server/db.nim index 7b39f3b..e68ebd6 100644 --- a/server/db.nim +++ b/server/db.nim @@ -289,13 +289,18 @@ template withTransaction*(db: DbConn, body: untyped) = ## One explicit transaction (DESIGN 4.2 step 6): COMMIT on success, ROLLBACK and re-raise on any ## failure. A template rather than a proc taking a closure: call sites run under the global lock ## inside `{.gcsafe.}` handlers, where a closure would need its own gcsafe proof. + ## #32: the rollback is not conditional on the error's class. A `Defect` unwinds like any other + ## failure, and a shared connection must never keep the BEGIN for the next caller. db.exec(sql"BEGIN") + var open = true try: body db.exec(sql"COMMIT") - except CatchableError: - try: db.exec(sql"ROLLBACK") - except CatchableError: discard # the original error is the one worth reporting + open = false + except Exception: + if open: + try: db.exec(sql"ROLLBACK") + except Exception: discard # the original error is the one worth reporting raise proc appliedMigrations*(db: DbConn): seq[MigrationRow] = diff --git a/server/faults.nim b/server/faults.nim index 6e07616..ace362a 100644 --- a/server/faults.nim +++ b/server/faults.nim @@ -2,7 +2,7 @@ ## The hook is compiled in only with `-d:leakfault`, and every fault checks ## `LEAK_FAULT=` from the environment: a normal build cannot fault, it contains no `LEAK_FAULT` ## string, and tools/fault.test.mjs asserts that the shipped binary's bytes lack it. -when defined(leakfault): +when defined(leakfault) or defined(dispfault): import std/os proc faultActive*(name: string): bool = @@ -18,3 +18,31 @@ proc crashNow*() = ## transactions (the `markerCrash` hook, TESTING 10.3, #60). A shipped build has no death path. when defined(leakfault): quit(70) + +when defined(dispfault): + var txnFaultFired = false + var ackFaultFired = false + +proc injectTxn*() = + ## #32 only: raise from inside a mutation that holds the database transaction, once per process. + ## The build define and the environment variable are both required, so a shipped binary has no + ## raise site at all. + when defined(dispfault): + if txnFaultFired: return + case getEnv("DISP_FAULT") + of "txn-catchable": + txnFaultFired = true + raise newException(ValueError, "injected fault") + of "txn-defect": + txnFaultFired = true + raise newException(Defect, "injected fault") + else: discard + +proc injectAfterAck*() = + ## #32 only: fail after the handler has already enqueued its ack, once per process, to prove the + ## guard never doubles an existing ack. A shipped binary has no raise site. + when defined(dispfault): + if ackFaultFired: return + if getEnv("DISP_FAULT") == "after-ack": + ackFaultFired = true + raise newException(Defect, "injected fault") diff --git a/server/main.nim b/server/main.nim index 80a086b..e31c6fb 100644 --- a/server/main.nim +++ b/server/main.nim @@ -92,6 +92,11 @@ var pingCounter: Atomic[int64] ## Payload of the last server Ping; the client echoes it in its Pong (4.3). Atomic because the ## heartbeat thread and the upgrade handler (a worker thread) both send pings. +var ackedReqId {.threadvar.}: int + ## #32: the reqId whose ack this handler invocation already enqueued, or -1. A threadvar is enough + ## because it is written and read entirely inside one `handleText` call on the thread that serves + ## the frame, even when that call unwinds through the dispatch guard. + proc nextPingSeq(): int64 = pingCounter.fetchAdd(1) + 1 @@ -105,10 +110,12 @@ proc nextN(conn: Conn): int = app.conns.nextFrameNo(conn.id) proc ackOk(conn: Conn, reqId: int, extra: JsonNode = nil) = + ackedReqId = reqId let n = nextN(conn) if n > 0: conn.ws.send($ackFrame(reqId, n, extra)) proc ackErr(conn: Conn, reqId: int, code: string) = + ackedReqId = reqId let n = nextN(conn) if n > 0: conn.ws.send($nackFrame(reqId, n, code)) @@ -403,6 +410,7 @@ proc settleLocked(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) ## Caller holds `app.dbLock` (ANALYSIS 4.1: every frame that references world state is built here). recordEncounters() ackOk(conn, reqId, extra) + faults.injectAfterAck() if roster: sendRoster() egressAll() @@ -1387,6 +1395,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = app.tokens[idx.get] = rec refreshPlayer(app.tokens[idx.get].owner) app.db.withTransaction: + faults.injectTxn() discard writePosition(app.db, app.tokens[idx.get]) writeStatuses(app.db, app.tokens[idx.get]) persistDerived(@[app.tokens[idx.get].owner]) @@ -2244,7 +2253,18 @@ proc handleText(conn: Conn, text: string) {.gcsafe.} = if not env.ok: malformedFrame(conn, nowMs) return - dispatch(conn, env) + # #32: one guard covers the whole handling of a readable envelope, so an escaping handler failure + # is still exactly one ack. A failure after the handler's own ack is not answered twice; anything + # else gets the static `internal` refusal. The transaction helpers roll back on every unwind path, + # including `Defect`, before this runs. + ackedReqId = -1 + try: + dispatch(conn, env) + except Exception as e: + if ackedReqId != env.reqId: + ackErr(conn, env.reqId, CodeInternal) + app.lg.log(lvError, "intent_failed", [("intent", env.t), ("reqId", $env.reqId), + ("class", $e.name), ("message", "unhandled")]) proc websocketEvent(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} = case event diff --git a/server/protocol.nim b/server/protocol.nim index 61d6b9e..83d1735 100644 --- a/server/protocol.nim +++ b/server/protocol.nim @@ -58,6 +58,9 @@ const CodeInUse* = "in-use" CodeNoRules* = "no-rules" CodeMalformed* = "malformed" + CodeInternal* = "internal" + ## #32: the server failed while handling a readable intent; nothing was applied. Static, no + ## detail (DESIGN 6.5). # The complete M3 intent catalogue (DESIGN 6.1: 29 intents). A name in here but not yet built # by its slice still gets exactly one ack; see `isImplementedIntent`. diff --git a/server/world.nim b/server/world.nim index 3f14850..4cfc08a 100644 --- a/server/world.nim +++ b/server/world.nim @@ -432,12 +432,17 @@ template authoringTransaction*(db: DbConn, body: untyped) = db.exec(sql"PRAGMA synchronous=FULL") try: db.exec(sql"BEGIN") + var open = true try: body db.exec(sql"COMMIT") - except CatchableError: - try: db.exec(sql"ROLLBACK") - except CatchableError: discard + open = false + except Exception: + # #32: roll back on every unwind path, `Defect` included, or the shared connection keeps an + # authoring transaction open for the next caller. + if open: + try: db.exec(sql"ROLLBACK") + except Exception: discard raise finally: db.exec(sql"PRAGMA synchronous=NORMAL") diff --git a/tests/tdb.nim b/tests/tdb.nim index 7456e67..8aafc42 100644 --- a/tests/tdb.nim +++ b/tests/tdb.nim @@ -3,7 +3,7 @@ ## migration leaves no trace (one transaction per step). import std/[unittest, os, strutils] import db_connector/db_sqlite -import db +import db, world var tmpCount = 0 proc tmpDir(): string = @@ -392,3 +392,53 @@ suite "step 8 wall CHECKs (DESIGN 4.4)": check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'wall_v1'") == "0" check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'marker_seen'") == "0" check db.getValue(sql"SELECT props_gm FROM entity WHERE id = 'tok000000009'") == "not json" + +suite "transaction unwind (#32)": + # The dispatch guard turns an escaping failure into one `internal` ack; the storage half of that + # contract is here: a `Defect` must roll back exactly like a `CatchableError` and leave the shared + # connection with no open transaction, or the next intent runs inside somebody else's BEGIN. + proc insertMeta(db: DbConn, k, v: string) = + db.exec(sql"INSERT INTO meta (k, v) VALUES (?, ?)", k, v) + + test "withTransaction rolls back a Defect and leaves the connection usable": + let d = tmpDir() + let db = openFresh(d) + defer: + close(db) + removeDir(d) + check migrate(db) == LatestVersion + var raised = false + try: + db.withTransaction: + insertMeta(db, "boom", "1") + raise newException(Defect, "injected defect") + except Defect: + raised = true + check raised + check db.getValue(sql"SELECT count(*) FROM meta WHERE k = 'boom'") == "0" + # no BEGIN was left open: the next ordinary transaction commits its own row and nothing else + db.withTransaction: + insertMeta(db, "next", "1") + check db.getValue(sql"SELECT count(*) FROM meta WHERE k = 'next'") == "1" + check db.getValue(sql"SELECT count(*) FROM meta") == "1" + + test "authoringTransaction rolls back a Defect and restores NORMAL": + let d = tmpDir() + let db = openFresh(d) + defer: + close(db) + removeDir(d) + check migrate(db) == LatestVersion + var raised = false + try: + db.authoringTransaction: + insertMeta(db, "boom", "1") + raise newException(Defect, "injected defect") + except Defect: + raised = true + check raised + check db.getValue(sql"SELECT count(*) FROM meta WHERE k = 'boom'") == "0" + check db.getValue(sql"PRAGMA synchronous") == "1" # NORMAL again (Q12) + db.authoringTransaction: + insertMeta(db, "next", "1") + check db.getValue(sql"SELECT count(*) FROM meta WHERE k = 'next'") == "1" diff --git a/tools/fault.test.mjs b/tools/fault.test.mjs index 7af2309..43bc2d3 100644 --- a/tools/fault.test.mjs +++ b/tools/fault.test.mjs @@ -11,9 +11,11 @@ import test from 'node:test' import assert from 'node:assert/strict' import fs from 'node:fs' +import { DatabaseSync } from 'node:sqlite' import path from 'node:path' import { runLeak, runChecker } from './leak.mjs' -import { buildServer, gmKeyOf, makeStateDir, startServer, stopServer } from './withserver.mjs' +import { buildServer, gmKeyOf, makeStateDir, signIn, startServer, stopServer } from './withserver.mjs' +import { openWs } from './lib.mjs' import { projectRoot } from './lib.mjs' const results = path.join(projectRoot, 'results') @@ -85,3 +87,103 @@ for (const [fault, expected] of Object.entries(FAULTS)) { } }) } + +// #32: an escaping failure in intent handling must still answer the request. The `dispfault` build +// is the only build with an injection point; the shipped binary must remain incapable of faulting. +test('the shipped build carries no dispatch fault hook', () => { + const bin = buildServer() + const bytes = fs.readFileSync(bin) + assert.equal(bytes.includes(Buffer.from('DISP_FAULT')), false, + `${bin} contains the dispatch fault hook: a production binary must be incapable of faulting`) +}) + +async function gmSession(s) { + const gmKey = gmKeyOf(s.stateDir) + const { cookie } = await signIn(s.origin, gmKey) + const ws = await openWs(s.origin, cookie) + const hello = await ws.waitText('hello') + await ws.waitText('walls') + return { ws, sceneId: hello.scene.id } +} + +test('a CatchableError inside a locked mutation: one internal ack, then the server keeps serving', + async () => { + const stateDir = makeStateDir() + const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'txn-catchable' } }) + try { + const gm = await gmSession(s) + const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', + pos: [100, 100], descriptive_name: 'a', actual_name: 'A' }) + assert.equal(tok.ok, true, JSON.stringify(tok)) + const bad = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [150, 150] }) + assert.equal(bad.ok, false) + assert.equal(bad.code, 'internal', 'an escaping CatchableError is the internal code') + assert.deepEqual(Object.keys(bad).sort(), ['code', 'n', 'ok', 'reqId', 't']) + const acks = gm.ws.messages.filter(m => m.t === 'ack' && m.reqId === bad.reqId) + assert.equal(acks.length, 1, 'exactly one ack for the failed intent') + // Nothing from the failed intent is durable: the row still holds the create position. + const db = new DatabaseSync(s.dbPath) + assert.deepEqual({ ...db.prepare('SELECT x, y FROM entity WHERE id = ?').get(tok.id) }, + { x: 100, y: 100 }) + db.close() + // One log event names the intent and the error class, never the message or payload. + const log = s.log() + assert.match(log, /ERROR intent_failed intent=token\.move reqId=\d+ class=ValueError message=unhandled/) + assert.equal(log.includes('injected fault'), false, 'the exception message is not logged') + + // The transaction is closed: the next move on the same connection commits its own row. + const good = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [120, 120] }) + assert.equal(good.ok, true, JSON.stringify(good)) + // And a second, unaffected connection can mutate too. + const gm2 = await gmSession(s) + const good2 = await gm2.ws.request({ t: 'token.move', id: tok.id, pos: [130, 130] }) + assert.equal(good2.ok, true, JSON.stringify(good2)) + gm.ws.close(); gm2.ws.close() + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } + }) + +test('a Defect inside a locked mutation: one internal ack and no open transaction', async () => { + const stateDir = makeStateDir() + const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'txn-defect' } }) + try { + const gm = await gmSession(s) + const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', + pos: [100, 100], descriptive_name: 'a', actual_name: 'A' }) + assert.equal(tok.ok, true, JSON.stringify(tok)) + const bad = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [150, 150] }) + assert.equal(bad.code, 'internal', 'a Defect is answered like any other escaping failure') + assert.equal(gm.ws.messages.filter(m => m.t === 'ack' && m.reqId === bad.reqId).length, 1) + assert.equal(gm.ws.closeInfo, null, 'the connection stays usable by default') + const good = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [120, 120] }) + assert.equal(good.ok, true, JSON.stringify(good)) + gm.ws.close() + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } +}) + +test('a failure after the ack was enqueued never appends a second ack', async () => { + const stateDir = makeStateDir() + const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'after-ack' } }) + try { + const gm = await gmSession(s) + const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', + pos: [100, 100], descriptive_name: 'a', actual_name: 'A' }) + assert.equal(tok.ok, true, JSON.stringify(tok)) + const ack = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [150, 150] }) + assert.equal(ack.ok, true, 'the handler\'s own ack is the one the client sees') + const all = gm.ws.messages.filter(m => m.t === 'ack' && m.reqId === ack.reqId) + assert.equal(all.length, 1, 'the guard must not append an internal ack after a sent ack') + assert.equal(all[0].code, undefined) + const next = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [120, 120] }) + assert.equal(next.ok, true, JSON.stringify(next)) + gm.ws.close() + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } +})