oficina / alta Public

alta-adopt: snapshot the state in one read transaction

A dry run's in-memory copy now comes from SQLite's online backup of the
state opened read-only, in a single step: one read transaction, WAL
contents included, consistent under a concurrent commit or checkpoint.
Nothing is copied to disk. A test snapshots while another connection
commits and checkpoints, with no writable temporary directory.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev cde5cefba93265ece4f400257a9242854e1ecdf8 parent 95853f1
3 files changed, +182 −53
  • cmd/alta-adopt/main_test.go +35 −7
  • cmd/alta-adopt/snapshot.go +28 −46
  • cmd/alta-adopt/snapshot_test.go +119 −0
diff --git a/cmd/alta-adopt/main_test.go b/cmd/alta-adopt/main_test.go
index d2a6fa2..500aa67 100644
--- a/cmd/alta-adopt/main_test.go
+++ b/cmd/alta-adopt/main_test.go
@@ -15,7 +15,6 @@ import (
"net/http/httptest"
"os"
"path/filepath"
- "reflect"
"strconv"
"strings"
"sync"
@@ -578,6 +577,39 @@ func stateOf(t *testing.T, path string) fileState {
return fileState{true, sha256.Sum256(b), fi.ModTime()}
}
+// untouched asserts the state's committed contents did not move: the
+// file's bytes and mtime are the same, a WAL that existed is the same and
+// one that did not is at most SQLite's empty one, there is no rollback
+// journal, and nothing else appeared beside the state. SQLite's -shm
+// coordination file may appear or change.
+func (r *rig) untouched(before map[string]fileState) {
+ r.t.Helper()
+ after := r.files()
+ if after[""] != before[""] {
+ r.t.Fatal("a read-only run changed the state file")
+ }
+ empty := sha256.Sum256(nil)
+ if w := after["-wal"]; before["-wal"].exists && w != before["-wal"] || !before["-wal"].exists && w.exists && w.sum != empty {
+ r.t.Fatal("a read-only run changed the WAL")
+ }
+ if after["-journal"].exists {
+ r.t.Fatal("a read-only run left a rollback journal")
+ }
+ ents, err := os.ReadDir(r.dir)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ for _, e := range ents {
+ switch strings.TrimPrefix(e.Name(), filepath.Base(r.state)) {
+ case "", "-wal", "-shm":
+ default:
+ if e.Name() != filepath.Base(r.cfgPath) {
+ r.t.Fatalf("a read-only run left %s beside the state", e.Name())
+ }
+ }
+ }
+}
+
func (r *rig) files() map[string]fileState {
r.t.Helper()
m := map[string]fileState{}
@@ -624,9 +656,7 @@ func TestDryRunLeavesStateUntouched(t *testing.T) {
t.Fatalf("setup: %+v", before)
}
out := r.readOnly()
- if after := r.files(); !reflect.DeepEqual(after, before) {
- t.Fatalf("a read-only run touched the state: before %+v after %+v", before, after)
- }
+ r.untouched(before)
// The pending migration was applied to the copy, which the runs read.
if !strings.Contains(out, adopt.SayStatusPreflight(adopt.PhasePreInitialize, false)) {
t.Fatalf("status did not read the migrated copy\n%s", out)
@@ -640,9 +670,7 @@ func TestDryRunLeavesStateUntouched(t *testing.T) {
t.Fatal("setup: no WAL")
}
out := r.readOnly()
- if after := r.files(); !reflect.DeepEqual(after, before) {
- t.Fatalf("a read-only run touched the state: before %+v after %+v", before, after)
- }
+ r.untouched(before)
if !strings.Contains(out, adopt.SayStatusLive(true)) {
t.Fatalf("status did not read the WAL\n%s", out)
}
diff --git a/cmd/alta-adopt/snapshot.go b/cmd/alta-adopt/snapshot.go
index c91ec23..cee4a88 100644
--- a/cmd/alta-adopt/snapshot.go
+++ b/cmd/alta-adopt/snapshot.go
@@ -4,7 +4,7 @@ import (
"context"
"database/sql"
"errors"
- "io"
+ "net/url"
"os"
"path/filepath"
@@ -13,14 +13,13 @@ import (
)
// snapshot answers an in-memory copy of the state at path, for a run
-// that must not write. SQLite never opens path itself: even a read-only
-// open of a WAL database may create its -shm, and Alta's own open sets
-// pragmas and applies migrations. Instead the file (and its -wal, which
-// holds committed transactions not yet checkpointed) is copied byte for
-// byte into a private temporary directory, that copy is restored into
-// memory, and the directory is removed before anything else runs. The
-// copy holds only what the state holds: sealed rows. With no state at
-// path, the snapshot is an empty database.
+// that must not write. The source is opened read-only (mode=ro) and
+// copied by SQLite's online backup in a single step, which holds one read
+// transaction for the whole copy: the result is one committed state, WAL
+// contents included, whatever another connection commits or checkpoints
+// meanwhile. Nothing is copied to disk; the only files SQLite may touch
+// are its own -shm and -wal coordination files, never the committed
+// contents. With no state at path, the snapshot is an empty database.
func snapshot(ctx context.Context, path string) (*sql.DB, error) {
mem, err := provision.OpenDB(":memory:")
if err != nil {
@@ -36,17 +35,19 @@ func snapshot(ctx context.Context, path string) (*sql.DB, error) {
return mem, nil
}
-func restore(ctx context.Context, mem *sql.DB, path string) error {
- dir, err := os.MkdirTemp("", "alta-adopt-")
+// readOnly is path as a read-only SQLite URI, waiting out a writer's
+// brief lock rather than failing.
+func readOnly(path string) (string, error) {
+ abs, err := filepath.Abs(path)
if err != nil {
- return err
+ return "", err
}
- defer os.RemoveAll(dir)
- cp := filepath.Join(dir, "state.db")
- if err := copyFile(path, cp); err != nil {
- return err
- }
- if err := copyFile(path+"-wal", cp+"-wal"); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return (&url.URL{Scheme: "file", Path: abs, RawQuery: "mode=ro&_pragma=busy_timeout(5000)"}).String(), nil
+}
+
+func restore(ctx context.Context, mem *sql.DB, path string) error {
+ src, err := readOnly(path)
+ if err != nil {
return err
}
conn, err := mem.Conn(ctx)
@@ -61,37 +62,18 @@ func restore(ctx context.Context, mem *sql.DB, path string) error {
if !ok {
return errors.New("alta-adopt: the SQLite driver cannot restore")
}
- b, err := r.NewRestore(cp)
+ b, err := r.NewRestore(src)
if err != nil {
return err
}
- for {
- more, err := b.Step(-1)
- if err != nil {
- _ = b.Finish()
- return err
- }
- if !more {
- return b.Finish()
- }
+ // -1: every page in one step, so one read transaction.
+ more, err := b.Step(-1)
+ if ferr := b.Finish(); err == nil {
+ err = ferr
+ }
+ if err == nil && more {
+ err = errors.New("alta-adopt: the snapshot did not finish in one step")
}
- })
-}
-
-// copyFile copies src, opened read-only, to a new private file dst.
-func copyFile(src, dst string) error {
- in, err := os.Open(src)
- if err != nil {
- return err
- }
- defer in.Close()
- out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
- if err != nil {
- return err
- }
- if _, err := io.Copy(out, in); err != nil {
- out.Close()
return err
- }
- return out.Close()
+ })
}
diff --git a/cmd/alta-adopt/snapshot_test.go b/cmd/alta-adopt/snapshot_test.go
new file mode 100644
index 0000000..2536ff4
--- /dev/null
+++ b/cmd/alta-adopt/snapshot_test.go
@@ -0,0 +1,119 @@
+package main
+
+import (
+ "context"
+ "database/sql"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+)
+
+// A snapshot taken while another connection commits and checkpoints is
+// one committed state, never a mix of two: every transaction moves the
+// first and the last row together, pages apart, so a torn copy shows
+// them differing. Nothing is copied to disk on the way.
+func TestSnapshotConsistentUnderConcurrentWrites(t *testing.T) {
+ // No scratch space on disk: the temporary directory is not even
+ // writable.
+ tmp := t.TempDir()
+ if err := os.Chmod(tmp, 0o500); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(tmp, 0o700) })
+ t.Setenv("TMPDIR", tmp)
+ dir := t.TempDir()
+ path := filepath.Join(dir, "state.db")
+ w, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer w.Close()
+ w.SetMaxOpenConns(1)
+ if _, err := w.Exec("CREATE TABLE t(id INTEGER PRIMARY KEY, n INTEGER NOT NULL, pad BLOB NOT NULL)"); err != nil {
+ t.Fatal(err)
+ }
+ const rows = 500
+ for i := 1; i <= rows; i++ {
+ if _, err := w.Exec("INSERT INTO t(id,n,pad) VALUES(?,0,zeroblob(1500))", i); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ var wg sync.WaitGroup
+ var commits atomic.Int64
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for i := 1; ctx.Err() == nil; i++ {
+ tx, err := w.Begin()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ // Every page between first and last is rewritten too, so a
+ // checkpoint moves the whole file under a copy.
+ if _, err := tx.Exec("UPDATE t SET n=n+1, pad=randomblob(1500)"); err != nil {
+ tx.Rollback()
+ t.Error(err)
+ return
+ }
+ if err := tx.Commit(); err != nil {
+ t.Error(err)
+ return
+ }
+ commits.Add(1)
+ {
+ if _, err := w.Exec("PRAGMA wal_checkpoint(PASSIVE)"); err != nil && !strings.Contains(err.Error(), "locked") && !strings.Contains(err.Error(), "busy") {
+ t.Error(err)
+ return
+ }
+ }
+ }
+ }()
+
+ // A failure stops the writer first, so it never reports after the test.
+ fail := func(format string, args ...any) {
+ t.Helper()
+ cancel()
+ wg.Wait()
+ t.Fatalf(format, args...)
+ }
+ seen := map[int64]bool{}
+ for i := 0; i < 100; i++ {
+ db, err := snapshot(context.Background(), path)
+ if err != nil {
+ fail("snapshot %d: %v", i, err)
+ }
+ var lo, hi, count int64
+ err = db.QueryRow("SELECT (SELECT n FROM t WHERE id=1), (SELECT n FROM t WHERE id=?), (SELECT count(DISTINCT n) FROM t)", rows).Scan(&lo, &hi, &count)
+ db.Close()
+ if err != nil {
+ fail("snapshot %d does not read: %v", i, err)
+ }
+ if lo != hi || count != 1 {
+ fail("snapshot %d mixes states: first %d last %d, %d distinct", i, lo, hi, count)
+ }
+ seen[lo] = true
+ }
+ cancel()
+ wg.Wait()
+ if len(seen) < 3 {
+ t.Fatalf("too little concurrency to mean anything: %d commits, %d states seen", commits.Load(), len(seen))
+ }
+ if ents, _ := os.ReadDir(tmp); len(ents) != 0 {
+ t.Fatalf("a snapshot wrote to the temporary directory: %d entries", len(ents))
+ }
+ ents, _ := os.ReadDir(dir)
+ for _, e := range ents {
+ switch e.Name() {
+ case "state.db", "state.db-wal", "state.db-shm":
+ default:
+ t.Fatalf("a snapshot left %s beside the state", e.Name())
+ }
+ }
+}