lease: snapshot when the WAL restarted before replication began
A wake starts the process before Replicate, and litestream's first sync came a monitor interval (10 s) later. A boot-time migration in that gap trips SQLite's autocheckpoint and the next write restarts the WAL; litestream v0.5.14 then continues incrementally from the new WAL and the replica never gets the migrated pages. Every later restore fails integrity_check (seen on flagship 2026-11-19). Replicate now forces the first sync before it returns, and when that sync carried on incrementally into another WAL generation than the last one replicated, writes a snapshot at once. HA leases are unchanged for now.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+363
−9
internal/lease/lease.go+12 −0internal/lease/release.go+1 −9internal/lease/wakegap.go+215 −0internal/lease/wakegap_test.go+135 −0
CI failed — run details
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 6cef18bc1..fb0d20fef 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -455,11 +455,23 @@ func (h *Held) Replicate(ctx context.Context, dbPath string, syncInterval time.D |
| gate = newFenceGate(db.Replica.Client) |
| db.Replica.Client = gate |
| } |
| + // Read before Open: the first sync moves the newest local L0 on. |
| + prev, hadPrev := lastReplicated(db) |
| if err := store.Open(opCtx); err != nil { |
| cancel() |
| closeErr := store.Close(opCtx) |
| return nil, errors.Join(fmt.Errorf("open litestream store: %w", err), closeErr) |
| } |
| + // The wake gap (wakegap.go): sync now rather than a monitor interval |
| + // from now, and snapshot when the WAL restarted while nothing |
| + // replicated it. An HA lease is left as it was for now: its monitor |
| + // runs every second, and its wake's replica requests are pinned by the |
| + // region HA tests; extending this to it is a follow-up. |
| + if err := syncAcrossGap(opCtx, db, prev, hadPrev && !h.ha); err != nil { |
| + cancel() |
| + closeErr := store.Close(opCtx) |
| + return nil, errors.Join(err, closeErr) |
| + } |
| if err := h.rn.Err(); err != nil { |
| cancel() |
| closeErr := store.Close(opCtx) |
diff --git a/internal/lease/release.go b/internal/lease/release.go| index d54cfe054..1d4accff9 100644 |
| --- a/internal/lease/release.go |
| +++ b/internal/lease/release.go |
| @@ -5,7 +5,6 @@ import ( |
| "context" |
| "errors" |
| "fmt" |
| - "io" |
| "net/http" |
| "time" |
| @@ -36,14 +35,7 @@ func (r *Replicator) snapshotWithin(ctx context.Context) (*ltx.FileInfo, error) |
| ctx, cancel = context.WithTimeout(ctx, time.Until(d)/2) |
| defer cancel() |
| } |
| - pos, rd, err := r.db.SnapshotReader(ctx) |
| - if err != nil { |
| - return nil, err |
| - } |
| - if c, ok := rd.(io.Closer); ok { |
| - defer c.Close() |
| - } |
| - return r.db.Replica.Client.WriteLTXFile(ctx, litestream.SnapshotLevel, 1, pos.TXID, rd) |
| + return writeSnapshot(ctx, r.db) |
| } |
| // releaseWithMarker is the one HA release. lease never deletes an HA lock: |
diff --git a/internal/lease/wakegap.go b/internal/lease/wakegap.go| new file mode 100644 |
| index 000000000..09d2842ae |
| --- /dev/null |
| +++ b/internal/lease/wakegap.go |
| @@ -0,0 +1,215 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "encoding/binary" |
| + "fmt" |
| + "io" |
| + "log" |
| + "os" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + "github.com/superfly/ltx" |
| +) |
| + |
| +// The wake gap. A wake starts the instance's process before it starts |
| +// replication (activator doWakeOnce: spawn is step 4, Replicate step 5), |
| +// and litestream's first sync waits a whole monitor interval after Open |
| +// (dbMonitorInterval, 10 s). Until that sync nothing holds litestream's |
| +// read lock, so the app's own autocheckpoint can copy every WAL frame into |
| +// the database file and its next write restart the WAL. litestream v0.5.14 |
| +// cannot see frames it never read: when the frame at its last offset |
| +// survives the restart, verify continues from the new WAL's start |
| +// (db.go verifyWithExecutor, the !saltMatch branch) and the replica lacks |
| +// every page those frames wrote. A schema migration on boot does exactly |
| +// this, and every restore after it fails its integrity check. |
| +// |
| +// Replicate closes it in two steps. It forces the first sync before it |
| +// returns, so litestream holds its read lock from then on and the gap ends |
| +// at Replicate rather than a monitor interval later. And when that sync |
| +// carried on incrementally into another WAL generation than the last one |
| +// this box replicated, the frames in between may be gone from the WAL, so |
| +// it writes a snapshot at once: the newest restore then starts from it and |
| +// never reads across the gap. When litestream noticed by itself and wrote |
| +// a full image, nothing more is needed. |
| + |
| +// walMark is where a replicator last read the WAL: an L0 file's TXID and |
| +// the WAL salts its header records. |
| +type walMark struct { |
| + txid ltx.TXID |
| + salt1, salt2 uint32 |
| + path string // the local L0 file |
| +} |
| + |
| +// lastReplicated is the newest local L0 file's mark. ok is false when there |
| +// is none: a first replication, or local state gone, when litestream reads |
| +// the replica's own position instead (its issue #781 path). |
| +func lastReplicated(db *litestream.DB) (walMark, bool) { |
| + minTXID, maxTXID, err := db.MaxLTX() |
| + if err != nil || maxTXID == 0 { |
| + return walMark{}, false |
| + } |
| + return readMark(db.LTXPath(0, minTXID, maxTXID)) |
| +} |
| + |
| +// firstAfter is the mark of the oldest local L0 file after txid: the first |
| +// file this session's sync wrote. ok is false when it wrote none. |
| +func firstAfter(db *litestream.DB, txid ltx.TXID) (walMark, bool) { |
| + ents, err := os.ReadDir(db.LTXLevelDir(0)) |
| + if err != nil { |
| + return walMark{}, false |
| + } |
| + var lo, hi ltx.TXID |
| + for _, e := range ents { |
| + minTXID, maxTXID, err := ltx.ParseFilename(e.Name()) |
| + if err != nil || minTXID <= txid { |
| + continue |
| + } |
| + if lo == 0 || minTXID < lo { |
| + lo, hi = minTXID, maxTXID |
| + } |
| + } |
| + if lo == 0 { |
| + return walMark{}, false |
| + } |
| + return readMark(db.LTXPath(0, lo, hi)) |
| +} |
| + |
| +func readMark(path string) (walMark, bool) { |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return walMark{}, false |
| + } |
| + defer f.Close() |
| + dec := ltx.NewDecoder(f) |
| + if err := dec.DecodeHeader(); err != nil { |
| + return walMark{}, false |
| + } |
| + h := dec.Header() |
| + return walMark{txid: h.MaxTXID, salt1: h.WALSalt1, salt2: h.WALSalt2, path: path}, true |
| +} |
| + |
| +// fullImage reports whether the LTX file at path holds every page of its |
| +// database (1 to its commit, less SQLite's lock page): what litestream |
| +// writes when its verify decides to snapshot. An incremental file stops |
| +// being contiguous at its first unchanged page, so this reads only that far. |
| +func fullImage(path string) bool { |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return false |
| + } |
| + defer f.Close() |
| + dec := ltx.NewDecoder(f) |
| + if err := dec.DecodeHeader(); err != nil { |
| + return false |
| + } |
| + h := dec.Header() |
| + lock := ltx.LockPgno(h.PageSize) |
| + buf := make([]byte, h.PageSize) |
| + want := uint32(1) |
| + for { |
| + if want == lock { |
| + want++ |
| + } |
| + var ph ltx.PageHeader |
| + if err := dec.DecodePage(&ph, buf); err == io.EOF { |
| + break |
| + } else if err != nil || ph.Pgno != want { |
| + return false |
| + } |
| + want++ |
| + } |
| + if want == lock { |
| + want++ |
| + } |
| + return want > h.Commit |
| +} |
| + |
| +// walSalts reads the salts in the database's WAL header. ok is false when |
| +// there is no readable header. |
| +func walSalts(walPath string) (salt1, salt2 uint32, ok bool) { |
| + f, err := os.Open(walPath) |
| + if err != nil { |
| + return 0, 0, false |
| + } |
| + defer f.Close() |
| + var hdr [litestream.WALHeaderSize]byte |
| + if _, err := io.ReadFull(f, hdr[:]); err != nil { |
| + return 0, 0, false |
| + } |
| + return binary.BigEndian.Uint32(hdr[16:]), binary.BigEndian.Uint32(hdr[20:]), true |
| +} |
| + |
| +// firstSyncTimeout bounds Replicate's first sync, and gapSnapshotTimeout |
| +// the snapshot after a gap. A replica that hangs must not hang the wake. |
| +var ( |
| + firstSyncTimeout = 30 * time.Second |
| + gapSnapshotTimeout = 5 * time.Minute |
| +) |
| + |
| +// syncAcrossGap is Replicate's first sync, and the snapshot that follows |
| +// it when that sync carried on incrementally into another WAL generation |
| +// than prev, the last mark this box replicated. Without a prev (hadPrev |
| +// false) it does nothing: litestream's own first sync then starts from a |
| +// snapshot or from the replica's position. |
| +// |
| +// A WAL already in another generation before the sync is a known gap: a |
| +// failed sync or snapshot then fails Replicate, so the wake does not serve |
| +// on a replica it knows cannot be restored. Otherwise a failed first sync |
| +// is only logged and the monitor carries on, as it did before. |
| +func syncAcrossGap(ctx context.Context, db *litestream.DB, prev walMark, hadPrev bool) error { |
| + if !hadPrev { |
| + return nil |
| + } |
| + known := false |
| + if s1, s2, ok := walSalts(db.WALPath()); ok && (s1 != prev.salt1 || s2 != prev.salt2) { |
| + known = true |
| + } |
| + sctx, cancel := context.WithTimeout(ctx, firstSyncTimeout) |
| + err := db.SyncAndWait(sctx) |
| + cancel() |
| + if err != nil { |
| + if known { |
| + return fmt.Errorf("first sync after an unreplicated WAL restart: %w", err) |
| + } |
| + log.Printf("lease: %s: first sync: %v (the monitor retries)", db.Path(), err) |
| + return nil |
| + } |
| + next, ok := firstAfter(db, prev.txid) |
| + if !ok || (next.salt1 == prev.salt1 && next.salt2 == prev.salt2) || fullImage(next.path) { |
| + return nil |
| + } |
| + synced, err := db.Pos() |
| + if err != nil { |
| + return fmt.Errorf("position after an unreplicated WAL restart: %w", err) |
| + } |
| + sctx, cancel = context.WithTimeout(ctx, gapSnapshotTimeout) |
| + defer cancel() |
| + info, err := writeSnapshot(sctx, db) |
| + if err != nil { |
| + // litestream's own snapshot monitor runs at Open, and when a |
| + // snapshot is due it writes the same file at the same moment. |
| + // Either copy covers the gap if it reaches the synced position. |
| + have, lerr := db.Replica.MaxLTXFileInfo(sctx, litestream.SnapshotLevel) |
| + if lerr != nil || have.MinTXID != 1 || have.MaxTXID < synced.TXID { |
| + return fmt.Errorf("snapshot after an unreplicated WAL restart: %w", err) |
| + } |
| + info = &have |
| + } |
| + log.Printf("lease: %s: the WAL restarted while nothing replicated it; snapshot 1-%s covers the gap", db.Path(), info.MaxTXID) |
| + return nil |
| +} |
| + |
| +// writeSnapshot is litestream's DB.Snapshot, closing its reader on every |
| +// outcome (snapshotWithin says why). |
| +func writeSnapshot(ctx context.Context, db *litestream.DB) (*ltx.FileInfo, error) { |
| + pos, rd, err := db.SnapshotReader(ctx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if c, ok := rd.(io.Closer); ok { |
| + defer c.Close() |
| + } |
| + return db.Replica.Client.WriteLTXFile(ctx, litestream.SnapshotLevel, 1, pos.TXID, rd) |
| +} |
diff --git a/internal/lease/wakegap_test.go b/internal/lease/wakegap_test.go| new file mode 100644 |
| index 000000000..0f7d2a2bd |
| --- /dev/null |
| +++ b/internal/lease/wakegap_test.go |
| @@ -0,0 +1,135 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "fmt" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| +) |
| + |
| +// A wake starts the process before Replicate (activator doWakeOnce, steps |
| +// 4 and 5). Writes in that gap reach the WAL with nothing holding |
| +// litestream's read lock: a large one (a schema migration on boot) trips |
| +// SQLite's autocheckpoint, the next write restarts the WAL, and the frames |
| +// litestream never read are only in the database file. litestream v0.5.14 |
| +// continues from the new WAL's start when the frame at its last offset |
| +// survived the restart, so before the fix the replica lacked every page the |
| +// migration wrote and the restore was malformed. |
| +func TestReplicateAfterUnreplicatedWALRestartRestoresWhole(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + rows int // rows the "migration" writes before Replicate |
| + }{ |
| + {"small write, same WAL generation", 50}, |
| + {"migration trips autocheckpoint and the WAL restarts", 20000}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + ctx := context.Background() |
| + backend := &lockStore{} |
| + path := filepath.Join(t.TempDir(), "app.db") |
| + seedDB(t, path) |
| + replica := t.TempDir() |
| + |
| + // First wake: process, then replication; a write; hibernate |
| + // (the process stops first, then the replicator). |
| + app := openWakeApp(t, path) |
| + h := localHeld(t, backend, 10*time.Second) |
| + h.replicaClient = lsfile.NewReplicaClient(replica) |
| + r, err := h.Replicate(ctx, path, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + wakeExec(t, app, `INSERT INTO t (body) VALUES ('first wake')`) |
| + if err := r.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + app.Close() |
| + if err := r.Close(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // Second wake: the process migrates before Replicate. |
| + app = openWakeApp(t, path) |
| + wakeExec(t, app, `CREATE TABLE m (id INTEGER PRIMARY KEY, body TEXT)`) |
| + wakeExec(t, app, `CREATE INDEX m_body ON m(body)`) |
| + tx, err := app.Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < tc.rows; i++ { |
| + if _, err := tx.Exec(`INSERT INTO m (body) VALUES (?)`, strings.Repeat(fmt.Sprint(i), 40)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + wakeExec(t, app, `INSERT INTO t (body) VALUES ('after the migration')`) |
| + h2 := localHeld(t, backend, 10*time.Second) |
| + h2.replicaClient = lsfile.NewReplicaClient(replica) |
| + r2, err := h2.Replicate(ctx, path, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + wakeExec(t, app, `INSERT INTO t (body) VALUES ('second wake')`) |
| + if err := r2.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + app.Close() |
| + if err := r2.Close(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + out := filepath.Join(t.TempDir(), "restored.db") |
| + opt := litestream.NewRestoreOptions() |
| + opt.OutputPath = out |
| + if err := litestream.NewReplicaWithClient(nil, lsfile.NewReplicaClient(replica)).Restore(ctx, opt); err != nil { |
| + t.Fatalf("restore: %v", err) |
| + } |
| + d, err := sql.Open("sqlite", "file:"+out+"?mode=ro") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + var ok string |
| + if err := d.QueryRow(`PRAGMA integrity_check`).Scan(&ok); err != nil || ok != "ok" { |
| + t.Fatalf("restored copy: integrity_check %q, %v", ok, err) |
| + } |
| + var m, last int |
| + if err := d.QueryRow(`SELECT count(*) FROM m`).Scan(&m); err != nil || m != tc.rows { |
| + t.Fatalf("restored copy holds %d migrated rows (%v), want %d", m, err, tc.rows) |
| + } |
| + if err := d.QueryRow(`SELECT count(*) FROM t WHERE body = 'second wake'`).Scan(&last); err != nil || last != 1 { |
| + t.Fatalf("restored copy lacks the second wake's write: %d, %v", last, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// openWakeApp opens path the way an app does: its own WAL connection, with |
| +// SQLite's default autocheckpoint. |
| +func openWakeApp(t *testing.T, path string) *sql.DB { |
| + t.Helper() |
| + d, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + d.SetMaxOpenConns(1) |
| + if err := d.Ping(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return d |
| +} |
| + |
| +func wakeExec(t *testing.T, d *sql.DB, q string) { |
| + t.Helper() |
| + if _, err := d.Exec(q); err != nil { |
| + t.Fatalf("%s: %v", q, err) |
| + } |
| +} |