carlos / platform Public

lease, activator: protect the database before anything starts

Replicate before start (#1290, round 2). A clean close writes a clean
record; every replication start deletes it first. The ordinary wake calls
ProtectStart after restore and before the seed, release commands and the
process: a database its clean close left untouched is pinned with a
SQLite read transaction until Replicate's litestream holds its own lock.
Replicate and Checkpoint (HA included) force a bounded first sync, and
when continuity is not proven require a full image (litestream's own, or
a level-9 snapshot) before returning; any failure fails the start. The
round-1 gap repair is replaced. Tests cover a failed and retried repair,
missing local metadata, a repair that times out, HA and Checkpoint.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2f3e059a5c0851f8668418b9a8b2dc14f0acab5e parent efe7200
16 files changed, +1,092 −366
  • docs/superpowers/specs/2026-11-19-replicate-before-start.md +11 −2
  • internal/activator/activator.go +27 −2
  • internal/activator/activator_test.go +62 −0
  • internal/activator/backend_exec.go +25 −1
  • internal/activator/harelease_test.go +8 −0
  • internal/activator/size_identical_test.go +2 −0
  • internal/lease/checkpoint.go +18 −1
  • internal/lease/continuity.go +431 −0
  • internal/lease/continuity_test.go +294 −0
  • internal/lease/fence_test.go +8 −1
  • internal/lease/ha_continuity_test.go +127 −0
  • internal/lease/lease.go +22 −9
  • internal/lease/protect_test.go +51 −0
  • internal/lease/release.go +6 −0
  • internal/lease/wakegap.go +0 −215
  • internal/lease/wakegap_test.go +0 −135
diff --git a/docs/superpowers/specs/2026-11-19-replicate-before-start.md b/docs/superpowers/specs/2026-11-19-replicate-before-start.md
index 56a36c09f..6ea8cb039 100644
--- a/docs/superpowers/specs/2026-11-19-replicate-before-start.md
+++ b/docs/superpowers/specs/2026-11-19-replicate-before-start.md
@@ -28,7 +28,11 @@ Two mechanisms carry it, both in `internal/lease`:
process makes stays in the WAL until litestream reads it. `Replicate`
takes the pin over. It releases the pin only after litestream's own init
has taken its read lock (a forced, bounded local sync). If the files are
- not continuous, nothing is pinned and `Replicate` snapshots instead.
+ not continuous, nothing is pinned, and `Replicate` makes sure the replica
+ restarts from a full image before it returns. That image is litestream's
+ own first file when that file holds every page (a first replication, or
+ a WAL litestream saw truncated). Otherwise `Replicate` writes a level-9
+ snapshot of the live file.
## Wake paths
@@ -49,6 +53,9 @@ Two mechanisms carry it, both in `internal/lease`:
on every box, so it is not reordered. It still cannot serve a gap: with no
pin, `Replicate` decides continuity itself, and a process that wrote first
fails the match and gets a full snapshot before `Publish`.
+- **Unit tenants and demos.** A unit tenant is replicated by the box-wide
+ litestream unit, which runs all the time, so it has no start gap. A
+ demo's lease is local. Neither takes a pin.
- **First start (no database file).** The process starts first, and
`Replicate` writes a full snapshot before the wake serves. No bootstrap
file: creating the database ahead of the app would fix `page_size`,
@@ -60,7 +67,9 @@ Two mechanisms carry it, both in `internal/lease`:
## Failure behaviour
`ProtectStart` failing (pin or record I/O) fails the wake before anything
-starts. `Replicate`'s init is bounded (`firstSyncTimeout`, 30 s). If it
+starts. litestream's init reads the replica's position, so a replica that
+cannot be reached now fails the wake too, where before the wake served and
+replication lagged. That is the price of "never unprotected". `Replicate`'s init is bounded (`firstSyncTimeout`, 30 s). If it
fails or times out, `Replicate` fails, and the wake goes through
`cleanupFailedWake` (process stopped, lease back). That is High 3. The
person sees the wake fail with "replicate <host>: ..." in `carlos logs
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 9d55096b4..0d3f63da6 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -382,6 +382,15 @@ func leaseLost(l Lease) error {
return nil
}
+// startProtector is a lease that protects its database before anything
+// that can write it starts (lease.ProtectStart; spec
+// 2026-11-19-replicate-before-start.md). A lease without it (a unit
+// tenant's, replicated by the box-wide unit; a demo's local lease) starts
+// as before.
+type startProtector interface {
+ ProtectStart(dbPath string) error
+}
+
// Lease is a held-but-not-yet-replicating lease (wake in progress; Eleven's
// actLease).
type Lease interface {
@@ -3200,6 +3209,21 @@ func (a *Service) doWakeOnce(ctx context.Context, e *actEntry) (*wokenInstance,
ctx = withStorageMode(ctx, rt, id, false, digest)
}
+ // 2c. Replicate before start (spec 2026-11-19-replicate-before-start.md,
+ // discussion #1290): nothing that can write the database (the seed, a
+ // release command, the process) starts before it is protected. A
+ // database exactly as its last clean close left it is pinned, so every
+ // frame the start writes stays in the WAL until Replicate's litestream
+ // reads it; any other is snapshotted by Replicate before the wake
+ // serves. A lease that cannot protect refuses the start.
+ if p, ok := lease.(startProtector); ok {
+ if err := p.ProtectStart(rt.DBPath); err != nil {
+ w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease)
+ return w, fmt.Errorf("protect %s: %w", host, err)
+ }
+ w.steps.mark(a.now(), "protect")
+ }
+
// 3. First-boot seed, strictly between the restore and the spawn — so it
// runs before Start's first health probe, and a brand-new instance is born
// seeded rather than briefly serving an empty database. fresh is the
@@ -3236,8 +3260,9 @@ func (a *Service) doWakeOnce(ctx context.Context, e *actEntry) (*wokenInstance,
// 4. Spawn before replication starts: a fresh instance creates its own DB
// on boot, so waiting for the socket guarantees the file exists for
- // litestream to open. Writes that land in the gap are picked up by the
- // replica's first sync.
+ // litestream to open. Writes that land before replication are kept in
+ // the WAL by step 2c's pin, or covered by the snapshot Replicate takes
+ // when continuity was not proven.
//
// Both doors are TIMED, because this is the half an app CANNOT see.
// Backend.Start execs the binary and waits until its socket accepts, so it
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go
index c7cfa56a1..aff3f39da 100644
--- a/internal/activator/activator_test.go
+++ b/internal/activator/activator_test.go
@@ -266,9 +266,24 @@ type fakeLease struct {
owed bool
}
+// ProtectStart is startProtector: it records "protect" in the order log
+// and answers b.protectErr.
+func (l *fakeLease) ProtectStart(string) error {
+ if l.b == nil {
+ return nil
+ }
+ l.b.mu.Lock()
+ defer l.b.mu.Unlock()
+ l.b.order = append(l.b.order, "protect")
+ return l.b.protectErr
+}
+
func (l *fakeLease) Replicate(_ context.Context, _ string, syncInterval time.Duration) (Rep, error) {
if l.b != nil {
l.b.mu.Lock()
+ if l.b.logReplicate {
+ l.b.order = append(l.b.order, "replicate")
+ }
l.b.syncIntervals = append(l.b.syncIntervals, syncInterval)
wrap := l.b.repWrap
l.b.mu.Unlock()
@@ -384,6 +399,11 @@ type fakeBackend struct {
// "a restored instance is never seeded" case.
restoreFresh bool
restoreErr error
+ // protectErr is what the lease's ProtectStart answers (replicate
+ // before start, #1290); logReplicate puts each Replicate in the order
+ // log too.
+ protectErr error
+ logReplicate bool
seedErr error
seedRoutes []registry.Route
startErr error
@@ -7322,3 +7342,45 @@ func TestAPendingFlagOffStopProvesTheHostCgroupBeforeTheLeaseGoes(t *testing.T)
}
func (b *fakeBackend) poolEligible(registry.Route) bool { return true }
+
+// --- replicate before start (#1290) ------------------------------------------
+//
+// Nothing that can write the database starts before the lease protects it
+// (spec 2026-11-19-replicate-before-start.md): protect comes after the
+// restore and before the seed and the process.
+
+func TestWakeProtectsTheDatabaseBeforeAnythingStarts(t *testing.T) {
+ a, b, _, _ := testActivator(t, time.Minute)
+ b.restoreFresh = true
+ b.logReplicate = true
+ rt := testRoute("protect.example.com")
+ rt.Seed = `["seed"]`
+ release, err := a.beginRequest(context.Background(), rt)
+ if err != nil {
+ t.Fatalf("beginRequest: %v", err)
+ }
+ release()
+ ev := b.events()
+ r, p, s, st, rep := indexOf(ev, "restore"), indexOf(ev, "protect"), indexOf(ev, "seed"), indexOf(ev, "start:instance"), indexOf(ev, "replicate")
+ if r == -1 || p == -1 || s == -1 || st == -1 || rep == -1 || !(r < p && p < s && s < st && st < rep) {
+ t.Fatalf("order %v, want restore < protect < seed < start:instance < replicate", ev)
+ }
+}
+
+func TestWakeThatCannotProtectStartsNothing(t *testing.T) {
+ a, b, _, _ := testActivator(t, time.Minute)
+ b.protectErr = errors.New("pin refused")
+ rt := testRoute("unprotected.example.com")
+ if _, err := a.beginRequest(context.Background(), rt); err == nil || !strings.Contains(err.Error(), "pin refused") {
+ t.Fatalf("beginRequest: %v, want the protection's refusal", err)
+ }
+ b.mu.Lock()
+ starts, releases := b.starts, b.releases
+ b.mu.Unlock()
+ if starts != 0 {
+ t.Fatalf("%d starts after a refused protection, want 0", starts)
+ }
+ if releases != 1 {
+ t.Fatalf("%d lease releases, want 1", releases)
+ }
+}
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 88f0dec31..a3b59fafc 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -952,6 +952,27 @@ type execLease struct {
// take's retirement in the background (startRetirement).
replicating func(*lease.Replicator)
replicatingOnce sync.Once
+ // protected is the start protection ProtectStart took (lease
+ // ProtectStart): Replicate takes it over, and a lease given back
+ // without replicating drops it.
+ protected atomic.Pointer[lease.Protection]
+}
+
+// ProtectStart is startProtector: the database is protected (continuity
+// decided, a continuous one pinned) before anything that can write it
+// starts. An error means nothing may start.
+func (l *execLease) ProtectStart(dbPath string) error {
+ if dbPath == "" {
+ dbPath = l.defaultDB
+ }
+ p, err := lease.ProtectStart(dbPath)
+ if err != nil {
+ return err
+ }
+ if old := l.protected.Swap(p); old != nil && old != p {
+ old.Drop()
+ }
+ return nil
}
func (l *execLease) Replicate(ctx context.Context, dbPath string, syncInterval time.Duration) (Rep, error) {
@@ -1004,7 +1025,10 @@ var (
_ interface{ SyncAndWait(context.Context) error } = (*lease.Replicator)(nil)
)
-func (l *execLease) Release(ctx context.Context) error { return l.held.Release(ctx) }
+func (l *execLease) Release(ctx context.Context) error {
+ l.protected.Load().Drop()
+ return l.held.Release(ctx)
+}
// RetryRelease is releaseRetrier: the held lease's conditional retry of a
// release that failed (#292).
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go
index de97a2ea8..97eafcabb 100644
--- a/internal/activator/harelease_test.go
+++ b/internal/activator/harelease_test.go
@@ -904,6 +904,14 @@ func (s *haSvc) wakePathRequests(reqs []string) []string {
if level, ok := strings.CutPrefix(r, "LIST "+prefix); ok && isReplicaLevelDir(level) {
continue
}
+ // A compaction into levels 1-8 is the store's monitor finishing
+ // the last session's work. Replicate's first sync (replicate
+ // before start, #1290) readies the store before the monitor's
+ // first pass, so one can land inside the wake. Snapshots (level 9)
+ // and L0 files still count.
+ if rel, ok := strings.CutPrefix(r, "PUT "+prefix); ok && len(rel) > 5 && isReplicaLevelDir(rel[:5]) && rel[:4] >= "0001" && rel[:4] <= "0008" {
+ continue
+ }
// The same listing under a storage generation (g-N/NNNN/): the
// replicator of a generations wake writes there.
if rel, ok := strings.CutPrefix(r, "LIST "+prefix+"g-"); ok {
diff --git a/internal/activator/size_identical_test.go b/internal/activator/size_identical_test.go
index 17f6aef23..b71fd5615 100644
--- a/internal/activator/size_identical_test.go
+++ b/internal/activator/size_identical_test.go
@@ -264,6 +264,7 @@ func TestNoSizeColumnSwapIsMains(t *testing.T) {
// 953b9fda: the fixture's wake, then the swap's events.
want := []string{
"restore",
+ "protect", // replicate before start (#1290)
"start:instance",
"raise:1073741824+536870912",
"startGen:" + f.staged,
@@ -290,6 +291,7 @@ func TestNoSizeColumnSwapIsMains(t *testing.T) {
// 953b9fda: the fixture's wake, then the failed swap's events.
want := []string{
"restore",
+ "protect", // replicate before start (#1290)
"start:instance",
"raise:1073741824+536870912",
"startGen:" + f.staged,
diff --git a/internal/lease/checkpoint.go b/internal/lease/checkpoint.go
index 573208fdd..b6db62284 100644
--- a/internal/lease/checkpoint.go
+++ b/internal/lease/checkpoint.go
@@ -3,6 +3,7 @@ package lease
import (
"context"
"errors"
+ "log"
"time"
)
@@ -37,15 +38,31 @@ func (h *Held) Checkpoint(ctx context.Context, dbPath string) (receipt Checkpoin
store.CompactionMonitorEnabled = false
store.L0RetentionCheckInterval = 0
store.SetRetentionEnabled(false)
+ // Replicate before start (continuity.go): a checkpoint that cannot
+ // prove the files continue the replica's last clean close snapshots
+ // before its receipt.
+ pin, continuous, err := beginContinuity(dbPath)
+ if err != nil {
+ return receipt, err
+ }
+ defer pin.Release()
openErr := store.Open(opCtx)
var syncErr error
if openErr == nil {
- syncErr = db.SyncAndWait(opCtx)
+ syncErr = startProtected(opCtx, db, continuous)
+ if syncErr == nil {
+ syncErr = db.SyncAndWait(opCtx)
+ }
}
if openErr != nil || syncErr != nil {
cancel()
}
closeErr := store.Close(opCtx)
+ if openErr == nil && syncErr == nil && closeErr == nil {
+ if rerr := recordClean(dbPath); rerr != nil {
+ log.Printf("lease: %s: clean record: %v (the next start snapshots)", dbPath, rerr)
+ }
+ }
until, healthErr := h.rn.SafeUntil()
err = errors.Join(openErr, syncErr, closeErr, healthErr, opCtx.Err())
if err != nil {
diff --git a/internal/lease/continuity.go b/internal/lease/continuity.go
new file mode 100644
index 000000000..cc91c1222
--- /dev/null
+++ b/internal/lease/continuity.go
@@ -0,0 +1,431 @@
+package lease
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
+)
+
+// Replicate before start (docs/superpowers/specs/2026-11-19-replicate-
+// before-start.md, discussion #1290). The invariant: a replica either
+// continues, without a gap, the WAL its last clean close left, or starts
+// from a full snapshot of the live file, and a wake does not serve until
+// one of the two is true.
+//
+// The clean record says which. A close whose final sync and store close
+// succeeded writes it. Every start of replication deletes it first, so a
+// crash, a lost meta directory, a restore, a process that wrote while
+// nothing replicated, or a repair that failed all leave no record that
+// matches, and the next start snapshots.
+//
+// The start pin keeps a continuous database continuous across a process
+// start. While a SQLite reader is held, the WAL can restart at most once
+// and no frame written after the reader began can be backfilled, so
+// whatever the process writes stays in the WAL until litestream reads it.
+
+// cleanRecordName is the clean record's file in the litestream meta
+// directory: losing the directory loses the record with it.
+const cleanRecordName = "carlos-clean.json"
+
+// metaPathOf is the replicator's litestream meta directory for dbPath (the
+// activator namespace newStore sets).
+func metaPathOf(dbPath string) string {
+ return filepath.Join(filepath.Dir(dbPath), ".activator-"+filepath.Base(dbPath)+"-litestream")
+}
+
+// cleanRecord is the state a clean close left: the newest local L0 file
+// and the database and WAL exactly as they were.
+type cleanRecord struct {
+ V int `json:"v"`
+ TXID uint64 `json:"txid"`
+ DBSize int64 `json:"db_size"`
+ DBMod int64 `json:"db_mtime_ns"`
+ WALSize int64 `json:"wal_size"`
+ WALMod int64 `json:"wal_mtime_ns"`
+}
+
+// currentState is the record the files would make now. ok is false when
+// the database or the local L0 history cannot be read: nothing to prove
+// continuity with.
+func currentState(dbPath string) (cleanRecord, bool) {
+ fi, err := os.Stat(dbPath)
+ if err != nil {
+ return cleanRecord{}, false
+ }
+ rec := cleanRecord{V: 1, DBSize: fi.Size(), DBMod: fi.ModTime().UnixNano(), WALSize: -1}
+ switch wi, err := os.Stat(dbPath + "-wal"); {
+ case err == nil:
+ rec.WALSize, rec.WALMod = wi.Size(), wi.ModTime().UnixNano()
+ case !errors.Is(err, os.ErrNotExist):
+ return cleanRecord{}, false
+ }
+ ents, err := os.ReadDir(filepath.Join(metaPathOf(dbPath), "ltx", "0"))
+ if err != nil {
+ return cleanRecord{}, false
+ }
+ for _, e := range ents {
+ if _, hi, err := ltx.ParseFilename(e.Name()); err == nil && uint64(hi) > rec.TXID {
+ rec.TXID = uint64(hi)
+ }
+ }
+ return rec, rec.TXID != 0
+}
+
+// isContinuous reports whether the files are exactly as a clean close left
+// them. Anything unreadable is not proof.
+func isContinuous(dbPath string) bool {
+ raw, err := os.ReadFile(filepath.Join(metaPathOf(dbPath), cleanRecordName))
+ if err != nil {
+ return false
+ }
+ var rec cleanRecord
+ if json.Unmarshal(raw, &rec) != nil || rec.V != 1 {
+ return false
+ }
+ now, ok := currentState(dbPath)
+ return ok && now == rec
+}
+
+// recordClean writes the clean record for dbPath's files as they are now.
+// Called only after a final sync and a store close that both succeeded.
+func recordClean(dbPath string) error {
+ rec, ok := currentState(dbPath)
+ if !ok {
+ return nil // nothing to vouch for: the next start snapshots
+ }
+ raw, err := json.Marshal(rec)
+ if err != nil {
+ return err
+ }
+ dir := metaPathOf(dbPath)
+ tmp := filepath.Join(dir, cleanRecordName+".tmp")
+ f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
+ if err != nil {
+ return err
+ }
+ if _, err = f.Write(raw); err == nil {
+ err = f.Sync()
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err == nil {
+ err = os.Rename(tmp, filepath.Join(dir, cleanRecordName))
+ }
+ if err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ return syncDir(dir)
+}
+
+// clearClean deletes the clean record, durably, before replication of
+// dbPath starts.
+func clearClean(dbPath string) error {
+ dir := metaPathOf(dbPath)
+ err := os.Remove(filepath.Join(dir, cleanRecordName))
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ return nil
+ case err != nil:
+ return err
+ }
+ return syncDir(dir)
+}
+
+// Protection is one database's start: whether it was continuous, and the
+// pin that keeps it so until Replicate's litestream holds its own lock.
+type Protection struct {
+ path string
+ continuous bool
+ db *sql.DB
+ tx *sql.Tx
+}
+
+// Continuous reports whether the database was exactly as its last clean
+// close left it, and is pinned.
+func (p *Protection) Continuous() bool { return p != nil && p.continuous }
+
+// Release drops the pin. Safe on nil and more than once.
+func (p *Protection) Release() {
+ if p == nil {
+ return
+ }
+ if p.tx != nil {
+ _ = p.tx.Rollback()
+ p.tx = nil
+ }
+ if p.db != nil {
+ _ = p.db.Close()
+ p.db = nil
+ }
+}
+
+var starts = struct {
+ sync.Mutex
+ m map[string]*Protection
+}{m: map[string]*Protection{}}
+
+// ProtectStart runs before anything that can write dbPath starts. It
+// decides continuity, deletes the clean record, and pins a continuous
+// database. Replicate (or Checkpoint) of the same path takes the pin over.
+// An error means the start must not happen.
+func ProtectStart(dbPath string) (*Protection, error) {
+ ReleaseStart(dbPath)
+ cont := isContinuous(dbPath)
+ if err := clearClean(dbPath); err != nil {
+ return nil, fmt.Errorf("lease: clear the clean record of %s: %w", dbPath, err)
+ }
+ p := &Protection{path: dbPath}
+ if cont {
+ pinned, err := p.pin()
+ if err != nil {
+ return nil, fmt.Errorf("lease: pin %s before start: %w", dbPath, err)
+ }
+ p.continuous = pinned
+ }
+ starts.Lock()
+ starts.m[dbPath] = p
+ starts.Unlock()
+ return p, nil
+}
+
+// Drop releases p if it is still the pending protection of its path (a
+// start that will not reach Replicate). A later start's protection of the
+// same path is left alone.
+func (p *Protection) Drop() {
+ if p == nil {
+ return
+ }
+ starts.Lock()
+ if starts.m[p.path] == p {
+ delete(starts.m, p.path)
+ }
+ starts.Unlock()
+ p.Release()
+}
+
+// ReleaseStart drops dbPath's pending protection, if any: a start that
+// will not reach Replicate.
+func ReleaseStart(dbPath string) {
+ takeStart(dbPath).Release()
+}
+
+func takeStart(dbPath string) *Protection {
+ starts.Lock()
+ defer starts.Unlock()
+ p := starts.m[dbPath]
+ delete(starts.m, dbPath)
+ return p
+}
+
+// pin opens a read transaction on a WAL-mode database whose WAL and
+// shared-memory files already exist (a clean close leaves both). It
+// creates nothing and changes no mode: anything else is not pinned, and
+// Replicate snapshots instead.
+func (p *Protection) pin() (bool, error) {
+ for _, f := range []string{p.path + "-wal", p.path + "-shm"} {
+ if _, err := os.Stat(f); err != nil {
+ return false, nil
+ }
+ }
+ db, err := sql.Open("sqlite", "file:"+p.path+"?_pragma=busy_timeout(5000)")
+ if err != nil {
+ return false, err
+ }
+ db.SetMaxOpenConns(1)
+ var mode string
+ if err := db.QueryRow(`PRAGMA journal_mode`).Scan(&mode); err != nil {
+ db.Close()
+ return false, err
+ }
+ if mode != "wal" {
+ db.Close()
+ return false, nil
+ }
+ tx, err := db.Begin()
+ if err != nil {
+ db.Close()
+ return false, err
+ }
+ var n int
+ if err := tx.QueryRow(`SELECT count(*) FROM sqlite_master`).Scan(&n); err != nil {
+ _ = tx.Rollback()
+ db.Close()
+ return false, err
+ }
+ p.db, p.tx = db, tx
+ return true, nil
+}
+
+// beginContinuity is where Replicate and Checkpoint decide: the pin a
+// ProtectStart left, or, with none, the files' own state now. The clean
+// record is gone either way once it returns.
+func beginContinuity(dbPath string) (*Protection, bool, error) {
+ if p := takeStart(dbPath); p != nil {
+ return p, p.continuous, nil
+ }
+ cont := isContinuous(dbPath)
+ if err := clearClean(dbPath); err != nil {
+ return nil, false, fmt.Errorf("lease: clear the clean record of %s: %w", dbPath, err)
+ }
+ return nil, cont, nil
+}
+
+// firstSyncTimeout bounds the forced first sync that takes litestream's
+// read lock; gapSnapshotTimeout bounds a snapshot when continuity is not
+// proven. Either failing fails the start.
+var (
+ firstSyncTimeout = 30 * time.Second
+ gapSnapshotTimeout = 2 * time.Minute
+)
+
+// startProtected is the first sync of a replication start, and, when
+// continuity is not proven, the full image the replica restarts from. It
+// returns once litestream holds its read lock and the replica either
+// continues or holds that image, or with the error that means the start
+// must not serve.
+//
+// The image is litestream's own when its first sync was a full one (a
+// first replication, or a WAL it could see was truncated or overwritten):
+// that file is captured locally and the monitor uploads it, as any other.
+// Otherwise a snapshot of the live file is written to the replica now.
+func startProtected(ctx context.Context, db *litestream.DB, continuous bool) error {
+ if _, err := os.Stat(db.Path()); errors.Is(err, os.ErrNotExist) {
+ // A first start whose process has not created its file: nothing
+ // to lose. Local state was reset, so litestream's first sync of
+ // the file is a full image.
+ return nil
+ }
+ before := newestLocalL0(db)
+ sctx, cancel := context.WithTimeout(ctx, firstSyncTimeout)
+ err := db.Sync(sctx)
+ cancel()
+ if err == nil && db.PageSize() == 0 {
+ err = errors.New("the database did not initialize")
+ }
+ if err != nil {
+ return fmt.Errorf("lease: first sync of %s: %w", db.Path(), err)
+ }
+ if continuous {
+ return nil
+ }
+ if path, ok := firstLocalL0After(db, before); ok && fullImage(path) {
+ return nil
+ }
+ sctx, cancel = context.WithTimeout(ctx, gapSnapshotTimeout)
+ defer cancel()
+ pos, err := db.Pos()
+ if err != nil {
+ return fmt.Errorf("lease: position of %s: %w", db.Path(), err)
+ }
+ info, err := writeSnapshot(sctx, db)
+ if err != nil {
+ // litestream's own snapshot monitor runs at Open and, when a
+ // snapshot is due, writes the same file at the same moment.
+ // Either copy will do if it reaches this position.
+ have, lerr := db.Replica.MaxLTXFileInfo(sctx, litestream.SnapshotLevel)
+ if lerr != nil || have.MinTXID != 1 || have.MaxTXID < pos.TXID {
+ return fmt.Errorf("lease: snapshot of %s (continuity not proven): %w", db.Path(), err)
+ }
+ info = &have
+ }
+ log.Printf("lease: %s: continuity with the last clean close not proven; snapshot 1-%s written before serving", db.Path(), info.MaxTXID)
+ return nil
+}
+
+// newestLocalL0 is the highest TXID among the local L0 files (0: none).
+func newestLocalL0(db *litestream.DB) ltx.TXID {
+ ents, _ := os.ReadDir(db.LTXLevelDir(0))
+ var hi ltx.TXID
+ for _, e := range ents {
+ if _, max, err := ltx.ParseFilename(e.Name()); err == nil && max > hi {
+ hi = max
+ }
+ }
+ return hi
+}
+
+// firstLocalL0After is the oldest local L0 file starting after txid: the
+// first file this start's sync wrote.
+func firstLocalL0After(db *litestream.DB, txid ltx.TXID) (string, bool) {
+ ents, err := os.ReadDir(db.LTXLevelDir(0))
+ if err != nil {
+ return "", false
+ }
+ var lo, hi ltx.TXID
+ for _, e := range ents {
+ min, max, err := ltx.ParseFilename(e.Name())
+ if err != nil || min <= txid {
+ continue
+ }
+ if lo == 0 || min < lo {
+ lo, hi = min, max
+ }
+ }
+ if lo == 0 {
+ return "", false
+ }
+ return db.LTXPath(0, lo, hi), 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 it snapshots. An incremental file stops being contiguous at
+// its first unchanged page, so this reads only that far. Anything
+// unreadable is not a full image.
+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 h.Commit > 0 && want > h.Commit
+}
+
+// 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/continuity_test.go b/internal/lease/continuity_test.go
new file mode 100644
index 000000000..88eb2f1bd
--- /dev/null
+++ b/internal/lease/continuity_test.go
@@ -0,0 +1,294 @@
+package lease
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+)
+
+// Replicate before start (docs/superpowers/specs/2026-11-19-replicate-
+// before-start.md, discussion #1290). A wake used to start the process
+// before Replicate. A large write in that gap (a schema migration on boot)
+// trips SQLite's autocheckpoint, the next write restarts the WAL, and
+// litestream v0.5.14 carries on incrementally from the new WAL: the
+// replica lacks every migrated page and each restore after it is
+// malformed.
+
+// gapRig is one database replicated to one local replica directory across
+// several wakes.
+type gapRig struct {
+ t *testing.T
+ backend *lockStore
+ path string
+ replica string
+ rows int // rows the migration wrote
+}
+
+func newGapRig(t *testing.T) *gapRig {
+ t.Helper()
+ g := &gapRig{t: t, backend: &lockStore{}, path: filepath.Join(t.TempDir(), "app.db"), replica: t.TempDir()}
+ seedDB(t, g.path)
+ return g
+}
+
+func (g *gapRig) held(client litestream.ReplicaClient) *Held {
+ g.t.Helper()
+ h := localHeld(g.t, g.backend, 10*time.Second)
+ if client == nil {
+ client = lsfile.NewReplicaClient(g.replica)
+ }
+ h.replicaClient = client
+ return h
+}
+
+// wake is a clean wake and hibernation in the order the activator keeps:
+// the process runs, Replicate, a write, the process stops, then the
+// replicator closes.
+func (g *gapRig) wake(body string) {
+ g.t.Helper()
+ ctx := context.Background()
+ app := openWakeApp(g.t, g.path)
+ r, err := g.held(nil).Replicate(ctx, g.path, 0)
+ if err != nil {
+ g.t.Fatal(err)
+ }
+ wakeExec(g.t, app, `INSERT INTO t (body) VALUES ('`+body+`')`)
+ if err := r.SyncAndWait(ctx); err != nil {
+ g.t.Fatal(err)
+ }
+ app.Close()
+ if err := r.Close(ctx); err != nil {
+ g.t.Fatal(err)
+ }
+}
+
+// migrate is a process that writes while nothing replicates: a migration
+// large enough to trip the autocheckpoint, then a write that restarts the
+// WAL. It returns the process, still running.
+func (g *gapRig) migrate(rows int) *sql.DB {
+ g.t.Helper()
+ g.rows = rows
+ app := openWakeApp(g.t, g.path)
+ wakeExec(g.t, app, `CREATE TABLE m (id INTEGER PRIMARY KEY, body TEXT)`)
+ wakeExec(g.t, app, `CREATE INDEX m_body ON m(body)`)
+ tx, err := app.Begin()
+ if err != nil {
+ g.t.Fatal(err)
+ }
+ for i := 0; i < rows; i++ {
+ if _, err := tx.Exec(`INSERT INTO m (body) VALUES (?)`, strings.Repeat(fmt.Sprint(i), 40)); err != nil {
+ g.t.Fatal(err)
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ g.t.Fatal(err)
+ }
+ wakeExec(g.t, app, `INSERT INTO t (body) VALUES ('after the migration')`)
+ return app
+}
+
+// replicateAndStop finishes a wake whose process is app: Replicate on h,
+// a write, a sync, the process stops, the replicator closes.
+func (g *gapRig) replicateAndStop(h *Held, app *sql.DB, body string) error {
+ g.t.Helper()
+ ctx := context.Background()
+ r, err := h.Replicate(ctx, g.path, 0)
+ if err != nil {
+ // The failed wake's cleanup: the process stops, the lease goes back.
+ app.Close()
+ _ = h.Release(ctx)
+ return err
+ }
+ wakeExec(g.t, app, `INSERT INTO t (body) VALUES ('`+body+`')`)
+ if err := r.SyncAndWait(ctx); err != nil {
+ g.t.Fatal(err)
+ }
+ app.Close()
+ cctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ return r.Close(cctx)
+}
+
+// restoresWhole restores the newest copy and checks it holds the
+// migration and the write after it.
+func (g *gapRig) restoresWhole(last string) {
+ g.t.Helper()
+ assertRestoresWhole(g.t, g.replica, g.rows, last)
+}
+
+func assertRestoresWhole(t *testing.T, replica string, rows int, last string) {
+ t.Helper()
+ ctx := context.Background()
+ 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, n int
+ if err := d.QueryRow(`SELECT count(*) FROM m`).Scan(&m); err != nil || m != rows {
+ t.Fatalf("restored copy holds %d migrated rows (%v), want %d", m, err, rows)
+ }
+ if err := d.QueryRow(`SELECT count(*) FROM t WHERE body = ?`, last).Scan(&n); err != nil || n != 1 {
+ t.Fatalf("restored copy lacks %q: %d, %v", last, n, err)
+ }
+}
+
+// bigMigration trips SQLite's 1000-frame autocheckpoint.
+const bigMigration = 20000
+
+// The process ran before Replicate (the claim wake's order, or any start
+// that took no pin): Replicate cannot prove continuity and snapshots.
+func TestReplicateAfterUnreplicatedWALRestartRestoresWhole(t *testing.T) {
+ for _, rows := range []int{50, bigMigration} {
+ t.Run(fmt.Sprint(rows), func(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(rows)
+ if err := g.replicateAndStop(g.held(nil), app, "second wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("second wake")
+ })
+ }
+}
+
+// failingSnapshots refuses level-9 writes while fail is set.
+type failingSnapshots struct {
+ litestream.ReplicaClient
+ fail atomic.Bool
+ hang atomic.Bool
+ tries atomic.Int32
+}
+
+func (c *failingSnapshots) WriteLTXFile(ctx context.Context, level int, lo, hi ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ if level == litestream.SnapshotLevel {
+ c.tries.Add(1)
+ if c.hang.Load() {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ if c.fail.Load() {
+ return nil, errors.New("snapshot refused")
+ }
+ }
+ return c.ReplicaClient.WriteLTXFile(ctx, level, lo, hi, r)
+}
+
+// Astra round 1, High 1: a repair that fails must be retried. Replicate
+// refuses (the wake does not serve), and the next Replicate repairs
+// again, however far the local state moved in between.
+func TestGapRepairFailureIsRetried(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ bad := &failingSnapshots{ReplicaClient: lsfile.NewReplicaClient(g.replica)}
+ bad.fail.Store(true)
+ if err := g.replicateAndStop(g.held(bad), app, "refused wake"); err == nil {
+ t.Fatal("Replicate served across a gap whose snapshot failed")
+ }
+ // The retry: a fresh process, a working replica.
+ app = openWakeApp(t, g.path)
+ if err := g.replicateAndStop(g.held(nil), app, "retried wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("retried wake")
+}
+
+// Astra round 1, High 2: missing local metadata is not proof of
+// continuity, even with a replica that already holds history.
+func TestReplicateWithoutLocalMetadataRestoresWhole(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ meta := filepath.Join(filepath.Dir(g.path), ".activator-"+filepath.Base(g.path)+"-litestream")
+ if err := os.RemoveAll(meta); err != nil {
+ t.Fatal(err)
+ }
+ if err := g.replicateAndStop(g.held(nil), app, "second wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("second wake")
+}
+
+// Astra round 1, High 3: a repair whose upload times out fails Replicate
+// within its bound instead of leaving the process running unprotected,
+// and the next wake repairs.
+func TestGapRepairTimeoutFailsReplicateAndIsRetried(t *testing.T) {
+ prev := gapSnapshotTimeout
+ gapSnapshotTimeout = 300 * time.Millisecond
+ t.Cleanup(func() { gapSnapshotTimeout = prev })
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ slow := &failingSnapshots{ReplicaClient: lsfile.NewReplicaClient(g.replica)}
+ slow.hang.Store(true)
+ start := time.Now()
+ err := g.replicateAndStop(g.held(slow), app, "timed out wake")
+ if err == nil {
+ t.Fatal("Replicate returned with its repair snapshot still hanging")
+ }
+ if d := time.Since(start); d > 20*time.Second {
+ t.Fatalf("Replicate took %s on a 300 ms repair budget", d)
+ }
+ app = openWakeApp(t, g.path)
+ if err := g.replicateAndStop(g.held(nil), app, "retried wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("retried wake")
+}
+
+// Astra round 1, High 4 (moves): a checkpoint across the gap snapshots.
+func TestCheckpointAcrossGapRestoresWhole(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ defer app.Close()
+ if _, err := g.held(nil).Checkpoint(context.Background(), g.path); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("after the migration")
+}
+
+// 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)
+ }
+}
diff --git a/internal/lease/fence_test.go b/internal/lease/fence_test.go
index ed16d1536..3c75a25b8 100644
--- a/internal/lease/fence_test.go
+++ b/internal/lease/fence_test.go
@@ -418,6 +418,10 @@ func TestWriteFenceNoDatabaseNeverTrips(t *testing.T) {
t.Fatalf("WAL not frameless: %v %v", fi, err)
}
g := fencedReplicatorAt(t, haHeld(t, fx, "instances/f"), lsfile.NewReplicaClient(t.TempDir()), path)
+ // Replicate's first sync (replicate before start, #1290) writes
+ // litestream's own first frame and captures it; the rig's
+ // one-hour monitor would ship it much later, so ship it here.
+ g.syncAndWait(t)
g.steps(t, 0, 59, nil)
})
}
@@ -443,10 +447,13 @@ func TestWriteFenceUncapturedAtFirstLook(t *testing.T) {
haBox(t)
fx := leasetest.NewLockFixture(t)
c := newFailingReplica(t)
- c.down.Store(true)
path := tempDB(t)
holdOpen(t, path)
+ // The replica goes down once Replicate has started: its first sync
+ // (replicate before start, #1290) needs it, and a start that cannot
+ // reach it does not serve.
g := fencedReplicatorAt(t, haHeld(t, fx, "instances/f"), c, path)
+ c.down.Store(true)
t.Cleanup(func() { c.down.Store(false) }) // before the rig's Close
addRows(t, path, 3)
if fi, err := os.Stat(path + "-wal"); err != nil || fi.Size() <= 32 {
diff --git a/internal/lease/ha_continuity_test.go b/internal/lease/ha_continuity_test.go
new file mode 100644
index 000000000..99c557316
--- /dev/null
+++ b/internal/lease/ha_continuity_test.go
@@ -0,0 +1,127 @@
+package lease_test
+
+import (
+ "database/sql"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ leasetest "github.com/carlosframework/platform/internal/lease/locktest"
+)
+
+// Astra round 1, High 4 (HA): an HA lease's Replicate across a gap (the
+// process migrated before replication began) snapshots like any other, so
+// the newest restore is whole (discussion #1290).
+func TestHAReplicateAcrossGapRestoresWhole(t *testing.T) {
+ haBox(t)
+ fx := leasetest.NewLockFixture(t)
+ replica := t.TempDir()
+ path := tempDB(t)
+
+ // A first wake under an ordinary lease, closed cleanly.
+ h, err := lease.Acquire(ctx, fx.Bucket, "instances/first", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ lease.SetReplicaClientForTest(h, lsfile.NewReplicaClient(replica))
+ app := openApp(t, path)
+ r, err := h.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ execOn(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)
+ }
+
+ // The process migrates before replication starts.
+ const rows = 20000
+ app = openApp(t, path)
+ execOn(t, app, `CREATE TABLE m (id INTEGER PRIMARY KEY, body TEXT)`)
+ execOn(t, app, `CREATE INDEX m_body ON m(body)`)
+ tx, err := app.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 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)
+ }
+ execOn(t, app, `INSERT INTO t (body) VALUES ('after the migration')`)
+
+ // The HA wake.
+ ha, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/ha", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1"}, hafresh.Proofs{LocalEligible: func() bool { return true }}, lease.LeaseTTL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lease.SetReplicaClientForTest(ha, lsfile.NewReplicaClient(replica))
+ hr, err := ha.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ execOn(t, app, `INSERT INTO t (body) VALUES ('ha wake')`)
+ if err := hr.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ app.Close()
+ if err := hr.ReleaseMarker(ctx, hafresh.Marker{V: 1, Clean: true}); 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, n int
+ if err := d.QueryRow(`SELECT count(*) FROM m`).Scan(&m); err != nil || m != rows {
+ t.Fatalf("restored copy holds %d migrated rows (%v), want %d", m, err, rows)
+ }
+ if err := d.QueryRow(`SELECT count(*) FROM t WHERE body = 'ha wake'`).Scan(&n); err != nil || n != 1 {
+ t.Fatalf("restored copy lacks the HA wake's write: %d, %v", n, err)
+ }
+}
+
+func openApp(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 execOn(t *testing.T, d *sql.DB, q string) {
+ t.Helper()
+ if _, err := d.Exec(q); err != nil {
+ t.Fatalf("%s: %v", q, err)
+ }
+}
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index fb0d20fef..c963b9398 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -455,19 +455,25 @@ 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)
+ // Replicate before start (continuity.go): the pin a ProtectStart left,
+ // or the files' own state, decides whether the replica can continue.
+ pin, continuous, err := beginContinuity(dbPath)
+ if err != nil {
+ return nil, err
+ }
+ defer pin.Release()
+ if _, serr := os.Stat(dbPath); errors.Is(serr, os.ErrNotExist) {
+ // A first start: no history of this file can be continued.
+ if err := db.ResetLocalState(opCtx); err != nil {
+ return nil, err
+ }
+ }
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 {
+ if err := startProtected(opCtx, db, continuous); err != nil {
cancel()
closeErr := store.Close(opCtx)
return nil, errors.Join(err, closeErr)
@@ -498,7 +504,7 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
db := litestream.NewDB(dbPath)
// Preserve the activator namespace: sharing the default metadata directory
// with another replicator corrupts shadow state even across sequential runs.
- db.SetMetaPath(filepath.Join(filepath.Dir(dbPath), ".activator-"+filepath.Base(dbPath)+"-litestream"))
+ db.SetMetaPath(metaPathOf(dbPath))
db.MonitorInterval = dbMonitorInterval
h.mu.Lock()
h.stored = true
@@ -792,6 +798,13 @@ func (r *Replicator) teardownAndRelease(ctx context.Context) error {
}
err := r.store.Close(ctx)
r.closeDone()
+ if err == nil {
+ // The final sync and the close succeeded: the files as they are
+ // now are what the replica holds (continuity.go).
+ if rerr := recordClean(r.db.Path()); rerr != nil {
+ log.Printf("lease: %s: clean record: %v (the next start snapshots)", r.db.Path(), rerr)
+ }
+ }
lease := r.rn.stop()
if lease != nil {
diff --git a/internal/lease/protect_test.go b/internal/lease/protect_test.go
new file mode 100644
index 000000000..59e3f9c5d
--- /dev/null
+++ b/internal/lease/protect_test.go
@@ -0,0 +1,51 @@
+package lease
+
+import (
+ "testing"
+
+ lsfile "github.com/benbjohnson/litestream/file"
+)
+
+// The start pin: taken before the process starts, it keeps every frame the
+// process writes in the WAL until Replicate's litestream reads it, so a
+// continuous database needs no snapshot even across a large migration.
+func TestProtectStartKeepsBootWritesWithoutSnapshot(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ p, err := ProtectStart(g.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !p.Continuous() {
+ t.Fatal("a database its clean close left untouched is not continuous")
+ }
+ app := g.migrate(bigMigration)
+ refuse := &failingSnapshots{ReplicaClient: lsfile.NewReplicaClient(g.replica)}
+ refuse.fail.Store(true)
+ if err := g.replicateAndStop(g.held(refuse), app, "pinned wake"); err != nil {
+ t.Fatalf("a pinned wake needed a snapshot: %v", err)
+ }
+ g.restoresWhole("pinned wake")
+}
+
+// A database written while nothing replicated it is not continuous, and
+// neither is one with no clean record.
+func TestProtectStartRefusesContinuityAfterOutsideWrites(t *testing.T) {
+ g := newGapRig(t)
+ if p, err := ProtectStart(g.path); err != nil || p.Continuous() {
+ t.Fatalf("no clean record: continuous %v, %v", p != nil && p.Continuous(), err)
+ }
+ ReleaseStart(g.path)
+ g.wake("first wake")
+ app := openWakeApp(t, g.path)
+ wakeExec(t, app, `INSERT INTO t (body) VALUES ('outside')`)
+ app.Close()
+ p, err := ProtectStart(g.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if p.Continuous() {
+ t.Fatal("a write after the clean close counted as continuous")
+ }
+ ReleaseStart(g.path)
+}
diff --git a/internal/lease/release.go b/internal/lease/release.go
index 1d4accff9..de4918b0a 100644
--- a/internal/lease/release.go
+++ b/internal/lease/release.go
@@ -5,6 +5,7 @@ import (
"context"
"errors"
"fmt"
+ "log"
"net/http"
"time"
@@ -285,6 +286,11 @@ func (r *Replicator) finalize(ctx context.Context, sync, snapshot bool) (uint64,
}
}
r.closeErr = r.store.Close(ctx)
+ if sync && syncErr == nil && r.closeErr == nil {
+ if rerr := recordClean(r.db.Path()); rerr != nil {
+ log.Printf("lease: %s: clean record: %v (the next start snapshots)", r.db.Path(), rerr)
+ }
+ }
r.finishTXID = uint64(r.db.Replica.Pos().TXID)
r.finishErr = errors.Join(syncErr, r.closeErr, r.rn.Err(), r.decideFinal())
if r.snapErr == nil && snapTXID != r.finishTXID {
diff --git a/internal/lease/wakegap.go b/internal/lease/wakegap.go
deleted file mode 100644
index 09d2842ae..000000000
--- a/internal/lease/wakegap.go
+++ /dev/null
@@ -1,215 +0,0 @@
-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
deleted file mode 100644
index 0f7d2a2bd..000000000
--- a/internal/lease/wakegap_test.go
+++ /dev/null
@@ -1,135 +0,0 @@
-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)
- }
-}