| 1 | package projectiondb |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "sync" |
| 11 | "testing" |
| 12 | ) |
| 13 | |
| 14 | func TestIntegrityReuseConcurrentReadersAndBoundedCertificates(t *testing.T) { |
| 15 | dir := t.TempDir() |
| 16 | var cache integrityCertificates |
| 17 | var workers sync.WaitGroup |
| 18 | for worker := range 8 { |
| 19 | workers.Go(func() { |
| 20 | for index := range 20 { |
| 21 | path := filepath.Join(dir, fmt.Sprintf("%d-%d.sqlite", worker, index)) |
| 22 | if err := os.WriteFile(path, []byte("database"), 0600); err != nil { |
| 23 | t.Error(err) |
| 24 | return |
| 25 | } |
| 26 | for range 2 { |
| 27 | if err := cache.check(path, false, func() error { return nil }); err != nil { |
| 28 | t.Error(err) |
| 29 | return |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | }) |
| 34 | } |
| 35 | workers.Wait() |
| 36 | cache.mu.Lock() |
| 37 | defer cache.mu.Unlock() |
| 38 | if len(cache.entries) > 128 { |
| 39 | t.Fatalf("unbounded certificates: %d", len(cache.entries)) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func TestIntegrityReuseRequiresUnchangedDatabaseAndWAL(t *testing.T) { |
| 44 | path := filepath.Join(t.TempDir(), "projection.sqlite") |
| 45 | if err := os.WriteFile(path, []byte("verified database"), 0600); err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | var cache integrityCertificates |
| 49 | audits := 0 |
| 50 | validate := func() error { audits++; return nil } |
| 51 | check := func(want int) { |
| 52 | t.Helper() |
| 53 | if err := cache.check(path, false, validate); err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | if audits != want { |
| 57 | t.Fatalf("full integrity audits=%d want=%d", audits, want) |
| 58 | } |
| 59 | } |
| 60 | check(1) |
| 61 | check(1) |
| 62 | // SQLite creates/removes an empty WAL when a read connection opens/closes. |
| 63 | if err := os.WriteFile(path+"-wal", nil, 0600); err != nil { |
| 64 | t.Fatal(err) |
| 65 | } |
| 66 | check(1) |
| 67 | if err := os.WriteFile(path+"-wal", make([]byte, 100), 0600); err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | check(2) |
| 71 | check(3) // An open nonempty WAL is always audited, even with stable stat data. |
| 72 | if err := os.WriteFile(path+"-wal", make([]byte, 200), 0600); err != nil { |
| 73 | t.Fatal(err) |
| 74 | } |
| 75 | check(4) |
| 76 | if err := os.Remove(path + "-wal"); err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | check(5) |
| 80 | // Atomic replacement must invalidate even with the same length and mtime. |
| 81 | info, err := os.Stat(path) |
| 82 | if err != nil { |
| 83 | t.Fatal(err) |
| 84 | } |
| 85 | replacement := path + ".new" |
| 86 | if err := os.WriteFile(replacement, []byte("verified database"), 0600); err != nil { |
| 87 | t.Fatal(err) |
| 88 | } |
| 89 | if err := os.Chtimes(replacement, info.ModTime(), info.ModTime()); err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | if err := os.Rename(replacement, path); err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | check(6) |
| 96 | check(6) |
| 97 | // Checkpoints may retain coarse timestamps while changing SQLite's header. |
| 98 | info, err = os.Stat(path) |
| 99 | if err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | if err := os.WriteFile(path, []byte("modified database"), 0600); err != nil { |
| 103 | t.Fatal(err) |
| 104 | } |
| 105 | if err := os.Chtimes(path, info.ModTime(), info.ModTime()); err != nil { |
| 106 | t.Fatal(err) |
| 107 | } |
| 108 | check(7) |
| 109 | } |
| 110 | |
| 111 | func TestIntegrityReuseNeverCertifiesFailureOrConcurrentMutation(t *testing.T) { |
| 112 | path := filepath.Join(t.TempDir(), "projection.sqlite") |
| 113 | if err := os.WriteFile(path, []byte("before"), 0600); err != nil { |
| 114 | t.Fatal(err) |
| 115 | } |
| 116 | var cache integrityCertificates |
| 117 | failure := errors.New("corrupt index") |
| 118 | if err := cache.check(path, false, func() error { return failure }); !errors.Is(err, failure) { |
| 119 | t.Fatal(err) |
| 120 | } |
| 121 | audits := 0 |
| 122 | if err := cache.check(path, false, func() error { audits++; return os.WriteFile(path, []byte("changed during audit"), 0600) }); err != nil { |
| 123 | t.Fatal(err) |
| 124 | } |
| 125 | if err := cache.check(path, false, func() error { audits++; return nil }); err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | if audits != 2 { |
| 129 | t.Fatal("concurrent mutation was certified") |
| 130 | } |
| 131 | // A quick audit is never enough for a full-audit caller. |
| 132 | var quickCache integrityCertificates |
| 133 | if err := quickCache.check(path, true, func() error { return nil }); err != nil { |
| 134 | t.Fatal(err) |
| 135 | } |
| 136 | if err := quickCache.check(path, false, func() error { return failure }); !errors.Is(err, failure) { |
| 137 | t.Fatal("quick audit replaced full integrity validation") |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | func TestIntegrityReuseRejectsReplacementDuringOpen(t *testing.T) { |
| 142 | path := filepath.Join(t.TempDir(), "projection.sqlite") |
| 143 | if err := os.WriteFile(path, []byte("first"), 0600); err != nil { |
| 144 | t.Fatal(err) |
| 145 | } |
| 146 | opened, known := integrityFileState(path) |
| 147 | if err := os.WriteFile(path, []byte("second generation"), 0600); err != nil { |
| 148 | t.Fatal(err) |
| 149 | } |
| 150 | var cache integrityCertificates |
| 151 | // A successful audit of the old open handle is not proof of the new path. |
| 152 | if err := cache.checkOpened(path, false, opened, known, func() error { return nil }); err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | audits := 0 |
| 156 | if err := cache.check(path, false, func() error { audits++; return nil }); err != nil { |
| 157 | t.Fatal(err) |
| 158 | } |
| 159 | if audits != 1 { |
| 160 | t.Fatal("replacement was incorrectly certified by an older open handle") |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | func TestIntegrityReuseDetectsNewConstraintCorruption(t *testing.T) { |
| 165 | path := filepath.Join(t.TempDir(), "projection.sqlite") |
| 166 | opts := OpenOptions{Path: path, RequireDisk: true, ReuseIntegrityCheck: true, |
| 167 | Migrations: []Migration{{Version: 1, Apply: func(ctx context.Context, tx *sql.Tx) error { |
| 168 | _, err := tx.ExecContext(ctx, `CREATE TABLE guarded(value INTEGER CHECK(value>0))`) |
| 169 | return err |
| 170 | }}}} |
| 171 | for range 3 { |
| 172 | h, err := Open(t.Context(), opts) |
| 173 | if err != nil { |
| 174 | t.Fatal(err) |
| 175 | } |
| 176 | if err := h.DB.Close(); err != nil { |
| 177 | t.Fatal(err) |
| 178 | } |
| 179 | } |
| 180 | h, err := Open(t.Context(), opts) |
| 181 | if err != nil { |
| 182 | t.Fatal(err) |
| 183 | } |
| 184 | h.DB.SetMaxOpenConns(1) |
| 185 | if _, err := h.DB.Exec(`PRAGMA ignore_check_constraints=ON`); err != nil { |
| 186 | t.Fatal(err) |
| 187 | } |
| 188 | if _, err := h.DB.Exec(`INSERT INTO guarded VALUES(-1)`); err != nil { |
| 189 | t.Fatal(err) |
| 190 | } |
| 191 | if err := h.DB.Close(); err != nil { |
| 192 | t.Fatal(err) |
| 193 | } |
| 194 | h, err = Open(t.Context(), opts) |
| 195 | if err != nil { |
| 196 | t.Fatal(err) |
| 197 | } |
| 198 | defer h.DB.Close() |
| 199 | if h.Status.QuarantinedPath == "" { |
| 200 | t.Fatal("changed corrupt database reused an earlier integrity certificate") |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | func BenchmarkHistoryProjectionRepeatedOpen(b *testing.B) { |
| 205 | path := filepath.Join(b.TempDir(), "history.sqlite") |
| 206 | opts := OpenOptions{Path: path, RequireDisk: true, MaxOpenConns: 1, |
| 207 | Migrations: []Migration{{Version: 1, Apply: func(ctx context.Context, tx *sql.Tx) error { |
| 208 | _, err := tx.ExecContext(ctx, `CREATE TABLE history(id INTEGER PRIMARY KEY, body BLOB); CREATE INDEX history_size ON history(length(body))`) |
| 209 | return err |
| 210 | }}}} |
| 211 | h, err := Open(b.Context(), opts) |
| 212 | if err != nil { |
| 213 | b.Fatal(err) |
| 214 | } |
| 215 | // About 100 MiB with a body table and index, comparable to a large locator. |
| 216 | if _, err := h.DB.Exec(`WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<24000) INSERT INTO history SELECT x,zeroblob(4096) FROM n`); err != nil { |
| 217 | b.Fatal(err) |
| 218 | } |
| 219 | if err := h.DB.Close(); err != nil { |
| 220 | b.Fatal(err) |
| 221 | } |
| 222 | info, err := os.Stat(path) |
| 223 | if err != nil { |
| 224 | b.Fatal(err) |
| 225 | } |
| 226 | b.Logf("fixture database bytes=%d", info.Size()) |
| 227 | for _, reuse := range []bool{false, true} { |
| 228 | b.Run(fmt.Sprintf("reuse=%v", reuse), func(b *testing.B) { |
| 229 | opts.ReuseIntegrityCheck = reuse |
| 230 | // Warm the unchanged-file proof outside the measured loop. |
| 231 | warm, err := Open(b.Context(), opts) |
| 232 | if err != nil { |
| 233 | b.Fatal(err) |
| 234 | } |
| 235 | if err := warm.DB.Close(); err != nil { |
| 236 | b.Fatal(err) |
| 237 | } |
| 238 | b.ResetTimer() |
| 239 | for range b.N { |
| 240 | h, err := Open(b.Context(), opts) |
| 241 | if err != nil { |
| 242 | b.Fatal(err) |
| 243 | } |
| 244 | var count int |
| 245 | if err := h.DB.QueryRow(`SELECT COUNT(*) FROM (SELECT id FROM history ORDER BY id DESC LIMIT 32)`).Scan(&count); err != nil || count != 32 { |
| 246 | b.Fatalf("count=%d err=%v", count, err) |
| 247 | } |
| 248 | if err := h.DB.Close(); err != nil { |
| 249 | b.Fatal(err) |
| 250 | } |
| 251 | } |
| 252 | }) |
| 253 | } |
| 254 | } |
| 255 |