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()) } } }