carlos / platform Public

lease: uncommitted WAL frames are covered; no coverage without L

Branch review R1 fixes:

- Fable P2-3: walCovered walks the frame headers past the captured end
  (a pure iter.Seq that readCoverage feeds one header at a time, at the
  WAL header's frame stride, bounded by the stat's size). Frames of
  this generation that commit nothing (bytes 4..7 zero) are covered:
  a spill still running, or rolled back, is no acknowledged write. A
  commit frame there is not covered. Removes residual (b).
- Fable P2-4: step consults coverage only when DB.Pos was read (lOK),
  so an unread L of 0 never discharges an obligation.
- Residual (d) stated at step: litestream's deferred checkpoint write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e35bc3aa9bd0085b054c62da16ecc01597cde25e parent 5b39fc2
5 files changed, +185 −36
  • internal/lease/fence.go +59 −20
  • internal/lease/fence_queue_test.go +45 −5
  • internal/lease/fence_test.go +38 −0
  • internal/lease/fencerun.go +25 −9
  • internal/lease/fencerun_test.go +18 −2
diff --git a/internal/lease/fence.go b/internal/lease/fence.go
index 936c52d15..ba4bcbb13 100644
--- a/internal/lease/fence.go
+++ b/internal/lease/fence.go
@@ -3,6 +3,7 @@ package lease
import (
"encoding/binary"
"errors"
+ "iter"
"time"
"github.com/superfly/ltx"
@@ -22,6 +23,8 @@ const (
// walHeaderSize is SQLite's WAL file header; a WAL no longer than this
// has no frames.
walHeaderSize = 32
+ // walFrameHeaderSize is the header in front of each WAL frame's page.
+ walFrameHeaderSize = 24
)
// walState is what one stat of the -wal file shows. A missing WAL is
@@ -66,8 +69,17 @@ type fenceQueue struct {
// step folds one sample taken at now into the queue and reports whether
// the oldest obligation is older than fenceLimit. covered is called only
-// on a run whose stat succeeded and that has unknown obligations; it
-// reports the TXID that captures the WAL as it is now, if it does.
+// on a run whose stat succeeded, whose local TXID was read (lOK: covered
+// can answer with L, and an unread L is 0, which would discharge without
+// proof) and that has unknown obligations; it reports the TXID that
+// captures the WAL as it is now, if it does.
+//
+// Residual (d): litestream's own deferred checkpoint (a PASSIVE
+// checkpoint once the database has gone a minute since the last one with
+// something synced) writes its _litestream_seq row into the WAL. If the
+// store went out within about a minute of an instance's last write, that
+// bookkeeping write is an obligation like any other, and an instance idle
+// since is fenced about 31 s after it.
func (q *fenceQueue) step(now time.Time, s fenceSample, covered func() (uint64, bool)) bool {
if s.R > q.r { // a failed sync zeroes Replica.Pos; keep the highest seen
q.r = s.R
@@ -98,14 +110,12 @@ func (q *fenceQueue) step(now time.Time, s fenceSample, covered func() (uint64,
if changed || (first && s.W.exists && s.W.size > walHeaderSize) { // P1-1: frames at the first look are unproven
q.ob = append(q.ob, fenceObligation{t: now})
}
- if s.statErr == nil && q.anyUnknown() {
+ if s.statErr == nil && s.lOK && q.anyUnknown() {
// Rule C: the WAL as it is now is all captured, by the newest
// LTX file's range and salts (walCovered), never by size alone.
- //
- // Residual (b): a rolled-back transaction that spilled frames
- // leaves frames past the captured end with the current salts
- // that no transaction will ever capture; if the instance then
- // goes idle, it is fenced spuriously.
+ // Frames past the captured end that end no transaction (a
+ // spill still running, or rolled back) are not writes anyone
+ // was told were stored, so they count as covered.
if txid, ok := covered(); ok {
for i := range q.ob {
if !q.ob[i].known {
@@ -147,12 +157,21 @@ func (q *fenceQueue) anyUnknown() bool {
}
// walCovered decides whether the WAL as it is now is all captured, and by
-// which TXID. walHdr is the WAL file's header (salts big-endian at bytes
-// 16..23; shorter than walHeaderSize is never covered); frameAtEnd is whatever was read at the newest LTX file's
-// captured end (h.WALOffset+h.WALSize; a frame header carries the salts
-// at bytes 8..15). h is that LTX file's header, nil if there is none. l
-// is the local TXID, returned when the WAL holds no frames.
-func walCovered(w walState, walHdr, frameAtEnd []byte, h *ltx.Header, l uint64) (txid uint64, ok bool) {
+// which TXID. walHdr is the WAL file's header (page size big-endian at
+// bytes 8..11, salts at 16..23; shorter than walHeaderSize is never
+// covered). pastEnd yields the frame headers past the newest LTX file's
+// captured end (h.WALOffset+h.WALSize), in order, each as read: a frame
+// header carries the commit size at bytes 4..7 (0 for a frame that ends
+// no transaction) and the salts at 8..15, and a short one is the end of
+// the file. h is that LTX file's header, nil if there is none. l is the
+// local TXID, returned when the WAL holds no frames.
+//
+// Frames past the captured end that belong to this WAL generation but end
+// no transaction are covered: uncommitted work (a spilled transaction
+// still running, or one rolled back) is not an acknowledged write. A
+// commit frame of this generation there is a transaction not yet
+// captured.
+func walCovered(w walState, walHdr []byte, pastEnd iter.Seq[[]byte], h *ltx.Header, l uint64) (txid uint64, ok bool) {
if !w.exists || w.size <= walHeaderSize {
return l, true
}
@@ -164,14 +183,34 @@ func walCovered(w walState, walHdr, frameAtEnd []byte, h *ltx.Header, l uint64)
if salt1 != h.WALSalt1 || salt2 != h.WALSalt2 {
return 0, false // the WAL restarted since the capture: its frames are unproven
}
- if w.size <= h.WALOffset+h.WALSize {
+ if w.size <= h.WALOffset+h.WALSize || pastEnd == nil {
return uint64(h.MaxTXID), true
}
- if len(frameAtEnd) >= 24 &&
- binary.BigEndian.Uint32(frameAtEnd[8:12]) == salt1 &&
- binary.BigEndian.Uint32(frameAtEnd[12:16]) == salt2 {
- return 0, false // a frame of this WAL generation past the capture
+ for frame := range pastEnd {
+ if len(frame) < walFrameHeaderSize ||
+ binary.BigEndian.Uint32(frame[8:12]) != salt1 ||
+ binary.BigEndian.Uint32(frame[12:16]) != salt2 {
+ // The end of the file, or bytes left from before a WAL
+ // restart: nothing of this generation follows.
+ break
+ }
+ if binary.BigEndian.Uint32(frame[4:8]) != 0 {
+ return 0, false // a committed transaction past the capture
+ }
}
- // Bytes past the captured end are left from before a WAL restart.
return uint64(h.MaxTXID), true
}
+
+// walFrameSize is one WAL frame's size (its header and a page) by the WAL
+// header's page size, 0 when the header is short or the page size is not
+// one SQLite writes (a power of two from 512 to 65536).
+func walFrameSize(walHdr []byte) int64 {
+ if len(walHdr) < walHeaderSize {
+ return 0
+ }
+ ps := binary.BigEndian.Uint32(walHdr[8:12])
+ if ps < 512 || ps > 65536 || ps&(ps-1) != 0 {
+ return 0
+ }
+ return walFrameHeaderSize + int64(ps)
+}
diff --git a/internal/lease/fence_queue_test.go b/internal/lease/fence_queue_test.go
index 93b21008a..1e62b2f4d 100644
--- a/internal/lease/fence_queue_test.go
+++ b/internal/lease/fence_queue_test.go
@@ -3,6 +3,8 @@ package lease
import (
"encoding/binary"
"errors"
+ "iter"
+ "slices"
"testing"
"time"
@@ -278,6 +280,23 @@ func TestFenceQueueOutageUnder30s(t *testing.T) {
wantFirstTrip(t, got, -1)
}
+// Fable P2-4: with DB.Pos unreadable (lOK false, L 0), coverage is not
+// consulted; a frameless WAL would answer "covered at 0", and R >= 0
+// would discharge every unknown obligation without proof.
+func TestFenceQueueUnreadLNeverDischarges(t *testing.T) {
+ got := firstTrip(t, 60, func(k int) (fenceSample, func() (uint64, bool)) {
+ switch {
+ case k == 0:
+ return fenceSample{L: 5, lOK: true, R: 5, W: frameless()}, coveredAt(5)
+ case k == 1: // a write, not yet captured
+ return fenceSample{L: 5, lOK: true, R: 5, W: walAt(1)}, notCovered
+ default: // DB.Pos fails from here; the WAL is frameless again
+ return fenceSample{L: 0, lOK: false, R: 5, W: frameless()}, coveredAt(0)
+ }
+ })
+ wantFirstTrip(t, got, 32)
+}
+
// A failed sync zeroes Replica.Pos: a falling R is not a loss of what
// was stored, so the queue keeps the highest R and does not trip.
func TestFenceQueueFallingRControl(t *testing.T) {
@@ -318,13 +337,17 @@ func TestFenceQueueMtimeOnlyChange(t *testing.T) {
})
}
+// walHeader is a WAL header for 4096-byte pages (frameSize) with the
+// given salts.
func walHeader(salt1, salt2 uint32) []byte {
b := make([]byte, walHeaderSize)
+ binary.BigEndian.PutUint32(b[8:], 4096)
binary.BigEndian.PutUint32(b[16:], salt1)
binary.BigEndian.PutUint32(b[20:], salt2)
return b
}
+// frameHeader is a frame header that ends no transaction (commit size 0).
func frameHeader(salt1, salt2 uint32) []byte {
b := make([]byte, 24)
binary.BigEndian.PutUint32(b[8:], salt1)
@@ -332,6 +355,17 @@ func frameHeader(salt1, salt2 uint32) []byte {
return b
}
+// commitHeader is a frame header that commits a transaction (the
+// database's size in pages after it, at bytes 4..7).
+func commitHeader(salt1, salt2 uint32) []byte {
+ b := frameHeader(salt1, salt2)
+ binary.BigEndian.PutUint32(b[4:], 7)
+ return b
+}
+
+// frames is the frame headers past the captured end, as walCovered reads them.
+func frames(f ...[]byte) iter.Seq[[]byte] { return slices.Values(f) }
+
func TestWalCovered(t *testing.T) {
const l = 9
h := &ltx.Header{MaxTXID: 12, WALOffset: walHeaderSize, WALSize: 3 * frameSize, WALSalt1: 0xAAAA0001, WALSalt2: 0xBBBB0002}
@@ -342,7 +376,7 @@ func TestWalCovered(t *testing.T) {
name string
w walState
hdr []byte
- frame []byte
+ frames iter.Seq[[]byte]
h *ltx.Header
want uint64
wantOK bool
@@ -358,14 +392,20 @@ func TestWalCovered(t *testing.T) {
{"salt 2 differs", framed, walHeader(h.WALSalt1, h.WALSalt2+1), nil, h, 0, false},
{"WAL ends at the captured end", walState{exists: true, size: end}, cur, nil, h, 12, true},
{"WAL shorter than the captured end", walState{exists: true, size: end - frameSize}, cur, nil, h, 12, true},
- {"frame at end with current salts", framed, cur, frameHeader(h.WALSalt1, h.WALSalt2), h, 0, false},
- {"frame at end with other salts (left from before a restart)", framed, cur, frameHeader(1, 2), h, 12, true},
- {"frame at end shorter than a frame header", framed, cur, frameHeader(h.WALSalt1, h.WALSalt2)[:23], h, 12, true},
+ {"a commit frame at the end with the current salts", framed, cur, frames(commitHeader(h.WALSalt1, h.WALSalt2)), h, 0, false},
+ {"a commit frame at the end with other salts (left from before a restart)", framed, cur, frames(commitHeader(1, 2)), h, 12, true},
+ {"frame at end shorter than a frame header", framed, cur, frames(commitHeader(h.WALSalt1, h.WALSalt2)[:23]), h, 12, true},
{"no frame at end", framed, cur, nil, h, 12, true},
+ {"no frame read at end", framed, cur, frames(), h, 12, true},
+ // P2-3: uncommitted work is not an acknowledged write.
+ {"uncommitted frames of this generation (a spill)", framed, cur, frames(frameHeader(h.WALSalt1, h.WALSalt2), frameHeader(h.WALSalt1, h.WALSalt2)), h, 12, true},
+ {"uncommitted frames, then a commit", framed, cur, frames(frameHeader(h.WALSalt1, h.WALSalt2), frameHeader(h.WALSalt1, h.WALSalt2), commitHeader(h.WALSalt1, h.WALSalt2)), h, 0, false},
+ {"uncommitted frames, then stale ones", framed, cur, frames(frameHeader(h.WALSalt1, h.WALSalt2), commitHeader(1, 2)), h, 12, true},
+ {"a stale frame, then a commit with the current salts", framed, cur, frames(commitHeader(1, 2), commitHeader(h.WALSalt1, h.WALSalt2)), h, 12, true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
- got, ok := walCovered(c.w, c.hdr, c.frame, c.h, l)
+ got, ok := walCovered(c.w, c.hdr, c.frames, c.h, l)
if got != c.want || ok != c.wantOK {
t.Fatalf("walCovered = (%d, %v), want (%d, %v)", got, ok, c.want, c.wantOK)
}
diff --git a/internal/lease/fence_test.go b/internal/lease/fence_test.go
index 5da2c094a..ed16d1536 100644
--- a/internal/lease/fence_test.go
+++ b/internal/lease/fence_test.go
@@ -11,6 +11,7 @@ import (
"os"
"path/filepath"
"slices"
+ "strings"
"sync"
"sync/atomic"
"testing"
@@ -856,6 +857,43 @@ func TestWriteFenceRealMonitorShortOutage(t *testing.T) {
}
}
+// Fable branch R1 P2-3: a transaction that spills frames into the WAL
+// and runs longer than 30 s on a healthy store is not fenced: its frames
+// past the captured end commit nothing yet. Once it commits and is
+// stored, still nothing trips.
+func TestWriteFenceLongSpillNeverTrips(t *testing.T) {
+ haBox(t)
+ fx := leasetest.NewLockFixture(t)
+ g := fencedReplicator(t, haHeld(t, fx, "instances/f"), lsfile.NewReplicaClient(t.TempDir()))
+ g.syncAndWait(t)
+ _, _, before := walSalts(t, g.path)
+ db := holdOpen(t, g.path)
+ if _, err := db.Exec(`PRAGMA cache_size=8`); err != nil { // a tiny page cache: the transaction spills
+ t.Fatal(err)
+ }
+ tx, err := db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ blob := strings.Repeat("x", 8000)
+ for i := 0; i < 200; i++ {
+ if _, err := tx.Exec(`INSERT INTO t (body) VALUES (?)`, blob); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, _, during := walSalts(t, g.path); during <= before+64*1024 {
+ t.Fatalf("case not reached: the WAL grew from %d to only %d bytes inside the transaction", before, during)
+ }
+ g.steps(t, 0, 60, nil) // the transaction is open throughout
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ g.capture(t)
+ g.syncAndWait(t)
+ g.steps(t, 61, 100, nil)
+}
+
func TestWriteFenceEndsWithTheReplicator(t *testing.T) {
haBox(t)
fx := leasetest.NewLockFixture(t)
diff --git a/internal/lease/fencerun.go b/internal/lease/fencerun.go
index db918ab8a..84a092f1b 100644
--- a/internal/lease/fencerun.go
+++ b/internal/lease/fencerun.go
@@ -174,12 +174,14 @@ func (r *Replicator) tripFence(q *fenceQueue, now time.Time) {
}
// readCoverage reads what walCovered decides from: the WAL header and
-// whatever is at the newest L0 LTX file's captured end. It does file I/O
-// only. w is the sample's stat: a WAL that is missing or has no frames is
-// answered without any read. A read that meets EOF passes the short
-// bytes on (a WAL that ends at or inside the trailing frame, or a header
-// cut short after the stat); any other open or read error, and an LTX
-// header that cannot be read, is not covered.
+// the frame headers past the newest L0 LTX file's captured end. It does
+// file I/O only. w is the sample's stat: a WAL that is missing or has no
+// frames is answered without any read. The frame headers are read one at
+// a time as walCovered asks for them, at the WAL header's frame stride,
+// and never past w.size; a frame header that meets EOF is passed on short
+// (the file ends there), as is a WAL header cut short after the stat. Any
+// other open or read error, and an LTX header that cannot be read, is not
+// covered.
func readCoverage(walPath string, w walState, l uint64, header func() (*ltx.Header, error)) (uint64, bool) {
if !w.exists || w.size <= walHeaderSize {
return walCovered(w, nil, nil, nil, l)
@@ -200,11 +202,25 @@ func readCoverage(walPath string, w walState, l uint64, header func() (*ltx.Head
if !ok {
return 0, false
}
- frame, ok := readAtMost(f, 24, h.WALOffset+h.WALSize)
- if !ok {
+ stride := walFrameSize(hdr)
+ failed := false
+ pastEnd := func(yield func([]byte) bool) {
+ for off := h.WALOffset + h.WALSize; off < w.size; off += stride {
+ frame, ok := readAtMost(f, walFrameHeaderSize, off)
+ if !ok {
+ failed = true
+ return
+ }
+ if !yield(frame) || len(frame) < walFrameHeaderSize || stride == 0 {
+ return // walCovered has decided, the file ended, or no stride to step by
+ }
+ }
+ }
+ txid, covered := walCovered(w, hdr, pastEnd, h, l)
+ if failed {
return 0, false
}
- return walCovered(w, hdr, frame, h, l)
+ return txid, covered
}
// readAtMost reads up to n bytes at off; EOF short of n is not an error.
diff --git a/internal/lease/fencerun_test.go b/internal/lease/fencerun_test.go
index 8c815e551..abb7b3f6a 100644
--- a/internal/lease/fencerun_test.go
+++ b/internal/lease/fencerun_test.go
@@ -36,8 +36,20 @@ func TestReadCoverage(t *testing.T) {
copy(b, cur)
return append(b, tail...)
}
+ // fullFrame is a committing frame, page included; spillFrame one
+ // that ends no transaction.
fullFrame := func(salt1, salt2 uint32) []byte {
- return append(frameHeader(salt1, salt2), make([]byte, frameSize-24)...)
+ return append(commitHeader(salt1, salt2), make([]byte, frameSize-24)...)
+ }
+ spillFrame := func() []byte {
+ return append(frameHeader(h.WALSalt1, h.WALSalt2), make([]byte, frameSize-24)...)
+ }
+ spill := func(n int) []byte {
+ var b []byte
+ for range n {
+ b = append(b, spillFrame()...)
+ }
+ return b
}
headerIs := func(hh *ltx.Header, err error) (func() (*ltx.Header, error), *int) {
n := 0
@@ -76,7 +88,11 @@ func TestReadCoverage(t *testing.T) {
wantOK bool
}{
{"frames, no L0 LTX file", upToEnd(fullFrame(h.WALSalt1, h.WALSalt2)), nil, nil, 0, false},
- {"frames past the captured end with the current salts", upToEnd(fullFrame(h.WALSalt1, h.WALSalt2)), h, nil, 0, false},
+ {"a commit frame past the captured end with the current salts", upToEnd(fullFrame(h.WALSalt1, h.WALSalt2)), h, nil, 0, false},
+ {"a long uncommitted spill past the captured end", upToEnd(spill(200)), h, nil, 12, true},
+ {"a spill, then a commit frame", upToEnd(append(spill(50), fullFrame(h.WALSalt1, h.WALSalt2)...)), h, nil, 0, false},
+ {"a spill, then stale frames", upToEnd(append(spill(5), fullFrame(1, 2)...)), h, nil, 12, true},
+ {"a spill cut inside its last frame header", upToEnd(append(spill(3), commitHeader(h.WALSalt1, h.WALSalt2)[:10]...)), h, nil, 12, true},
{"a stale-salt frame at the end", upToEnd(fullFrame(1, 2)), h, nil, 12, true},
{"the file ends exactly at the captured end", upToEnd(nil), h, nil, 12, true},
{"EOF inside the trailing frame header", upToEnd(frameHeader(h.WALSalt1, h.WALSalt2)[:10]), h, nil, 12, true},