carlos / platform Public

activator: restored replicas keep lease.CheckDB for rootfs rows too; the placeholder's round trip is proven through real Litestream, and zero-length, damaged and bare restores are refused (Task 7 round 1, P1 2)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev bc288b25a0e3560c942227e668a3ec32c7512206 parent 07419af
3 files changed, +194 −122
  • internal/activator/backend_exec.go +1 −1
  • internal/activator/rootfsdb.go +0 −39
  • internal/activator/rootfsdb_test.go +193 −82
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 2f23552e0..3417aeb9a 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -871,7 +871,7 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool
// that never had a snapshot — and the alternatives to failing here are
// both worse than a down route: serving a corrupt database, or (if
// this returned fresh) running the route's seed over recoverable data.
- if err := restoredDBCheck(rt)(dbPath); err != nil {
+ if err := lease.CheckDB(dbPath); err != nil {
q := dbPath + quarantineSuffix
_ = os.Remove(q) // keep exactly one: the newest failure is the evidence
if mvErr := os.Rename(dbPath, q); mvErr != nil {
diff --git a/internal/activator/rootfsdb.go b/internal/activator/rootfsdb.go
index 63caaf174..5fd50475c 100644
--- a/internal/activator/rootfsdb.go
+++ b/internal/activator/rootfsdb.go
@@ -22,7 +22,6 @@ import (
"sync"
"github.com/carlosframework/platform/internal/instancefs"
- "github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/registry"
_ "modernc.org/sqlite"
@@ -168,44 +167,6 @@ func (b *ExecBackend) PlaceRootfsDB(ctx context.Context, rt registry.Route) erro
return nil
}
-// restoredDBCheck is the proof a restored database must pass before
-// anything serves from it: lease.CheckDB (integrity and at least one table)
-// for a binary row, whose app made its own schema before its first
-// replication; checkRootfsRestoredDB for a rootfs row, whose replica may
-// be D7's placeholder and nothing more (an app that never opens CARLOS_DB),
-// which has no tables by design. Without it, the restart from the replica
-// that D7 exists for would read the placeholder as corrupt (Review Focus 8).
-func restoredDBCheck(rt registry.Route) func(path string) error {
- if rt.Rootfs() {
- return checkRootfsRestoredDB
- }
- return lease.CheckDB
-}
-
-// checkRootfsRestoredDB is CheckDB without the table count: the restored
-// file opens read-only and its integrity_check is ok. The agent restored
-// it into the instance directory itself, under the lease, before anything
-// of the instance runs, as CheckDB does for a binary row.
-func checkRootfsRestoredDB(path string) error {
- db, err := sql.Open("sqlite", "file:"+path+"?mode=ro")
- if err != nil {
- return err
- }
- defer db.Close()
- db.SetMaxOpenConns(1)
- if _, err := db.Exec("PRAGMA busy_timeout=5000"); err != nil {
- return fmt.Errorf("open: %w", err)
- }
- var res string
- if err := db.QueryRow("PRAGMA integrity_check").Scan(&res); err != nil {
- return fmt.Errorf("integrity_check: %w", err)
- }
- if res != "ok" {
- return fmt.Errorf("integrity_check: %s", res)
- }
- return nil
-}
-
// writeBeneathExcl creates dir/name beneath dir (O_EXCL, 0600), writes
// data, syncs it, and returns the identity of the file it wrote.
func writeBeneathExcl(dir, name string, data []byte) (os.FileInfo, error) {
diff --git a/internal/activator/rootfsdb_test.go b/internal/activator/rootfsdb_test.go
index 606e05acf..4309618d8 100644
--- a/internal/activator/rootfsdb_test.go
+++ b/internal/activator/rootfsdb_test.go
@@ -3,22 +3,25 @@
package activator
// D7 (Plan 3 Task 7, Astra R1 finding 8), production-wired: the real
-// ExecBackend's PlaceRootfsDB and Restore, the replica a directory the
-// test owns (restoreReplica stubbed to copy from it), and a lease whose
-// replica's first upload copies the local database there.
+// ExecBackend's PlaceRootfsDB and Restore (with its lease.CheckDB), and
+// real Litestream over local file storage for the replica: the lease's
+// replication is a litestream.DB on a file replica client, and
+// restoreReplica is litestream's own restore from that client.
import (
- "bytes"
"context"
"database/sql"
"errors"
- "io"
"os"
"path/filepath"
+ "strings"
"sync"
"testing"
"time"
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
@@ -26,8 +29,9 @@ import (
// TestPlaceRootfsDBWritesAnEmptySQLiteDatabase: the file is at the row's
// nested database path, 0600, an SQLite database in WAL mode with no
-// tables that the restore check for a rootfs row accepts (and that the
-// binary check, which wants a table, would not); a symlink, file or
+// tables (so lease.CheckDB alone would refuse it: its replica passes only
+// once Litestream has added its own tables, TestRootfsAppWithoutSQLite
+// Restarts); a symlink, file or
// directory already at the name is left exactly as it was, nothing is
// written through it, and the temp name is gone on every path.
func TestPlaceRootfsDBWritesAnEmptySQLiteDatabase(t *testing.T) {
@@ -45,11 +49,8 @@ func TestPlaceRootfsDBWritesAnEmptySQLiteDatabase(t *testing.T) {
if err != nil || !fi.Mode().IsRegular() || fi.Mode().Perm() != 0o600 {
t.Fatalf("placed %v, %v: want a regular 0600 file", fi, err)
}
- if err := checkRootfsRestoredDB(dbPath); err != nil {
- t.Fatalf("the rootfs restore check refuses the placeholder: %v", err)
- }
if err := lease.CheckDB(dbPath); err == nil {
- t.Fatal("lease.CheckDB accepted a database with no tables: the rootfs check is no longer the only one that must")
+ t.Fatal("lease.CheckDB accepted a bare placeholder with no tables")
}
db, err := sql.Open("sqlite", "file:"+dbPath+"?mode=ro")
if err != nil {
@@ -127,8 +128,8 @@ func assertNoTemp(t *testing.T, dir string) {
}
}
-// bucketRig is the replica side of TestRootfsAppWithoutSQLiteRestarts: a
-// directory standing in for the instance's replica prefix.
+// bucketRig is the replica side: real Litestream over a file replica
+// client in dir, standing in for the instance's replica prefix.
type bucketRig struct {
dir string
mu sync.Mutex
@@ -136,45 +137,66 @@ type bucketRig struct {
syncs int
}
-func (r *bucketRig) replica() string { return filepath.Join(r.dir, "replica.db") }
+func (r *bucketRig) client() litestream.ReplicaClient {
+ return lsfile.NewReplicaClient(filepath.Join(r.dir, "replica"))
+}
-func copyFile(src, dst string) error {
- in, err := os.Open(src)
- if err != nil {
- return err
+// restore is lease.Restore's body over the file client: litestream's own
+// restore, and "no replica" (fresh) when it has nothing to restore.
+func (r *bucketRig) restore(ctx context.Context, dbPath string) (bool, error) {
+ if err := os.MkdirAll(filepath.Dir(dbPath), 0o700); err != nil {
+ return false, err
}
- defer in.Close()
- out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
- if err != nil {
- return err
- }
- if _, err := io.Copy(out, in); err != nil {
- out.Close()
- return err
+ rep := litestream.NewReplicaWithClient(nil, r.client())
+ opt := litestream.NewRestoreOptions()
+ opt.OutputPath = dbPath
+ if err := rep.Restore(ctx, opt); err != nil {
+ if errors.Is(err, litestream.ErrTxNotAvailable) || errors.Is(err, litestream.ErrNoSnapshots) {
+ return false, nil
+ }
+ return false, err
}
- return out.Close()
+ r.mu.Lock()
+ r.restores++
+ r.mu.Unlock()
+ return true, nil
}
-// bucketRep is the running replica: its first upload copies the local
-// database to the bucket; Close is the sleep's final checkpoint.
+// bucketRep is the running replication: a litestream.DB on the local
+// database with its own metadata directory (lease.newStore's naming), no
+// background monitor; SyncAndWait is the first upload, Close the sleep's
+// final sync.
type bucketRep struct {
- rig *bucketRig
- dbPath string
+ rig *bucketRig
+ db *litestream.DB
}
func (r *bucketRep) Err() error { return nil }
-func (r *bucketRep) SyncAndWait(context.Context) error {
+func (r *bucketRep) SyncAndWait(ctx context.Context) error {
r.rig.mu.Lock()
r.rig.syncs++
r.rig.mu.Unlock()
- return copyFile(r.dbPath, r.rig.replica())
+ return r.db.SyncAndWait(ctx)
+}
+func (r *bucketRep) Close(ctx context.Context) error {
+ if err := r.db.SyncAndWait(ctx); err != nil {
+ return err
+ }
+ return r.db.Close(ctx)
}
-func (r *bucketRep) Close(context.Context) error { return nil }
type bucketLease struct{ rig *bucketRig }
func (l bucketLease) Replicate(_ context.Context, dbPath string, _ time.Duration) (Rep, error) {
- return &bucketRep{rig: l.rig, dbPath: dbPath}, nil
+ db := litestream.NewDB(dbPath)
+ db.SetMetaPath(filepath.Join(filepath.Dir(dbPath), ".activator-"+filepath.Base(dbPath)+"-litestream"))
+ db.MonitorInterval = time.Hour
+ db.Replica = litestream.NewReplicaWithClient(db, l.rig.client())
+ db.Replica.SyncInterval = time.Hour
+ if err := db.Open(); err != nil {
+ return nil, err
+ }
+ return &bucketRep{rig: l.rig, db: db}, nil
}
func (bucketLease) Release(context.Context) error { return nil }
@@ -204,28 +226,15 @@ func (b *bucketBackend) placements() int {
return b.placed
}
-// Review Focus 8: an app that never opens CARLOS_DB restarts. Its first
-// wake places the placeholder and serves, and the replica holds it after
-// the first sync. Once it has served (GoodVersion set): (a) a wake on the
-// same box uses the warm file, with no refusal and no new placeholder;
-// (b) with the local database gone (a new box, a lost disk), Restore
-// restores the placeholder from the replica and the wake serves; (c) with
-// the replica gone too, the wake refuses with errRootfsReplicaMissing,
-// starts nothing and places nothing.
-func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) {
+// bucketService is a Service over the staged rootfs rig, with its replica
+// on real Litestream and restoreReplica restoring from it.
+func bucketService(t *testing.T) (*Service, *bucketBackend, *stagedRootfsCtl, registry.Route) {
+ t.Helper()
eb, ctl, rt := newStagedRootfsRig(t)
ctl.setServe(serveVersions(t, eb, rt, 0, "v1")) // serves, never opens CARLOS_DB
rig := &bucketRig{dir: t.TempDir()}
old := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
- rig.mu.Lock()
- defer rig.mu.Unlock()
- if _, err := os.Stat(rig.replica()); errors.Is(err, os.ErrNotExist) {
- return false, nil
- }
- rig.restores++
- return true, copyFile(rig.replica(), dbPath)
- }
+ restoreReplica = func(ctx context.Context, dbPath, _, _, _ string) (bool, error) { return rig.restore(ctx, dbPath) }
t.Cleanup(func() { restoreReplica = old })
bb := &bucketBackend{ExecBackend: eb, rig: rig}
reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
@@ -237,7 +246,64 @@ func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) {
a.gens = true
armRootfsForTest(a)
t.Cleanup(func() { a.Shutdown(context.Background()) })
+ return a, bb, ctl, rt
+}
+
+// sleepEntry stops host's awake entry and waits for it to go.
+func sleepEntry(t *testing.T, a *Service, host string) {
+ t.Helper()
+ a.mu.Lock()
+ e := a.entries[host]
+ if e == nil || e.state != actAwake {
+ a.mu.Unlock()
+ t.Fatalf("no awake entry to stop: %+v", e)
+ }
+ a.beginStopLocked(e, StopIdle)
+ a.mu.Unlock()
+ waitFor(t, "the instance to sleep", func() bool { return a.entryCount() == 0 })
+}
+
+// removeLocal is a lost disk: the database, its WAL and SHM, and
+// litestream's metadata.
+func removeLocal(t *testing.T, dbPath string) {
+ t.Helper()
+ for _, s := range []string{"", "-wal", "-shm"} {
+ if err := os.Remove(dbPath + s); err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ }
+ if err := os.RemoveAll(filepath.Join(filepath.Dir(dbPath), ".activator-"+filepath.Base(dbPath)+"-litestream")); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func hasTable(t *testing.T, dbPath, name string) bool {
+ t.Helper()
+ db, err := sql.Open("sqlite", "file:"+dbPath+"?mode=ro")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ var n int
+ if err := db.QueryRow("SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?", name).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n == 1
+}
+// Review Focus 8: an app that never opens CARLOS_DB restarts, through
+// real Litestream. Its first wake places the placeholder and serves, and
+// the replica holds it after the first sync (Litestream added its own
+// tables, so the replica is a database lease.CheckDB accepts). Once it
+// has served (GoodVersion set): (a) a wake on the same box uses the warm
+// file, with no refusal and no new placeholder; (b) with the local
+// database gone (a new box, a lost disk), Restore restores it from the
+// replica, lease.CheckDB passes, and the wake serves; (c) with the
+// replica gone too, the wake refuses with errRootfsReplicaMissing, starts
+// nothing and places nothing.
+func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) {
+ a, bb, ctl, rt := bucketService(t)
+ rig := bb.rig
wake := func() error {
done, err := a.beginRequest(context.Background(), rt)
if err == nil {
@@ -245,25 +311,6 @@ func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) {
}
return err
}
- sleep := func() {
- t.Helper()
- a.mu.Lock()
- e := a.entries[rt.Host]
- if e == nil || e.state != actAwake {
- a.mu.Unlock()
- t.Fatalf("no awake entry to stop: %+v", e)
- }
- a.beginStopLocked(e, StopIdle)
- a.mu.Unlock()
- waitFor(t, "the instance to sleep", func() bool { return a.entryCount() == 0 })
- }
- removeLocal := func() {
- for _, s := range []string{"", "-wal", "-shm"} {
- if err := os.Remove(rt.DBPath + s); err != nil && !errors.Is(err, os.ErrNotExist) {
- t.Fatal(err)
- }
- }
- }
// The first boot.
if err := wake(); err != nil {
@@ -272,12 +319,17 @@ func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) {
if bb.placements() != 1 || rig.syncs != 1 {
t.Fatalf("placements %d, first uploads %d; want 1, 1", bb.placements(), rig.syncs)
}
- local, _ := os.ReadFile(rt.DBPath)
- inBucket, err := os.ReadFile(rig.replica())
- if err != nil || len(local) == 0 || !bytes.Equal(local, inBucket) {
- t.Fatalf("the replica does not hold the placeholder after the first sync (%v)", err)
+ sleepEntry(t, a, rt.Host)
+ // What the replica holds, restored aside: the placeholder plus
+ // Litestream's own tables, which lease.CheckDB accepts.
+ aside := filepath.Join(t.TempDir(), "aside.db")
+ if ok, err := rig.restore(context.Background(), aside); !ok || err != nil {
+ t.Fatalf("the replica holds nothing after the first sync: %v %v", ok, err)
}
- sleep()
+ if err := lease.CheckDB(aside); err != nil || !hasTable(t, aside, "_litestream_seq") {
+ t.Fatalf("the replicated placeholder: CheckDB %v, _litestream_seq %v", err, hasTable(t, aside, "_litestream_seq"))
+ }
+ rig.restores = 0
rt.GoodVersion = "v1" // it has served
t.Run("a: warm on the same box", func(t *testing.T) {
@@ -287,21 +339,21 @@ func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) {
if bb.placements() != 1 || rig.restores != 0 {
t.Fatalf("placements %d, restores %d; want no new placeholder and no restore", bb.placements(), rig.restores)
}
- sleep()
+ sleepEntry(t, a, rt.Host)
})
t.Run("b: the local database is gone", func(t *testing.T) {
- removeLocal()
+ removeLocal(t, rt.DBPath)
if err := wake(); err != nil {
t.Fatalf("wake from the replica: %v", err)
}
if rig.restores != 1 || bb.placements() != 1 {
t.Fatalf("restores %d, placements %d; want the replica restored and no new placeholder", rig.restores, bb.placements())
}
- sleep()
+ sleepEntry(t, a, rt.Host)
})
t.Run("c: the replica is gone too", func(t *testing.T) {
- removeLocal()
- if err := os.Remove(rig.replica()); err != nil {
+ removeLocal(t, rt.DBPath)
+ if err := os.RemoveAll(filepath.Join(rig.dir, "replica")); err != nil {
t.Fatal(err)
}
starts := len(ctl.started())
@@ -317,3 +369,62 @@ func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) {
}
})
}
+
+// A restore that reports success but leaves something that is not a
+// database with a schema never serves a served rootfs row: a zero-length
+// file, a damaged file, and a bare placeholder that never replicated
+// Litestream's tables are each refused by lease.CheckDB, quarantined, and
+// the wake starts nothing (never the fresh && GoodVersion path bypassed).
+func TestRestoredRootfsReplicaMustPassCheckDB(t *testing.T) {
+ for name, write := range map[string]func(t *testing.T, path string){
+ "zero-length": func(t *testing.T, path string) {
+ if err := os.WriteFile(path, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ },
+ "damaged": func(t *testing.T, path string) {
+ raw, err := emptySQLiteDB()
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw = append([]byte(nil), raw...)
+ for i := 100; i < len(raw); i += 7 {
+ raw[i] ^= 0xa5
+ }
+ if err := os.WriteFile(path, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ },
+ "bare placeholder": func(t *testing.T, path string) {
+ raw, err := emptySQLiteDB()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ a, bb, ctl, rt := bucketService(t)
+ restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
+ if err := os.MkdirAll(filepath.Dir(dbPath), 0o700); err != nil {
+ return false, err
+ }
+ write(t, dbPath)
+ return true, nil
+ }
+ rt.GoodVersion = "v1"
+ _, err := a.beginRequest(context.Background(), rt)
+ if err == nil || !strings.Contains(err.Error(), "corrupt") {
+ t.Fatalf("wake = %v, want the restored replica refused as corrupt", err)
+ }
+ if len(ctl.started()) != 0 || bb.placements() != 0 {
+ t.Fatalf("starts %d, placements %d: a served row booted on a bad restore", len(ctl.started()), bb.placements())
+ }
+ if _, err := os.Stat(rt.DBPath); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the bad restore is still the live database: %v", err)
+ }
+ })
+ }
+}