fix: dispatch guard and Defect-safe rollback (#32)

A readable intent that fails in handling now always gets exactly one ack:
the new static internal code, unless the handler's own ack was already
enqueued. Both transaction helpers roll back on every unwind path,
Defect included, so the shared SQLite connection never keeps an open
transaction. Test-only dispfault build covers catchable/defect/after-ack;
DESIGN 6.5 records internal as an owner decision and 6.2 names refusal
codes as additive.
This commit is contained in:
2026-11-20 21:36:44 +01:00
parent 38941da003
commit a5c0ee5d4c
9 changed files with 246 additions and 12 deletions
+8 -3
View File
@@ -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] =
+29 -1
View File
@@ -2,7 +2,7 @@
## The hook is compiled in only with `-d:leakfault`, and every fault checks
## `LEAK_FAULT=<name>` 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")
+21 -1
View File
@@ -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
+3
View File
@@ -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`.
+8 -3
View File
@@ -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")