Diffinery

homeflare/celldpublic

2294 lines · 90.9 KBRaw History
1//! db.rs — SQLite database lifecycle: WAL-mode setup, the long-running read-lock
2//! checkpoint takeover, the WAL→LTX capture loop, and manual checkpointing.
3//! Ported from [email protected] `db.go`.
4//!
5//! T9 is the highest-risk module in the crate (Risk R-4: a long-running read
6//! transaction interacting with manual `PRAGMA wal_checkpoint`), so it is landed
7//! in tight, independently-tested sub-steps.
8//!
9//! ## Async/blocking shape — DECISION (synchronous `Db`)
10//! `rusqlite::Connection` is `!Sync` and a `rusqlite::Transaction` borrows its
11//! `Connection`. Rather than thread a borrow across `.await`, this module keeps
12//! the capture API **synchronous** and owns the connection directly: the
13//! long-running read transaction is held with raw `BEGIN`/`ROLLBACK` SQL plus a
14//! `read_lock_held` flag — exactly as Go does (`acquireReadLock` runs `BEGIN` +
15//! `SELECT COUNT(1)`, db.go:956-976; `releaseReadLock` rolls back, db.go:979-992).
16//! T10's `Replica` drives `sync()`/`checkpoint()` from a blocking context
17//! (`spawn_blocking` or a dedicated DB thread). This sidesteps the !Sync/borrow
18//! problem entirely and makes the idempotent-release behavior (issue #934) a
19//! trivial flag check.
20//!
21//! ## What this implements (the functional capture path)
22//! - `open`/`init`: WAL-mode DSN, `wal_autocheckpoint(0)`, control tables, read
23//! page size, acquire the read lock, ensure the WAL has ≥1 frame.
24//! - `acquire_read_lock`/`release_read_lock`: the checkpoint takeover; release is
25//! idempotent (db.go:979-992 / issue #934, footgun F-2).
26//! - `sync` → `verify` → `sync_inner` → `write_ltx_from_wal`/`write_ltx_from_db`:
27//! diff the real WAL against the last LTX position and write the next L0 LTX
28//! file (`db.go:1517-1723`), with atomic tmp→rename and the pos cache.
29//! - `verify`: the snapshot-on-continuity-break branch lattice (`db.go:1296-1436`,
30//! footgun F-7), including the issue #900 / #927 edge cases.
31//! - `checkpoint`/`exec_checkpoint`: release→`PRAGMA wal_checkpoint(<mode>)`→
32//! re-acquire (`db.go:1875-1919`, footgun F-1) and the two-phase WAL-restart
33//! handling (`db.go:1808-1873`, footgun F-9).
34//! - `checkpoint_if_needed`: the 3-tier policy + the three anti-feedback flags
35//! (`synced_since_checkpoint`/`synced_to_wal_end`/`last_synced_wal_offset`,
36//! issues #896/#927/#997, footgun F-5).
37//! - Litestream #1292 / celld #150: seal passive checkpoints with a writer
38//! barrier, retain database-growth pages, and snapshot truncate boundaries.
39//! - `crc64`, `pos` (cached + `LTXError` mapping), `reset_local_state`,
40//! `snapshot_to_writer`.
41//!
42//! ## Deferred work outside the functional path
43//! - `setPersistWAL` (the `unsafe` `sqlite3_file_control(SQLITE_FCNTL_PERSIST_WAL)`
44//! FFI, footgun F-10): only matters when *all* connections close and SQLite
45//! would delete the WAL; the capture path keeps its own connection open.
46//! - The background monitor loop + backoff (footgun F-13), `Replica` integration
47//! (`ensure_exists`/`sync_status`/`sync_and_wait`/retention/`syncReplicaWithRetry`):
48//! these need T10's `Replica` handle and land with it.
49//! - A `loom` model of the lock protocol.
50
51use crate::error::{new_ltx_error, Error, Result};
52use crate::ltx::{self, lock_pgno, Crc64};
53use crate::wal::WalReader;
54use crate::{
55 ltx_file_path, ltx_level_dir, Pos, CHECKPOINT_MODE_PASSIVE, CHECKPOINT_MODE_RESTART,
56 CHECKPOINT_MODE_TRUNCATE, META_DIR_SUFFIX, TXID, WAL_FRAME_HEADER_SIZE, WAL_HEADER_SIZE,
57};
58use rusqlite::{Connection, OpenFlags};
59use std::collections::HashMap;
60use std::path::{Path, PathBuf};
61use std::time::{Duration, SystemTime, UNIX_EPOCH};
62
63/// Maps a `rusqlite::Error` into the crate error type.
64fn sql_err(e: rusqlite::Error) -> Error {
65 Error::Other(Box::new(e))
66}
67
68/// SQLite checkpoint mode. Replaces Go's stringly-typed `mode` param; `Display`
69/// interpolates straight into `PRAGMA wal_checkpoint(<mode>)` (db.go:1905), so it
70/// must render exactly `PASSIVE`/`FULL`/`RESTART`/`TRUNCATE`.
71///
72/// Ported from [email protected] litestream.go:22-28. RESTART was removed from
73/// automatic use (issue #724) but is still callable (`crc64` forces it), so all
74/// four variants are kept.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum CheckpointMode {
77 /// Non-blocking checkpoint; skips if there are active transactions.
78 Passive,
79 /// Like RESTART but does not block new transactions before flushing.
80 Full,
81 /// Blocks new transactions, flushes, and restarts the WAL.
82 Restart,
83 /// Like RESTART plus truncates the WAL file to zero length.
84 Truncate,
85}
86
87impl std::fmt::Display for CheckpointMode {
88 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 let s = match self {
90 CheckpointMode::Passive => CHECKPOINT_MODE_PASSIVE,
91 CheckpointMode::Full => crate::CHECKPOINT_MODE_FULL,
92 CheckpointMode::Restart => CHECKPOINT_MODE_RESTART,
93 CheckpointMode::Truncate => CHECKPOINT_MODE_TRUNCATE,
94 };
95 f.write_str(s)
96 }
97}
98
99/// `verify()`'s decision result (db.go:1509-1515).
100#[derive(Debug, Clone, Default)]
101struct SyncInfo {
102 /// End of the previous LTX read (byte offset into the WAL).
103 offset: i64,
104 salt1: u32,
105 salt2: u32,
106 /// Database page count recorded by the previous LTX file.
107 prev_commit: u32,
108 /// If true, a full snapshot is required.
109 snapshotting: bool,
110 /// Reason for the snapshot (for logging / test assertions).
111 reason: String,
112}
113
114/// A SQLite database managed for replication.
115///
116/// Owns the connection (WAL mode, auto-checkpoint disabled) so litestream — not
117/// SQLite — decides when the WAL is checkpointed, and holds the long-running read
118/// transaction that takes over checkpointing.
119///
120/// Ported from `DB` (db.go:64-198). Synchronous by DECISION (see module docs):
121/// the `!Sync` connection stays on whatever thread T10 drives it from.
122pub struct Db {
123 host: crate::LtxHost,
124 path: PathBuf,
125 meta_path: PathBuf,
126 /// Main connection: writes, PRAGMAs, checkpoints, page-size reads.
127 conn: Connection,
128 /// Dedicated connection that holds the long-running read transaction.
129 ///
130 /// Go's `db.db` is a `*sql.DB` **connection pool**: the read lock (`db.rtx`)
131 /// lives on one pooled connection while every other `db.db.Exec` grabs a
132 /// *different* connection from the pool. A single `rusqlite::Connection`
133 /// cannot do that — an `INSERT` issued on the same connection that holds the
134 /// read transaction would be buffered in that transaction and not flushed to
135 /// the WAL (it would not write a fresh WAL page after a TRUNCATE checkpoint).
136 /// So the read lock gets its own connection, mirroring the pool's separation.
137 rtx_conn: Connection,
138 page_size: u32,
139
140 /// `true` while the long-running read transaction is open (db.go:70 `rtx`).
141 /// We track a flag rather than holding a borrowing `rusqlite::Transaction`.
142 read_lock_held: bool,
143
144 // ── Tunables (db.go:131-197) ────────────────────────────────────────────
145 /// PASSIVE checkpoint threshold, in pages (db.go:34 default 1000).
146 pub min_checkpoint_page_n: u32,
147 /// TRUNCATE checkpoint threshold, in pages; 0 disables (db.go:35 default).
148 pub truncate_page_n: u32,
149 /// Time-based PASSIVE checkpoint interval; 0 disables (db.go:32 default 60s).
150 pub checkpoint_interval: Duration,
151 /// Busy timeout for SQLite locks (db.go:33 default 1s).
152 pub busy_timeout: Duration,
153
154 // ── Anti-feedback-loop bookkeeping (issues #896/#927/#997, footgun F-5) ──
155 /// True once data has synced since the last checkpoint (#896, db.go:80).
156 synced_since_checkpoint: bool,
157 /// True if the last sync reached the exact WAL EOF (#927, db.go:88).
158 synced_to_wal_end: bool,
159 /// Logical end of WAL content after the last sync = `WALOffset + WALSize`
160 /// from the last LTX (#997, db.go:96). Used for checkpoint thresholds
161 /// instead of file size (stale post-checkpoint frames inflate file size).
162 last_synced_wal_offset: i64,
163
164 /// Cached L0 position; `None` = invalid (db.go:106-109).
165 pos_cache: Option<Pos>,
166 /// Last L0 `FileInfo` (db.go:99-102; only L0 is tracked in the one-shot).
167 max_l0_file_info: Option<ltx::FileInfo>,
168
169 /// Unit-test hook that runs while the passive checkpoint writer barrier is
170 /// held and immediately before the checkpoint PRAGMA.
171 #[cfg(test)]
172 passive_checkpoint_barrier_hook: Option<Box<dyn FnOnce() + Send>>,
173}
174
175impl Db {
176 /// Default minimum-checkpoint page count (`DefaultMinCheckpointPageN`,
177 /// db.go:34).
178 pub const DEFAULT_MIN_CHECKPOINT_PAGE_N: u32 = 1000;
179 /// Default truncate page count (`DefaultTruncatePageN`, db.go:35).
180 pub const DEFAULT_TRUNCATE_PAGE_N: u32 = 121_359;
181 /// Default checkpoint interval (`DefaultCheckpointInterval`, db.go:32).
182 pub const DEFAULT_CHECKPOINT_INTERVAL: Duration = Duration::from_secs(60);
183 /// Default busy timeout (`DefaultBusyTimeout`, db.go:33).
184 pub const DEFAULT_BUSY_TIMEOUT: Duration = Duration::from_secs(1);
185
186 /// Opens and initializes the database with litestream's WAL-mode setup and
187 /// acquires the long-running read lock.
188 ///
189 /// Ported from `DB.init` (db.go:795-911) — the connection-setup half plus the
190 /// read-lock acquire and `ensureWALExists`. (Replica wiring lands in T10.)
191 pub fn open(path: impl AsRef<Path>) -> Result<Db> {
192 Self::open_with_host(path, crate::LtxHost::default())
193 }
194
195 /// Opens the database with an injected clock and executor host.
196 pub fn open_with_host(path: impl AsRef<Path>, host: crate::LtxHost) -> Result<Db> {
197 Self::open_with_host_and_optional_vfs(path, host, None)
198 }
199
200 /// Opens both managed connections through an internal test VFS.
201 #[cfg(celld_internal_tests)]
202 pub fn open_with_host_and_vfs(
203 path: impl AsRef<Path>,
204 host: crate::LtxHost,
205 vfs: &str,
206 ) -> Result<Db> {
207 Self::open_with_host_and_optional_vfs(path, host, Some(vfs))
208 }
209
210 fn open_with_host_and_optional_vfs(
211 path: impl AsRef<Path>,
212 host: crate::LtxHost,
213 vfs: Option<&str>,
214 ) -> Result<Db> {
215 let path = path.as_ref().to_path_buf();
216 let meta_path = Self::meta_path_for(&path);
217
218 let open = |path: &Path| match vfs {
219 Some(vfs) => Connection::open_with_flags_and_vfs(path, OpenFlags::default(), vfs),
220 None => Connection::open(path),
221 };
222 let conn = open(&path).map_err(sql_err)?;
223
224 // DSN pragmas: busy_timeout + wal_autocheckpoint(0) (db.go:818).
225 // autocheckpoint MUST be 0 — litestream owns checkpointing (footgun
226 // F-10). Per-connection, not per-file: the cell's own writer
227 // connection keeps SQLite's default 1000-page autocheckpoint, which
228 // is safe because this connection's long-running read transaction
229 // pins a WAL read mark, so a PASSIVE checkpoint elsewhere can
230 // backfill but never reset or truncate the WAL under the reader.
231 conn.busy_timeout(Self::DEFAULT_BUSY_TIMEOUT)
232 .map_err(sql_err)?;
233 conn.pragma_update(None, "wal_autocheckpoint", 0)
234 .map_err(sql_err)?;
235
236 // Enable WAL; SQLite returns the new mode on success (db.go:849-853).
237 let mode: String = conn
238 .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0))
239 .map_err(sql_err)?;
240 if mode != "wal" {
241 return Err(Error::Other(
242 format!("enable wal failed, mode={mode:?}").into(),
243 ));
244 }
245
246 // Control tables: `_litestream_seq` forces WAL writes when empty; the
247 // `_litestream_lock` table forces a write lock during sync (db.go:857-864).
248 conn.execute_batch(
249 "CREATE TABLE IF NOT EXISTS _litestream_seq (id INTEGER PRIMARY KEY, seq INTEGER);\
250 CREATE TABLE IF NOT EXISTS _litestream_lock (id INTEGER);",
251 )
252 .map_err(sql_err)?;
253
254 // Dedicated read-lock connection (mirrors a second pooled connection).
255 let rtx_conn = open(&path).map_err(sql_err)?;
256 rtx_conn
257 .busy_timeout(Self::DEFAULT_BUSY_TIMEOUT)
258 .map_err(sql_err)?;
259
260 let mut db = Db {
261 host,
262 path,
263 meta_path,
264 conn,
265 rtx_conn,
266 page_size: 0,
267 read_lock_held: false,
268 min_checkpoint_page_n: Self::DEFAULT_MIN_CHECKPOINT_PAGE_N,
269 truncate_page_n: Self::DEFAULT_TRUNCATE_PAGE_N,
270 checkpoint_interval: Self::DEFAULT_CHECKPOINT_INTERVAL,
271 busy_timeout: Self::DEFAULT_BUSY_TIMEOUT,
272 synced_since_checkpoint: false,
273 synced_to_wal_end: false,
274 last_synced_wal_offset: 0,
275 pos_cache: None,
276 max_l0_file_info: None,
277 #[cfg(test)]
278 passive_checkpoint_barrier_hook: None,
279 };
280
281 // Start the long-running read transaction (db.go:867-871).
282 db.acquire_read_lock()?;
283
284 // Read page size (db.go:874-878).
285 let page_size: i64 = db
286 .conn
287 .query_row("PRAGMA page_size", [], |r| r.get(0))
288 .map_err(sql_err)?;
289 if page_size <= 0 {
290 return Err(Error::Other(
291 format!("invalid db page size: {page_size}").into(),
292 ));
293 }
294 // Validated > 0 above; SQLite page sizes are <= 65536.
295 db.page_size = page_size as u32;
296
297 // Ensure the meta directory exists (db.go:880-883).
298 db.host.create_dir_all(&db.meta_path)?;
299
300 // Clear crash-leftover temp files (db.go:576).
301 remove_tmp_files(&db.host, &db.meta_path)?;
302
303 // Ensure the WAL has at least one frame (db.go:886-888).
304 db.ensure_wal_exists()?;
305
306 Ok(db)
307 }
308
309 // ── Paths ──────────────────────────────────────────────────────────────
310
311 /// Computes the litestream meta-directory path (`.<file>-litestream`) for a
312 /// database file path, without opening it. Public so a host can locate (e.g.
313 /// to wipe, during a hard recovery) the meta dir of a database it no longer
314 /// has an open [`Db`] handle for. Mirrors `DB.MetaPath` (db.go:292) at the
315 /// path level.
316 pub fn meta_path_for_path(path: impl AsRef<Path>) -> PathBuf {
317 Self::meta_path_for(path.as_ref())
318 }
319
320 fn meta_path_for(path: &Path) -> PathBuf {
321 // Go: filepath.Join(dir, "."+file+MetaDirSuffix) (db.go:206).
322 let dir = path.parent();
323 let file = path.file_name().map(|s| s.to_owned()).unwrap_or_default();
324 let mut name = std::ffi::OsString::from(".");
325 name.push(&file);
326 name.push(META_DIR_SUFFIX);
327 match dir {
328 Some(d) if !d.as_os_str().is_empty() => d.join(name),
329 _ => PathBuf::from(name),
330 }
331 }
332
333 /// The database file path. Ported from `DB.Path` (db.go:275).
334 pub fn path(&self) -> &Path {
335 &self.path
336 }
337
338 /// Path to the litestream meta directory (`.<file>-litestream`).
339 /// Ported from `DB.MetaPath` (db.go:292).
340 pub fn meta_path(&self) -> &Path {
341 &self.meta_path
342 }
343
344 /// Path to SQLite's WAL sidecar file (`<db>-wal`).
345 /// Ported from `DB.WALPath` (db.go:287-289).
346 pub fn wal_path(&self) -> PathBuf {
347 let mut s = self.path.clone().into_os_string();
348 s.push("-wal");
349 PathBuf::from(s)
350 }
351
352 /// Root LTX directory (`<meta>/ltx`). Ported from `DB.LTXDir` (db.go:302).
353 fn ltx_dir(&self) -> String {
354 crate::ltx_dir(&self.meta_path.to_string_lossy())
355 }
356
357 /// LTX level sub-directory. Ported from `DB.LTXLevelDir` (db.go:332).
358 fn ltx_level_dir(&self, level: u32) -> String {
359 ltx_level_dir(&self.meta_path.to_string_lossy(), level)
360 }
361
362 /// Local path of a single LTX file. Ported from `DB.LTXPath` (db.go:338).
363 ///
364 /// `pub` so the [`crate::replica::Replica`] can read the local L0 LTX files
365 /// the capture loop wrote and upload them (the Go exported `DB.LTXPath`,
366 /// used by `Replica.uploadLTXFile`, replica.go:183).
367 pub fn ltx_path(&self, level: u32, min_txid: TXID, max_txid: TXID) -> String {
368 ltx_file_path(&self.meta_path.to_string_lossy(), level, min_txid, max_txid)
369 }
370
371 /// Reads one local LTX file through the host filesystem.
372 pub fn read_ltx_file(&self, level: u32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> {
373 let path = self.ltx_path(level, min_txid, max_txid);
374 Ok(self.host.read(Path::new(&path))?)
375 }
376
377 /// The SQLite page size, in bytes. Ported from `DB.PageSize` (db.go:445).
378 pub fn page_size(&self) -> u32 {
379 self.page_size
380 }
381
382 // ── Read-lock takeover (checkpoint prevention) ─────────────────────────
383
384 /// Begins a long-running read transaction to prevent external checkpoints.
385 ///
386 /// Ported from `acquireReadLock` (db.go:956-976): `BEGIN` then `SELECT
387 /// COUNT(1) FROM _litestream_seq` to obtain the SHARED read lock. Held with
388 /// raw SQL + a flag instead of a borrowing `rusqlite::Transaction` (see
389 /// module docs). Idempotent: a no-op if already held.
390 fn acquire_read_lock(&mut self) -> Result<()> {
391 if self.read_lock_held {
392 return Ok(());
393 }
394 self.rtx_conn.execute_batch("BEGIN").map_err(sql_err)?;
395 // Execute a read query to obtain the read lock. On failure, roll back.
396 if let Err(e) = self
397 .rtx_conn
398 .query_row("SELECT COUNT(1) FROM _litestream_seq", [], |r| {
399 r.get::<_, i64>(0)
400 })
401 {
402 let _ = self.rtx_conn.execute_batch("ROLLBACK");
403 return Err(sql_err(e));
404 }
405 self.read_lock_held = true;
406 Ok(())
407 }
408
409 /// Rolls back the long-running read transaction.
410 ///
411 /// Ported from `releaseReadLock` (db.go:979-992). Uses the `rollback` helper
412 /// semantics: a "no transaction is active" / "already rolled back" error is
413 /// swallowed (issue #934, footgun F-2) — a double release must return
414 /// `Ok(())`. The `read_lock_held` flag is cleared regardless.
415 fn release_read_lock(&mut self) -> Result<()> {
416 if !self.read_lock_held {
417 return Ok(());
418 }
419 self.read_lock_held = false;
420 rollback(&self.rtx_conn)
421 }
422
423 // ── WAL bootstrap ──────────────────────────────────────────────────────
424
425 /// Ensures the real WAL exists and has a header.
426 ///
427 /// Ported from `ensureWALExists` (db.go:1199-1209): exit early if the WAL
428 /// header is present; otherwise force a write to `_litestream_seq`.
429 fn ensure_wal_exists(&self) -> Result<()> {
430 if let Ok(md) = self.host.metadata(&self.wal_path()) {
431 if md.len >= WAL_HEADER_SIZE as u64 {
432 return Ok(());
433 }
434 }
435 self.conn
436 .execute_batch(
437 "INSERT INTO _litestream_seq (id, seq) VALUES (1, 1) \
438 ON CONFLICT (id) DO UPDATE SET seq = seq + 1",
439 )
440 .map_err(sql_err)?;
441 Ok(())
442 }
443
444 /// Size of the WAL file in bytes, 0 if absent. Ported from `walFileSize`
445 /// (db.go:1183-1191).
446 fn wal_file_size(&self) -> Result<i64> {
447 match self.host.metadata(&self.wal_path()) {
448 Ok(md) => Ok(md.len as i64),
449 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
450 Err(e) => Err(e.into()),
451 }
452 }
453
454 /// The size of the main database file in bytes, 0 if absent.
455 fn db_file_size(&self) -> Result<i64> {
456 match self.host.metadata(&self.path) {
457 Ok(md) => Ok(md.len as i64),
458 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
459 Err(e) => Err(e.into()),
460 }
461 }
462
463 // ── Position ───────────────────────────────────────────────────────────
464
465 /// The highest `(min,max)` TXID pair in the L0 directory, `(0,0)` if none.
466 /// Ported from `DB.MaxLTX` (db.go:363-380).
467 fn max_ltx(&self) -> Result<(TXID, TXID)> {
468 let dir = self.ltx_level_dir(0);
469 let entries = match self.host.read_dir(Path::new(&dir)) {
470 Ok(e) => e,
471 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((TXID(0), TXID(0))),
472 Err(e) => return Err(e.into()),
473 };
474 let mut min_txid = TXID(0);
475 let mut max_txid = TXID(0);
476 for ent in entries {
477 let name = ent.file_name;
478 let name = name.to_string_lossy();
479 if let Ok((mn, mx)) = ltx::parse_filename(&name) {
480 if mx > max_txid {
481 min_txid = mn;
482 max_txid = mx;
483 }
484 }
485 }
486 Ok((min_txid, max_txid))
487 }
488
489 /// The current replication position (cached; recomputed from the max L0 file).
490 ///
491 /// Ported from `DB.Pos` (db.go:392-425). Wraps fs/decode failures in
492 /// `LTXError` (db.go:412,418, footgun F-7's error-mapping companion).
493 pub fn pos(&mut self) -> Result<Pos> {
494 if let Some(p) = self.pos_cache {
495 return Ok(p);
496 }
497
498 let (min_txid, max_txid) = self.max_ltx()?;
499 if min_txid == TXID(0) {
500 return Ok(Pos::ZERO); // no replication yet
501 }
502
503 let ltx_path = self.ltx_path(0, min_txid, max_txid);
504 let bytes = match self.host.read(Path::new(&ltx_path)) {
505 Ok(b) => b,
506 Err(e) => {
507 return Err(Error::Ltx(Box::new(new_ltx_error(
508 "open",
509 &ltx_path,
510 0,
511 min_txid.0,
512 max_txid.0,
513 e.into(),
514 ))));
515 }
516 };
517
518 let decoded = match ltx::decode_file(&bytes) {
519 Ok(d) => d,
520 Err(_e) => {
521 // Decode/verify failure indicates corruption (db.go:417-419).
522 return Err(Error::Ltx(Box::new(new_ltx_error(
523 "verify",
524 &ltx_path,
525 0,
526 min_txid.0,
527 max_txid.0,
528 Error::LTXCorrupted,
529 ))));
530 }
531 };
532
533 let pos = Pos::new(decoded.header.max_txid, decoded.trailer.post_apply_checksum);
534 self.pos_cache = Some(pos);
535 Ok(pos)
536 }
537
538 /// Clears the cached position so the next `pos()` recomputes from disk.
539 /// Ported from `invalidatePosCache` (db.go:430-434).
540 fn invalidate_pos_cache(&mut self) {
541 self.pos_cache = None;
542 }
543
544 /// Removes local LTX files, forcing a fresh snapshot on the next sync.
545 /// Ported from `DB.ResetLocalState` (db.go:309-328).
546 pub fn reset_local_state(&mut self) -> Result<()> {
547 match self.host.remove_dir_all(Path::new(&self.ltx_dir())) {
548 Ok(()) => {}
549 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
550 Err(e) => return Err(e.into()),
551 }
552 self.max_l0_file_info = None;
553 self.invalidate_pos_cache();
554 Ok(())
555 }
556
557 /// Clears the local L0 directory and seeds it with a single baseline L0 LTX
558 /// file (`data` for the `min_txid`..`max_txid` range), atomically. The next
559 /// [`Db::sync`] then sees the baseline does not match the real WAL and writes
560 /// a fresh snapshot at the current database state.
561 ///
562 /// This is the file-writing tail of `checkDatabaseBehindReplica`
563 /// (db.go:1241-1293): clear L0, invalidate the pos cache, write the fetched
564 /// remote L0 file to its local path via a temp-file + fsync + rename, then
565 /// invalidate the cache again. The *detection* half (compare DB pos vs replica
566 /// pos and fetch the bytes) lives on [`crate::replica::Replica`] because the
567 /// synchronous `Db` has no `ReplicaClient` handle of its own (see the module
568 /// docs / OPEN_QUESTIONS T9/T10 deferral). Used by
569 /// [`crate::replica::Replica::check_database_behind_replica`] (issue #781).
570 pub fn seed_l0_baseline(&mut self, min_txid: TXID, max_txid: TXID, data: &[u8]) -> Result<()> {
571 // Clear local L0 files (db.go:1241-1249).
572 let l0_dir = self.ltx_level_dir(0);
573 match self.host.remove_dir_all(Path::new(&l0_dir)) {
574 Ok(()) => {}
575 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
576 Err(e) => return Err(e.into()),
577 }
578 self.max_l0_file_info = None;
579 self.invalidate_pos_cache();
580 self.host.create_dir_all(Path::new(&l0_dir))?;
581
582 // Write the baseline file atomically (db.go:1260-1286).
583 let local_path = self.ltx_path(0, min_txid, max_txid);
584 let tmp_path = format!("{local_path}.tmp");
585 write_file_atomic(&self.host, &tmp_path, &local_path, data)?;
586 self.invalidate_pos_cache();
587 Ok(())
588 }
589
590 // ── Capture loop ───────────────────────────────────────────────────────
591
592 /// Copies pending data from the WAL into the next L0 LTX file and applies
593 /// the checkpoint policy.
594 ///
595 /// Ported from `DB.Sync` (db.go:994-1056). The public entry point of the
596 /// capture loop. Synchronous (see module docs); T10 drives it.
597 pub fn sync(&mut self) -> Result<()> {
598 // Ensure the WAL has at least one frame (db.go:1017-1020).
599 self.ensure_wal_exists()?;
600
601 let (orig_wal_size, new_wal_size, synced) = self.verify_and_sync()?;
602
603 // Track that data was synced for time-based checkpoint decisions.
604 if synced {
605 self.synced_since_checkpoint = true;
606 }
607
608 self.checkpoint_if_needed(orig_wal_size, new_wal_size)?;
609
610 // Recompute the cached position (kept for parity with db.go:1037-1041).
611 let _ = self.pos()?;
612
613 Ok(())
614 }
615
616 /// Verifies the last sync against the current WAL, then syncs.
617 ///
618 /// Ported from `DB.verifyAndSync` (db.go:1058-1090). Returns
619 /// `(orig_wal_size, new_wal_size, synced)` where the sizes are the **logical**
620 /// WAL offset (`WALOffset+WALSize` of the last LTX), not file size (#997).
621 fn verify_and_sync(&mut self) -> Result<(i64, i64, bool)> {
622 // Use the last synced WAL offset as the logical size for checkpoint
623 // decisions; on the first sync fall back to file size (db.go:1062-1069).
624 let mut orig_wal_size = self.last_synced_wal_offset;
625 if orig_wal_size == 0 {
626 orig_wal_size = self.wal_file_size()?;
627 }
628
629 let info = self.verify()?;
630 let synced = self.sync_inner(info)?;
631
632 let new_wal_size = self.last_synced_wal_offset;
633 Ok((orig_wal_size, new_wal_size, synced))
634 }
635
636 /// Ensures the LTX state matches where it left off from the real WAL.
637 ///
638 /// Ported branch-for-branch from `DB.verify` (db.go:1296-1436), footgun F-7.
639 /// This is the snapshot-on-continuity-break brain — do not refactor for
640 /// elegance on pass one.
641 fn verify(&mut self) -> Result<SyncInfo> {
642 let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64;
643 let mut info = SyncInfo {
644 snapshotting: true,
645 ..Default::default()
646 };
647
648 let pos = self.pos()?;
649 if pos.txid == TXID(0) {
650 info.offset = WAL_HEADER_SIZE as i64;
651 return Ok(info); // first sync
652 }
653
654 // Determine the last WAL offset we saved from, by decoding the last LTX
655 // file's header (db.go:1311-1326).
656 let ltx_path = self.ltx_path(0, pos.txid, pos.txid);
657 let ltx_bytes = match self.host.read(Path::new(&ltx_path)) {
658 Ok(b) => b,
659 Err(e) => {
660 return Err(Error::Ltx(Box::new(new_ltx_error(
661 "open",
662 &ltx_path,
663 0,
664 pos.txid.0,
665 pos.txid.0,
666 e.into(),
667 ))));
668 }
669 };
670 let hdr = match ltx::Header::parse(&ltx_bytes) {
671 Ok(h) => h,
672 Err(_) => {
673 return Err(Error::Ltx(Box::new(new_ltx_error(
674 "decode",
675 &ltx_path,
676 0,
677 pos.txid.0,
678 pos.txid.0,
679 Error::LTXCorrupted,
680 ))));
681 }
682 };
683 info.offset = hdr.wal_offset + hdr.wal_size;
684 info.salt1 = hdr.wal_salt1;
685 info.salt2 = hdr.wal_salt2;
686 info.prev_commit = hdr.commit;
687
688 // If the LTX WAL offset exceeds the real WAL size, the WAL was truncated.
689 let wal_size = self.wal_file_size()?;
690 if info.offset > wal_size {
691 // If we previously synced to the exact WAL end, this truncation is an
692 // expected checkpoint: reset to the header and continue incrementally
693 // rather than snapshotting (issue #927, db.go:1335-1355).
694 if self.synced_to_wal_end {
695 self.synced_to_wal_end = false;
696
697 let wal_hdr = read_wal_header(&self.host, &self.wal_path())?;
698 info.offset = WAL_HEADER_SIZE as i64;
699 info.salt1 = be_u32(&wal_hdr[16..]);
700 info.salt2 = be_u32(&wal_hdr[20..]);
701 info.snapshotting = false;
702 info.reason = String::new();
703 return Ok(info);
704 }
705
706 info.reason = "wal truncated by another process".to_string();
707 return Ok(info);
708 }
709
710 // Compare WAL headers; restart from the beginning of the WAL if different.
711 let wal_hdr = read_wal_header(&self.host, &self.wal_path())?;
712 let salt1 = be_u32(&wal_hdr[16..]);
713 let salt2 = be_u32(&wal_hdr[20..]);
714 let salt_match = salt1 == hdr.wal_salt1 && salt2 == hdr.wal_salt2;
715
716 // Edge case: LTX represents the start of the WAL (WALOffset=32, WALSize=0).
717 // Handle this before computing prev_wal_offset to avoid underflow
718 // (32 - 4120 = -4088). See issue #900 (db.go:1375-1383).
719 if info.offset == WAL_HEADER_SIZE as i64 {
720 if salt_match {
721 info.snapshotting = false;
722 return Ok(info);
723 }
724 info.reason = "wal header salt reset, snapshotting".to_string();
725 return Ok(info);
726 }
727
728 // If the offset is at the start of the first page, we can't check the
729 // previous page (db.go:1386-1399).
730 let prev_wal_offset = info.offset - frame_size;
731 if prev_wal_offset == WAL_HEADER_SIZE as i64 {
732 if salt_match {
733 info.snapshotting = false;
734 return Ok(info);
735 }
736 info.reason = "wal header salt reset, snapshotting".to_string();
737 return Ok(info);
738 } else if prev_wal_offset < WAL_HEADER_SIZE as i64 {
739 return Err(Error::Other(
740 format!("prev WAL offset is less than the header size: {prev_wal_offset}").into(),
741 ));
742 }
743
744 // If we can't verify the last page is in the last LTX file, snapshot.
745 let last_page_match =
746 self.last_page_match(&ltx_bytes, &hdr, prev_wal_offset, frame_size)?;
747 if !last_page_match {
748 info.reason =
749 "last page does not exist in last ltx file, wal overwritten by another process"
750 .to_string();
751 return Ok(info);
752 }
753
754 // Salt changed (possible FULL/RESTART checkpoint). With a last-page match
755 // we assume the WAL was not overwritten (db.go:1412-1431).
756 if !salt_match {
757 info.offset = WAL_HEADER_SIZE as i64;
758 info.salt1 = salt1;
759 info.salt2 = salt2;
760
761 let detected =
762 self.detect_full_checkpoint(&[(salt1, salt2), (hdr.wal_salt1, hdr.wal_salt2)])?;
763 if detected {
764 info.reason = "full or restart checkpoint detected, snapshotting".to_string();
765 } else {
766 info.snapshotting = false;
767 }
768 return Ok(info);
769 }
770
771 info.snapshotting = false;
772 Ok(info)
773 }
774
775 /// Checks whether the last page read in the WAL exists in the last LTX file.
776 ///
777 /// Ported from `DB.lastPageMatch` (db.go:1438-1475). Re-reads the last synced
778 /// WAL frame and searches the last LTX file's pages for a matching
779 /// `(pgno, data)` pair.
780 fn last_page_match(
781 &self,
782 ltx_bytes: &[u8],
783 hdr: &ltx::Header,
784 prev_wal_offset: i64,
785 frame_size: i64,
786 ) -> Result<bool> {
787 if prev_wal_offset <= WAL_HEADER_SIZE as i64 {
788 return Ok(false);
789 }
790
791 let frame = read_wal_file_at(&self.host, &self.wal_path(), prev_wal_offset, frame_size)?;
792 let pgno = be_u32(&frame[0..]);
793 let fsalt1 = be_u32(&frame[8..]);
794 let fsalt2 = be_u32(&frame[12..]);
795 let data = &frame[WAL_FRAME_HEADER_SIZE..];
796
797 if fsalt1 != hdr.wal_salt1 || fsalt2 != hdr.wal_salt2 {
798 return Ok(false);
799 }
800
801 // Verify the last WAL page exists, byte-for-byte, in the last LTX file.
802 // Decode the full file and compare the decompressed page bytes.
803 let pages = ltx::decode_file_pages(ltx_bytes).map_err(|_| Error::LTXCorrupted)?;
804 for (p, page_data) in &pages {
805 if *p == pgno && page_data.as_slice() == data {
806 return Ok(true);
807 }
808 }
809 Ok(false)
810 }
811
812 /// Detects whether a FULL or RESTART checkpoint occurred (we may have missed
813 /// frames). Ported from `DB.detectFullCheckpoint` (db.go:1477-1507).
814 fn detect_full_checkpoint(&self, known_salts: &[(u32, u32)]) -> Result<bool> {
815 let wal_bytes = self.host.read(&self.wal_path())?;
816 let rd = WalReader::new(&wal_bytes).map_err(Error::from)?;
817 let last_known = known_salts.last().copied().unwrap_or((0, 0));
818 let mut m = rd.frame_salts_until(last_known);
819 for s in known_salts {
820 m.remove(s);
821 }
822 Ok(!m.is_empty())
823 }
824
825 /// Copies pending bytes from the real WAL into a new L0 LTX file.
826 ///
827 /// Ported from `DB.sync` (db.go:1517-1723). Returns `true` if an LTX file was
828 /// written (there were new pages or we were snapshotting). Atomic
829 /// tmp→fsync→rename with the pos cache + anti-feedback flags updated after.
830 fn sync_inner(&mut self, mut info: SyncInfo) -> Result<bool> {
831 let pos = self.pos()?;
832 let tx_id = TXID(pos.txid.0 + 1);
833 let filename = self.ltx_path(0, tx_id, tx_id);
834
835 let db_size = self.db_file_size()?;
836 let mut commit = (db_size / self.page_size as i64) as u32;
837
838 let wal_bytes = self.host.read(&self.wal_path())?;
839
840 // Choose the WAL reader start: from the header, or seek to info.offset.
841 // A previous-frame mismatch falls back to a full read (snapshot),
842 // mirroring NewWALReaderWithOffset's PrevFrameMismatchError handling
843 // (db.go:1565-1581, footgun F-7).
844 let mut rd = if info.offset == WAL_HEADER_SIZE as i64 {
845 WalReader::new(&wal_bytes).map_err(Error::from)?
846 } else {
847 match WalReader::new_with_offset(&wal_bytes, info.offset, info.salt1, info.salt2) {
848 Ok(r) => r,
849 Err(crate::wal::WalError::PrevFrameMismatch) => {
850 info.offset = WAL_HEADER_SIZE as i64;
851 WalReader::new(&wal_bytes).map_err(Error::from)?
852 }
853 Err(e) => return Err(e.into()),
854 }
855 };
856
857 let (page_map, max_offset, wal_commit) = rd.page_map().map_err(Error::from)?;
858 if wal_commit > 0 {
859 commit = wal_commit;
860 }
861
862 let sz = if max_offset > 0 {
863 max_offset - info.offset
864 } else {
865 0
866 };
867 if sz < 0 {
868 return Err(Error::Other(
869 format!(
870 "wal size must be positive: sz={sz}, maxOffset={max_offset}, info.offset={}",
871 info.offset
872 )
873 .into(),
874 ));
875 }
876
877 // Exit if there are no new WAL pages and we are not snapshotting
878 // (db.go:1603-1607).
879 if !info.snapshotting && sz == 0 {
880 return Ok(false);
881 }
882
883 let (rd_salt1, rd_salt2) = rd.salt();
884
885 // Build the page set for the encoder.
886 let pages: Vec<(u32, Vec<u8>)> = if info.snapshotting {
887 self.collect_snapshot_pages(&wal_bytes, &page_map, commit)?
888 } else {
889 self.collect_wal_pages(&wal_bytes, &page_map, info.prev_commit, commit)?
890 };
891
892 let header = ltx::Header {
893 version: ltx::VERSION,
894 flags: ltx::HEADER_FLAG_NO_CHECKSUM,
895 page_size: self.page_size,
896 commit,
897 min_txid: tx_id,
898 max_txid: tx_id,
899 timestamp: self.host.now_unix_millis(),
900 pre_apply_checksum: 0,
901 wal_offset: info.offset,
902 wal_size: sz,
903 wal_salt1: rd_salt1,
904 wal_salt2: rd_salt2,
905 node_id: 0,
906 };
907
908 // Encode the LTX file (with HeaderFlagNoChecksum, so post-apply is 0).
909 let encoded = ltx::encode_file(&header, &pages, 0)?;
910
911 // Atomic tmp → fsync → rename (db.go:1609-1685, footgun F-8).
912 let tmp_filename = format!("{filename}.tmp");
913 if let Some(parent) = Path::new(&tmp_filename).parent() {
914 self.host.create_dir_all(parent)?;
915 }
916 write_file_atomic(&self.host, &tmp_filename, &filename, &encoded).inspect_err(|_| {
917 // On rename failure, clear the L0 cache + invalidate pos
918 // (db.go:1680-1684). We do this in the error path below too.
919 })?;
920
921 // Update the L0 file-info cache and the cached position (db.go:1687-1702).
922 self.max_l0_file_info = Some(ltx::FileInfo {
923 level: 0,
924 min_txid: tx_id,
925 max_txid: tx_id,
926 pre_apply_checksum: 0,
927 post_apply_checksum: 0,
928 size: encoded.len() as i64,
929 created_at: Some(system_time_from_unix_millis(self.host.now_unix_millis())),
930 });
931 // The encoder's post-apply pos: for a NoChecksum file the post-apply
932 // checksum is 0; the position is (tx_id, 0).
933 self.pos_cache = Some(Pos::new(tx_id, 0));
934
935 // Track the logical end of WAL content for checkpoint decisions
936 // (db.go:1704-1718, issues #997/#927, footgun F-5).
937 let final_offset = info.offset + sz;
938 self.last_synced_wal_offset = final_offset;
939 self.synced_to_wal_end = match self.wal_file_size() {
940 Ok(wal_size) => final_offset == wal_size,
941 Err(_) => false,
942 };
943
944 Ok(true)
945 }
946
947 /// Collects the page set for an incremental sync, in ascending page-number
948 /// order. Pages absent from the WAL growth range come from the database file
949 /// (Litestream #1292 / celld #150).
950 fn collect_wal_pages(
951 &self,
952 wal_bytes: &[u8],
953 page_map: &HashMap<u32, i64>,
954 prev_commit: u32,
955 commit: u32,
956 ) -> Result<Vec<(u32, Vec<u8>)>> {
957 let mut pgnos: Vec<u32> = page_map.keys().copied().collect();
958 let lock = lock_pgno(self.page_size);
959 if commit > prev_commit {
960 for pgno in (prev_commit + 1)..=commit {
961 if pgno != lock && !page_map.contains_key(&pgno) {
962 pgnos.push(pgno);
963 }
964 }
965 }
966 pgnos.sort_unstable();
967
968 let mut out = Vec::with_capacity(pgnos.len());
969 let mut db_file: Option<crate::HostFile> = None;
970 for pgno in pgnos {
971 let data = if let Some(&offset) = page_map.get(&pgno) {
972 read_wal_page(wal_bytes, offset, self.page_size)?
973 } else {
974 let f = match &mut db_file {
975 Some(f) => f,
976 None => {
977 db_file = Some(self.host.open(&self.path)?);
978 db_file.as_mut().unwrap()
979 }
980 };
981 let offset = (pgno as i64 - 1) * self.page_size as i64;
982 f.read_exact_at(offset as u64, self.page_size as usize)?
983 };
984 out.push((pgno, data));
985 }
986 Ok(out)
987 }
988
989 /// Collects the full page set for a snapshot: every page `1..=commit`
990 /// (skipping the lock page), reading from the WAL where present, else the DB
991 /// file. Ported from `DB.writeLTXFromDB` (db.go:1725-1770).
992 fn collect_snapshot_pages(
993 &self,
994 wal_bytes: &[u8],
995 page_map: &HashMap<u32, i64>,
996 commit: u32,
997 ) -> Result<Vec<(u32, Vec<u8>)>> {
998 let lock = lock_pgno(self.page_size);
999 let mut db_file: Option<crate::HostFile> = None;
1000 let mut out = Vec::with_capacity(commit as usize);
1001
1002 for pgno in 1..=commit {
1003 if pgno == lock {
1004 continue;
1005 }
1006 if let Some(&offset) = page_map.get(&pgno) {
1007 let data = read_wal_page(wal_bytes, offset, self.page_size)?;
1008 out.push((pgno, data));
1009 continue;
1010 }
1011 // Read directly from the database file.
1012 let f = match &mut db_file {
1013 Some(f) => f,
1014 None => {
1015 db_file = Some(self.host.open(&self.path)?);
1016 db_file.as_mut().unwrap()
1017 }
1018 };
1019 let offset = (pgno as i64 - 1) * self.page_size as i64;
1020 let data = f.read_exact_at(offset as u64, self.page_size as usize)?;
1021 out.push((pgno, data));
1022 }
1023 Ok(out)
1024 }
1025
1026 // ── Checkpointing ──────────────────────────────────────────────────────
1027
1028 /// Performs a checkpoint based on the configured thresholds (3-tier policy).
1029 ///
1030 /// Ported from `DB.checkpointIfNeeded` (db.go:1092-1156, footgun F-5). Checks
1031 /// in priority order: TruncatePageN (TRUNCATE, blocking) → MinCheckpointPageN
1032 /// (PASSIVE) → CheckpointInterval (PASSIVE, gated on `synced_since_checkpoint`).
1033 fn checkpoint_if_needed(&mut self, orig_wal_size: i64, new_wal_size: i64) -> Result<()> {
1034 if self.page_size == 0 {
1035 return Ok(());
1036 }
1037
1038 // Priority 1: emergency TRUNCATE (blocking) on the *original* logical size.
1039 if self.truncate_page_n > 0
1040 && orig_wal_size >= calc_wal_size(self.page_size, self.truncate_page_n)
1041 {
1042 return self.checkpoint(CheckpointMode::Truncate);
1043 }
1044
1045 // Priority 2: PASSIVE at the min threshold on the *new* logical size.
1046 if new_wal_size >= calc_wal_size(self.page_size, self.min_checkpoint_page_n) {
1047 return self.checkpoint_passive_swallowing_busy();
1048 }
1049
1050 // Priority 3: time-based PASSIVE, gated on data synced since last
1051 // checkpoint (#896). Uses the DB-file mtime and a logical-size guard so an
1052 // idle DB does not spin LTX files (db.go:1133-1153).
1053 if self.checkpoint_interval > Duration::ZERO && self.synced_since_checkpoint {
1054 let elapsed = self.host.file_age(&self.path)?;
1055 if elapsed > self.checkpoint_interval && new_wal_size > calc_wal_size(self.page_size, 1)
1056 {
1057 return self.checkpoint_passive_swallowing_busy();
1058 }
1059 }
1060
1061 Ok(())
1062 }
1063
1064 /// PASSIVE checkpoint that swallows SQLITE_BUSY (log-and-continue, the one
1065 /// sanctioned best-effort case, db.go:1118-1124 / footgun F-6).
1066 fn checkpoint_passive_swallowing_busy(&mut self) -> Result<()> {
1067 match self.checkpoint(CheckpointMode::Passive) {
1068 Ok(()) => Ok(()),
1069 Err(e) if is_sqlite_busy_error(&e) => Ok(()),
1070 Err(e) => Err(e),
1071 }
1072 }
1073
1074 /// Performs a checkpoint on the WAL.
1075 ///
1076 /// Ported from `DB.Checkpoint`/`DB.checkpoint` (db.go:1801-1873, footgun F-9).
1077 /// A passive checkpoint seals the WAL under a short writer barrier before
1078 /// it runs. If any checkpoint restarts the WAL, a post-checkpoint write lock
1079 /// protects either an incremental sync or a full boundary snapshot.
1080 ///
1081 /// NOTE: the upstream `chkMu.TryLock` snapshot-vs-checkpoint gate (footgun F-3)
1082 /// is unnecessary in the synchronous `Db` — `&mut self` already serializes
1083 /// `sync`/`checkpoint`/`snapshot`. T10 preserves this by serializing access to
1084 /// the `Db` (single owner / one blocking thread).
1085 pub fn checkpoint(&mut self, mode: CheckpointMode) -> Result<()> {
1086 // Read the WAL header before the checkpoint to detect a restart.
1087 let hdr = read_wal_header(&self.host, &self.wal_path())?;
1088
1089 // Copy the end of the WAL before the checkpoint to capture as much as
1090 // possible (db.go:1823-1826).
1091 self.verify_and_sync()?;
1092
1093 let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64;
1094 let pre_checkpoint_frame_n = if self.last_synced_wal_offset > WAL_HEADER_SIZE as i64 {
1095 (self.last_synced_wal_offset - WAL_HEADER_SIZE as i64) / frame_size
1096 } else {
1097 0
1098 };
1099
1100 // A passive checkpoint does not acquire SQLite's writer lock. Hold a
1101 // short write transaction on the dedicated read-lock connection, then
1102 // sync again to seal every commit before running the checkpoint on the
1103 // main connection. Keep the barrier until the checkpoint completes.
1104 let wal_frame_n = if mode == CheckpointMode::Passive {
1105 self.exec_passive_checkpoint_with_barrier()?
1106 } else {
1107 self.exec_checkpoint(mode)?
1108 };
1109
1110 // Force a write so a restarted WAL has a new header and at least one
1111 // frame that verify can read.
1112 self.conn
1113 .execute_batch(
1114 "INSERT INTO _litestream_seq (id, seq) VALUES (1, 1) \
1115 ON CONFLICT (id) DO UPDATE SET seq = seq + 1",
1116 )
1117 .map_err(sql_err)?;
1118
1119 // If the WAL header is unchanged, the WAL did not restart — done.
1120 let other = read_wal_header(&self.host, &self.wal_path())?;
1121 if hdr == other {
1122 self.synced_since_checkpoint = false;
1123 return Ok(());
1124 }
1125
1126 // The WAL restarted. Grab the write lock, then either copy the new WAL
1127 // tail or take a complete boundary image. TRUNCATE always needs the
1128 // boundary image because SQLite reports zero frames after resetting the
1129 // WAL. A forced checkpoint also needs one if it covered more frames than
1130 // the sealed pre-checkpoint sync observed.
1131 self.conn.execute_batch("BEGIN").map_err(sql_err)?;
1132 let post = (|| -> Result<()> {
1133 self.conn
1134 .execute_batch("INSERT INTO _litestream_lock (id) VALUES (1)")
1135 .map_err(sql_err)?;
1136 if mode == CheckpointMode::Truncate
1137 || (mode != CheckpointMode::Passive && wal_frame_n > pre_checkpoint_frame_n)
1138 {
1139 let info = SyncInfo {
1140 offset: WAL_HEADER_SIZE as i64,
1141 salt1: be_u32(&other[16..]),
1142 salt2: be_u32(&other[20..]),
1143 snapshotting: true,
1144 reason: "checkpoint boundary snapshot".to_string(),
1145 ..Default::default()
1146 };
1147 self.sync_inner(info)?;
1148 } else {
1149 self.verify_and_sync()?;
1150 }
1151 Ok(())
1152 })();
1153 // Always roll back the write transaction (db.go:1849,1867).
1154 let rb = rollback(&self.conn);
1155 post?;
1156 rb?;
1157
1158 self.synced_since_checkpoint = false;
1159 Ok(())
1160 }
1161
1162 /// Seals and runs a passive checkpoint while holding SQLite's writer lock.
1163 ///
1164 /// The long-lived read transaction uses `rtx_conn`, so this method releases
1165 /// that read lock and temporarily reuses the same connection for the writer
1166 /// barrier. The checkpoint itself runs through `conn`, as SQLite does not
1167 /// permit a checkpoint on the connection that owns the write transaction.
1168 fn exec_passive_checkpoint_with_barrier(&mut self) -> Result<i64> {
1169 self.release_read_lock()?;
1170
1171 let result = (|| -> Result<i64> {
1172 self.rtx_conn.execute_batch("BEGIN").map_err(sql_err)?;
1173 self.rtx_conn
1174 .execute_batch("INSERT INTO _litestream_lock (id) VALUES (1)")
1175 .map_err(sql_err)?;
1176
1177 // Commits can land between the earlier sync and acquisition of the
1178 // barrier. This second sync seals them before the checkpoint.
1179 self.verify_and_sync()?;
1180 #[cfg(test)]
1181 if let Some(hook) = self.passive_checkpoint_barrier_hook.take() {
1182 hook();
1183 }
1184 self.run_checkpoint_pragma(CheckpointMode::Passive)
1185 })();
1186
1187 // Release the writer barrier before restoring the long-lived read lock.
1188 // Preserve the operation error if both the operation and cleanup fail.
1189 let rollback_result = rollback(&self.rtx_conn);
1190 let reacquire_result = self.acquire_read_lock();
1191 match result {
1192 Err(error) => Err(error),
1193 Ok(wal_frame_n) => {
1194 rollback_result?;
1195 reacquire_result?;
1196 Ok(wal_frame_n)
1197 }
1198 }
1199 }
1200
1201 /// Releases the read lock, runs `PRAGMA wal_checkpoint(<mode>)`, and
1202 /// re-acquires the read lock — re-acquiring even on error.
1203 ///
1204 /// Ported from `DB.execCheckpoint` (db.go:1875-1919, footgun F-1). The exact
1205 /// release→checkpoint→re-acquire sequence is load-bearing.
1206 fn exec_checkpoint(&mut self, mode: CheckpointMode) -> Result<i64> {
1207 // Ensure the read lock is removed before the checkpoint; defer the
1208 // re-acquire so it runs even on early return.
1209 self.release_read_lock()?;
1210
1211 let result = self.run_checkpoint_pragma(mode);
1212
1213 // Re-acquire the read lock immediately after the checkpoint (the deferred
1214 // re-acquire in Go). If the pragma succeeded, propagate any re-acquire
1215 // error; otherwise surface the original pragma error.
1216 let reacquire = self.acquire_read_lock();
1217 match (result, reacquire) {
1218 (Ok(wal_frame_n), Ok(())) => Ok(wal_frame_n),
1219 (Ok(_), Err(e)) => Err(e),
1220 (Err(e), _) => Err(e),
1221 }
1222 }
1223
1224 /// Runs the raw `PRAGMA wal_checkpoint(<mode>)` and reads its 3-int result.
1225 fn run_checkpoint_pragma(&self, mode: CheckpointMode) -> Result<i64> {
1226 let sql = format!("PRAGMA wal_checkpoint({mode})");
1227 let (_, wal_frame_n, _): (i64, i64, i64) = self
1228 .conn
1229 .query_row(&sql, [], |row| {
1230 Ok((
1231 row.get::<_, i64>(0)?,
1232 row.get::<_, i64>(1)?,
1233 row.get::<_, i64>(2)?,
1234 ))
1235 })
1236 .map_err(sql_err)?;
1237 Ok(wal_frame_n)
1238 }
1239
1240 // ── CRC64 ──────────────────────────────────────────────────────────────
1241
1242 /// Returns a CRC-64/ISO checksum of the database file and its current
1243 /// position, after forcing a RESTART checkpoint so the DB sits at the WAL
1244 /// start. Ported from `DB.CRC64` (db.go:2329-2359).
1245 pub fn crc64(&mut self) -> Result<(u64, Pos)> {
1246 // Force a RESTART checkpoint to ensure the DB is at the start of the WAL.
1247 self.checkpoint(CheckpointMode::Restart)?;
1248
1249 let pos = self.pos()?;
1250
1251 // Checksum the whole database file (CRC64-ISO).
1252 let bytes = self.host.read(&self.path)?;
1253 let mut h = Crc64::new();
1254 h.update(&bytes);
1255 Ok((h.sum64(), pos))
1256 }
1257
1258 // ── Snapshot ───────────────────────────────────────────────────────────
1259
1260 /// Writes a full database snapshot as an LTX file to `w` and returns the
1261 /// snapshot position. Ported from `DB.SnapshotReader` (db.go:1922-2021),
1262 /// buffered (not streamed — DECISION, see `client/mod.rs`).
1263 ///
1264 /// The snapshot spans `MinTXID=1 .. MaxTXID=pos.TXID` (db.go:1996-1997). Its
1265 /// page set is the full DB (lock page skipped), and — being a snapshot — the
1266 /// rolling post-apply checksum **is** tracked.
1267 pub fn snapshot_to_writer<W: std::io::Write>(&mut self, w: &mut W) -> Result<Pos> {
1268 if self.page_size == 0 {
1269 return Err(Error::Other(
1270 "db not ready: page size not initialized".into(),
1271 ));
1272 }
1273
1274 let pos = self.pos()?;
1275
1276 let db_size = self.db_file_size()?;
1277 let mut commit = (db_size / self.page_size as i64) as u32;
1278
1279 let wal_bytes = self.host.read(&self.wal_path())?;
1280 let mut rd = WalReader::new(&wal_bytes).map_err(Error::from)?;
1281 let (page_map, max_offset, wal_commit) = rd.page_map().map_err(Error::from)?;
1282 if wal_commit > 0 {
1283 commit = wal_commit;
1284 }
1285 let wal_offset = rd.offset();
1286 let sz = if max_offset > 0 {
1287 max_offset - wal_offset
1288 } else {
1289 0
1290 };
1291 let (salt1, salt2) = rd.salt();
1292
1293 let pages = self.collect_snapshot_pages(&wal_bytes, &page_map, commit)?;
1294
1295 // A snapshot tracks the rolling post-apply checksum (MinTXID==1, no
1296 // NoChecksum flag) — compute it the way decode_file verifies it.
1297 let lock = lock_pgno(self.page_size);
1298 let mut rolling: crate::Checksum = crate::CHECKSUM_FLAG;
1299 for (p, d) in &pages {
1300 if *p != lock {
1301 rolling = crate::CHECKSUM_FLAG | (rolling ^ ltx::checksum_page(*p, d));
1302 }
1303 }
1304
1305 let header = ltx::Header {
1306 version: ltx::VERSION,
1307 flags: 0,
1308 page_size: self.page_size,
1309 commit,
1310 min_txid: TXID(1),
1311 max_txid: pos.txid,
1312 timestamp: self.host.now_unix_millis(),
1313 pre_apply_checksum: 0,
1314 wal_offset,
1315 wal_size: sz,
1316 wal_salt1: salt1,
1317 wal_salt2: salt2,
1318 node_id: 0,
1319 };
1320
1321 let encoded = ltx::encode_file(&header, &pages, rolling)?;
1322 w.write_all(&encoded)?;
1323
1324 Ok(Pos::new(pos.txid, rolling))
1325 }
1326
1327 /// Closes the database, releasing the read lock first so other processes can
1328 /// checkpoint. Ported from the read-lock-release + connection-close portion of
1329 /// `DB.Close` (db.go:623-647). (The replica final-sync + retry land in T10.)
1330 pub fn close(mut self) -> Result<()> {
1331 self.release_read_lock()?;
1332 // The connection is dropped here, closing it.
1333 Ok(())
1334 }
1335}
1336
1337// ── free functions ─────────────────────────────────────────────────────────
1338
1339/// Returns the size of the WAL for a given page size & count, in i64 math to
1340/// avoid u32 overflow with large page sizes. Ported from `calcWALSize`
1341/// (db.go:1193-1197).
1342fn calc_wal_size(page_size: u32, page_n: u32) -> i64 {
1343 WAL_HEADER_SIZE as i64 + (WAL_FRAME_HEADER_SIZE as i64 + page_size as i64) * page_n as i64
1344}
1345
1346/// `true` if the error indicates an SQLITE_BUSY condition. Ported from
1347/// `isSQLiteBusyError` (db.go:1158-1167). Matches both the rusqlite busy code and
1348/// the Go substrings (footgun F-6).
1349fn is_sqlite_busy_error(err: &Error) -> bool {
1350 // Prefer matching the rusqlite error code when present.
1351 if let Error::Other(b) = err {
1352 if let Some(re) = b.downcast_ref::<rusqlite::Error>() {
1353 if let Some(code) = re.sqlite_error_code() {
1354 if code == rusqlite::ErrorCode::DatabaseBusy
1355 || code == rusqlite::ErrorCode::DatabaseLocked
1356 {
1357 return true;
1358 }
1359 }
1360 }
1361 }
1362 let s = err.to_string();
1363 s.contains("database is locked") || s.contains("SQLITE_BUSY")
1364}
1365
1366/// `true` if the error indicates disk space issues (ENOSPC/EDQUOT). Ported from
1367/// `isDiskFullError` (db.go:1169-1180, footgun F-6) — case-insensitive substring
1368/// match for parity with the Go test table.
1369///
1370/// Currently consumed only by tests; its production caller is the background
1371/// monitor's disk-full temp-file cleanup (db.go:2304-2309), which lands with the
1372/// `Replica` integration in T10. The classifier itself is real and tested now.
1373#[cfg_attr(not(test), allow(dead_code))]
1374fn is_disk_full_error(err_msg: &str) -> bool {
1375 let s = err_msg.to_lowercase();
1376 s.contains("no space left on device")
1377 || s.contains("disk quota exceeded")
1378 || s.contains("enospc")
1379 || s.contains("edquot")
1380}
1381
1382/// Rolls back the connection's current transaction, swallowing the
1383/// "already rolled back" / "no transaction is active" errors (issue #934).
1384/// Ported from `rollback` (litestream.go:130-135), adapted to rusqlite's message.
1385fn rollback(conn: &Connection) -> Result<()> {
1386 match conn.execute_batch("ROLLBACK") {
1387 Ok(()) => Ok(()),
1388 Err(e) => {
1389 let msg = e.to_string();
1390 // Go swallows "transaction has already been committed or rolled back".
1391 // rusqlite/SQLite reports "cannot rollback - no transaction is active".
1392 if msg.contains("transaction has already been committed or rolled back")
1393 || msg.contains("no transaction is active")
1394 || msg.contains("cannot rollback")
1395 {
1396 Ok(())
1397 } else {
1398 Err(sql_err(e))
1399 }
1400 }
1401 }
1402}
1403
1404/// Reads the 32-byte WAL header. Ported from `readWALHeader`
1405/// (litestream.go:138-148): returns the header bytes; errors if the file is
1406/// missing or shorter than 32 bytes.
1407fn read_wal_header(host: &crate::LtxHost, path: &Path) -> Result<[u8; WAL_HEADER_SIZE]> {
1408 let mut file = host.open(path)?;
1409 let bytes = file.read_exact_at(0, WAL_HEADER_SIZE)?;
1410 Ok(bytes
1411 .try_into()
1412 .expect("the exact read has the header size"))
1413}
1414
1415/// Reads `n` bytes at `offset` from a WAL file. Ported from `readWALFileAt`
1416/// (litestream.go:152-166): a short read is an "unexpected EOF" error.
1417fn read_wal_file_at(host: &crate::LtxHost, path: &Path, offset: i64, n: i64) -> Result<Vec<u8>> {
1418 let mut file = host.open(path)?;
1419 Ok(file.read_exact_at(offset as u64, n as usize)?)
1420}
1421
1422/// Reads one page's worth of bytes from an in-memory WAL buffer at the frame
1423/// `offset` (the offset is the start of the *frame header*; the page data follows
1424/// the 24-byte frame header). Mirrors `walFile.ReadAt(data, offset+WALFrameHeaderSize)`
1425/// (db.go:1745,1787).
1426fn read_wal_page(wal_bytes: &[u8], offset: i64, page_size: u32) -> Result<Vec<u8>> {
1427 let start = (offset + WAL_FRAME_HEADER_SIZE as i64) as usize;
1428 let end = start
1429 .checked_add(page_size as usize)
1430 .ok_or_else(|| Error::Other("wal page read overflow".into()))?;
1431 if end > wal_bytes.len() {
1432 return Err(Error::Io(std::io::Error::new(
1433 std::io::ErrorKind::UnexpectedEof,
1434 format!("short read wal page @ {offset}"),
1435 )));
1436 }
1437 Ok(wal_bytes[start..end].to_vec())
1438}
1439
1440/// Writes `data` to `tmp_path`, fsyncs, then renames to `final_path` — the
1441/// crash-consistent atomic-write idiom (footgun F-8). On any failure the temp
1442/// file is removed.
1443fn write_file_atomic(
1444 host: &crate::LtxHost,
1445 tmp_path: &str,
1446 final_path: &str,
1447 data: &[u8],
1448) -> Result<()> {
1449 let result = (|| -> Result<()> {
1450 let mut file = host.create(Path::new(tmp_path))?;
1451 file.write_all(data)?;
1452 file.sync_all()?;
1453 drop(file);
1454 host.rename(Path::new(tmp_path), Path::new(final_path))?;
1455 Ok(())
1456 })();
1457 if result.is_err() {
1458 let _ = host.remove_file(Path::new(tmp_path));
1459 }
1460 result
1461}
1462
1463/// Recursively removes `.tmp` files under `root`. Ported from `removeTmpFiles`
1464/// (litestream.go:169-182): missing root / errored entries are skipped.
1465fn remove_tmp_files(host: &crate::LtxHost, root: &Path) -> Result<()> {
1466 fn walk(host: &crate::LtxHost, dir: &Path) {
1467 let entries = match host.read_dir(dir) {
1468 Ok(e) => e,
1469 Err(_) => return,
1470 };
1471 for ent in entries {
1472 let path = ent.path;
1473 if ent.is_dir {
1474 walk(host, &path);
1475 } else if path.extension().and_then(|e| e.to_str()) == Some("tmp") {
1476 let _ = host.remove_file(&path);
1477 }
1478 }
1479 }
1480 walk(host, root);
1481 Ok(())
1482}
1483
1484fn system_time_from_unix_millis(milliseconds: i64) -> SystemTime {
1485 if milliseconds >= 0 {
1486 UNIX_EPOCH + Duration::from_millis(milliseconds as u64)
1487 } else {
1488 UNIX_EPOCH - Duration::from_millis(milliseconds.unsigned_abs())
1489 }
1490}
1491
1492/// Big-endian `u32` from the first four bytes of `b`.
1493#[inline]
1494fn be_u32(b: &[u8]) -> u32 {
1495 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
1496}
1497
1498#[cfg(test)]
1499// Unit tests inspect materialized file-format fixtures outside production.
1500#[allow(clippy::disallowed_methods)]
1501mod tests {
1502 use super::*;
1503
1504 // ── Test helpers ──────────────────────────────────────────────────────
1505
1506 /// Opens a managed `Db` plus a *separate* writer connection over the same
1507 /// file (the analog of testingutil.MustOpenDBs: the app writes through its
1508 /// own connection while the managed Db holds the read lock).
1509 fn open_dbs() -> (tempfile::TempDir, Db, Connection) {
1510 let dir = tempfile::tempdir().unwrap();
1511 let path = dir.path().join("db");
1512 let db = Db::open(&path).unwrap();
1513 let w = open_writer(&path);
1514 (dir, db, w)
1515 }
1516
1517 fn open_writer(path: &Path) -> Connection {
1518 let w = Connection::open(path).unwrap();
1519 w.busy_timeout(Duration::from_millis(5000)).unwrap();
1520 let _: String = w
1521 .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0))
1522 .unwrap();
1523 w
1524 }
1525
1526 fn assert_ltx_covers_commit(db: &Db, txid: TXID) {
1527 let bytes = std::fs::read(db.ltx_path(0, txid, txid)).unwrap();
1528 let decoded = ltx::decode_file(&bytes).expect("LTX decodes and verifies");
1529 let present: std::collections::BTreeSet<u32> = decoded.pgnos.iter().copied().collect();
1530 let lock = lock_pgno(db.page_size);
1531 let missing: Vec<u32> = (1..=decoded.header.commit)
1532 .filter(|pgno| *pgno != lock && !present.contains(pgno))
1533 .collect();
1534 assert!(
1535 missing.is_empty(),
1536 "LTX {txid} does not cover commit {}: missing {missing:?}",
1537 decoded.header.commit
1538 );
1539 }
1540
1541 /// Counts whole WAL frames currently in the WAL file (the Go
1542 /// `walPageCountForTest` helper, db_test.go:488-506).
1543 fn wal_page_count(db: &Db) -> i64 {
1544 let md = match std::fs::metadata(db.wal_path()) {
1545 Ok(m) => m,
1546 Err(_) => return 0,
1547 };
1548 let size = md.len() as i64;
1549 if db.page_size == 0 || size <= WAL_HEADER_SIZE as i64 {
1550 return 0;
1551 }
1552 let frame_size = WAL_FRAME_HEADER_SIZE as i64 + db.page_size as i64;
1553 (size - WAL_HEADER_SIZE as i64) / frame_size
1554 }
1555
1556 // ── Path / size unit tests ────────────────────────────────────────────
1557
1558 // Port of TestDB_Path / WALPath / MetaPath (db_test.go:22-49).
1559 #[test]
1560 fn paths_match_litestream() {
1561 // Absolute meta path: /tmp/db -> /tmp/.db-litestream.
1562 let mp = Db::meta_path_for(Path::new("/tmp/db"));
1563 assert_eq!(mp, PathBuf::from("/tmp/.db-litestream"));
1564 // Relative: db -> .db-litestream.
1565 let mp = Db::meta_path_for(Path::new("db"));
1566 assert_eq!(mp, PathBuf::from(".db-litestream"));
1567 }
1568
1569 // Port of TestCalcWALSize (db_internal_test.go:111-174): no overflow.
1570 #[test]
1571 fn calc_wal_size_no_overflow() {
1572 let cases: &[(u32, u32)] = &[
1573 (4096, 121359),
1574 (16384, 121359),
1575 (32768, 121359),
1576 (65536, 121359),
1577 (1024, 1000),
1578 ];
1579 for &(page_size, page_n) in cases {
1580 let want = WAL_HEADER_SIZE as i64
1581 + (WAL_FRAME_HEADER_SIZE as i64 + page_size as i64) * page_n as i64;
1582 let got = calc_wal_size(page_size, page_n);
1583 assert_eq!(got, want, "calc_wal_size({page_size},{page_n})");
1584 assert!(got > 0, "must be positive");
1585 if page_size >= 32768 && page_n >= 100_000 {
1586 let min_expected = page_size as i64 * page_n as i64;
1587 assert!(got >= min_expected, "suspiciously small (overflow?)");
1588 }
1589 }
1590 }
1591
1592 // Port of TestIsDiskFullError (db_internal_test.go:1064-1125).
1593 #[test]
1594 fn disk_full_error_classification() {
1595 assert!(is_disk_full_error(
1596 "write /tmp/file: no space left on device"
1597 ));
1598 assert!(is_disk_full_error("No Space Left On Device"));
1599 assert!(is_disk_full_error("write: disk quota exceeded"));
1600 assert!(is_disk_full_error("ENOSPC: cannot write file"));
1601 assert!(is_disk_full_error("error EDQUOT while writing"));
1602 assert!(is_disk_full_error("sync failed: no space left on device"));
1603 assert!(!is_disk_full_error("connection refused"));
1604 assert!(!is_disk_full_error("permission denied"));
1605 }
1606
1607 // Port of TestIsSQLiteBusyError (db_internal_test.go:1127-1164) — string path.
1608 #[test]
1609 fn sqlite_busy_error_classification() {
1610 let busy = Error::Other("database is locked".into());
1611 assert!(is_sqlite_busy_error(&busy));
1612 let busy2 = Error::Other("SQLITE_BUSY: cannot commit".into());
1613 assert!(is_sqlite_busy_error(&busy2));
1614 let other = Error::Other("connection refused".into());
1615 assert!(!is_sqlite_busy_error(&other));
1616 }
1617
1618 // ── Open / read-lock unit tests ───────────────────────────────────────
1619
1620 #[test]
1621 fn open_enables_wal_and_holds_read_lock() {
1622 let dir = tempfile::tempdir().unwrap();
1623 let path = dir.path().join("state.db");
1624 let db = Db::open(&path).unwrap();
1625
1626 assert_eq!(db.page_size(), 4096, "default sqlite page size");
1627 assert!(db.read_lock_held, "read lock acquired during open");
1628
1629 let mode: String = db
1630 .conn
1631 .query_row("PRAGMA journal_mode", [], |r| r.get(0))
1632 .unwrap();
1633 assert_eq!(mode, "wal", "journal mode persisted as WAL");
1634
1635 let autockpt: i64 = db
1636 .conn
1637 .query_row("PRAGMA wal_autocheckpoint", [], |r| r.get(0))
1638 .unwrap();
1639 assert_eq!(autockpt, 0, "auto-checkpoint disabled");
1640
1641 // WAL sidecar exists (ensure_wal_exists forced a frame).
1642 let wal = std::fs::metadata(db.wal_path()).unwrap();
1643 assert!(
1644 wal.len() >= WAL_HEADER_SIZE as u64,
1645 "WAL has at least a 32-byte header"
1646 );
1647
1648 assert_eq!(db.meta_path().file_name().unwrap(), ".state.db-litestream");
1649 assert_eq!(db.wal_path().file_name().unwrap(), "state.db-wal");
1650 }
1651
1652 // Port of TestDB_releaseReadLock_DoubleRollback (db_internal_test.go:812-869):
1653 // a second release after a rollback must NOT error (issue #934, footgun F-2).
1654 #[test]
1655 fn release_read_lock_double_rollback_is_ok() {
1656 let (_dir, mut db, w) = open_dbs();
1657 w.execute_batch("CREATE TABLE t (id INT)").unwrap();
1658
1659 // Sync acquires (re-acquires) the read lock.
1660 db.sync().unwrap();
1661 assert!(db.read_lock_held, "read lock held after sync");
1662
1663 // First rollback directly on the read-lock connection (simulates the
1664 // bare `db.rtx.Rollback()` in execCheckpoint / the Go test).
1665 db.rtx_conn.execute_batch("ROLLBACK").unwrap();
1666
1667 // release_read_lock() must be a no-op now (the flag is still set, but the
1668 // underlying ROLLBACK will report "no transaction" and be swallowed).
1669 db.release_read_lock()
1670 .expect("double release must not error");
1671 }
1672
1673 // ── Capture-loop tests (port of TestDB_Sync family, db_test.go:106-281) ──
1674
1675 // TestDB_Sync/Initial: first sync sets page size, creates the WAL, TXID 1.
1676 #[test]
1677 fn sync_initial_creates_txid_1() {
1678 let (_dir, mut db, w) = open_dbs();
1679 w.execute_batch("CREATE TABLE t (id INT)").unwrap();
1680
1681 db.sync().unwrap();
1682
1683 assert!(db.page_size() > 0, "page size available after sync");
1684 let wal = std::fs::metadata(db.wal_path()).unwrap();
1685 assert!(wal.len() > 0, "wal exists");
1686
1687 let pos = db.pos().unwrap();
1688 assert_eq!(pos.txid, TXID(1), "first sync is TXID 1");
1689
1690 // The L0 file decodes and verifies, and is a snapshot (MinTXID==1).
1691 let bytes = std::fs::read(db.ltx_path(0, TXID(1), TXID(1))).unwrap();
1692 let decoded = ltx::decode_file(&bytes).expect("L0 file decodes + verifies");
1693 assert!(decoded.header.is_snapshot(), "txid 1 is a snapshot");
1694 assert_eq!(decoded.header.max_txid, TXID(1));
1695 }
1696
1697 // TestDB_Sync/MultiSync: each sync with new writes advances TXID by exactly 1.
1698 #[test]
1699 fn sync_multi_advances_txid() {
1700 let (_dir, mut db, w) = open_dbs();
1701 w.execute_batch("CREATE TABLE foo (bar TEXT)").unwrap();
1702
1703 db.sync().unwrap();
1704 let pos0 = db.pos().unwrap();
1705
1706 w.execute("INSERT INTO foo (bar) VALUES ('baz')", [])
1707 .unwrap();
1708 db.sync().unwrap();
1709 let pos1 = db.pos().unwrap();
1710 assert_eq!(pos1.txid, TXID(pos0.txid.0 + 1), "TXID advanced by one");
1711
1712 // The incremental L0 file decodes + verifies.
1713 let bytes = std::fs::read(db.ltx_path(0, pos1.txid, pos1.txid)).unwrap();
1714 ltx::decode_file(&bytes).expect("incremental L0 file decodes + verifies");
1715 }
1716
1717 // TestDB_Sync/NoDB analog: sync on an empty (never-written) DB is fine and
1718 // produces a snapshot at TXID 1 (the DB file exists, just has no user tables).
1719 #[test]
1720 fn sync_idempotent_when_idle() {
1721 let (_dir, mut db, _w) = open_dbs();
1722 db.sync().unwrap();
1723 let pos_a = db.pos().unwrap();
1724 // A second idle sync must NOT advance the TXID (issue #896/#994).
1725 db.sync().unwrap();
1726 let pos_b = db.pos().unwrap();
1727 assert_eq!(pos_a.txid, pos_b.txid, "idle sync does not advance TXID");
1728 }
1729
1730 // TestDB_WriteLTXFromWAL_PageGrowthCoverage (db_internal_test.go:1464-1580):
1731 // when the DB grows between syncs, the incremental LTX must contain every new
1732 // page in (prevCommit, newCommit].
1733 #[test]
1734 fn incremental_ltx_covers_all_grown_pages() {
1735 let (_dir, mut db, w) = open_dbs();
1736 w.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, data BLOB)")
1737 .unwrap();
1738 for i in 0..5 {
1739 w.execute(
1740 "INSERT INTO t VALUES (?, ?)",
1741 rusqlite::params![i, vec![0u8; 100]],
1742 )
1743 .unwrap();
1744 }
1745 db.sync().unwrap();
1746 let pos1 = db.pos().unwrap();
1747 let prev_commit =
1748 ltx::Header::parse(&std::fs::read(db.ltx_path(0, pos1.txid, pos1.txid)).unwrap())
1749 .unwrap()
1750 .commit;
1751
1752 for i in 5..150 {
1753 w.execute(
1754 "INSERT INTO t VALUES (?, ?)",
1755 rusqlite::params![i, vec![0u8; 3000]],
1756 )
1757 .unwrap();
1758 }
1759 db.sync().unwrap();
1760 let pos2 = db.pos().unwrap();
1761
1762 let bytes = std::fs::read(db.ltx_path(0, pos2.txid, pos2.txid)).unwrap();
1763 let new_commit = ltx::Header::parse(&bytes).unwrap().commit;
1764 let decoded = ltx::decode_file(&bytes).expect("decodes + verifies");
1765 let present: std::collections::BTreeSet<u32> = decoded.pgnos.iter().copied().collect();
1766
1767 let lock = lock_pgno(db.page_size);
1768 let mut missing = Vec::new();
1769 for pgno in (prev_commit + 1)..=new_commit {
1770 if pgno == lock {
1771 continue;
1772 }
1773 if !present.contains(&pgno) {
1774 missing.push(pgno);
1775 }
1776 }
1777 assert!(
1778 missing.is_empty(),
1779 "pages missing from incremental LTX: {missing:?} (prev={prev_commit}, new={new_commit})"
1780 );
1781 }
1782
1783 #[test]
1784 fn incremental_ltx_fills_checkpointed_growth_pages_from_database() {
1785 let (_dir, mut db, w) = open_dbs();
1786 w.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, data BLOB)")
1787 .unwrap();
1788 for i in 0..10 {
1789 w.execute(
1790 "INSERT INTO t VALUES (?, ?)",
1791 rusqlite::params![i, vec![0u8; 100]],
1792 )
1793 .unwrap();
1794 }
1795 db.sync().unwrap();
1796 let previous = db.pos().unwrap();
1797 let previous_header = ltx::Header::parse(
1798 &std::fs::read(db.ltx_path(0, previous.txid, previous.txid)).unwrap(),
1799 )
1800 .unwrap();
1801
1802 // Move database growth out of the old WAL, then create a small restarted
1803 // WAL. verify() treats this as an expected checkpoint and performs an
1804 // incremental capture, so pages absent from the new WAL must come from
1805 // the database file.
1806 db.release_read_lock().unwrap();
1807 for i in 10..310 {
1808 w.execute(
1809 "INSERT INTO t VALUES (?, ?)",
1810 rusqlite::params![i, vec![i as u8; 4000]],
1811 )
1812 .unwrap();
1813 }
1814 let (busy, wal_frames, checkpointed): (i64, i64, i64) = w
1815 .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
1816 Ok((row.get(0)?, row.get(1)?, row.get(2)?))
1817 })
1818 .unwrap();
1819 assert_eq!(busy, 0);
1820 assert_eq!(wal_frames, checkpointed);
1821 w.execute(
1822 "INSERT INTO t VALUES (?, ?)",
1823 rusqlite::params![310, vec![1u8; 32]],
1824 )
1825 .unwrap();
1826 db.acquire_read_lock().unwrap();
1827
1828 let info = db.verify().unwrap();
1829 assert!(
1830 !info.snapshotting,
1831 "expected incremental checkpoint recovery"
1832 );
1833 assert_eq!(info.prev_commit, previous_header.commit);
1834 assert!(db.sync_inner(info).unwrap());
1835
1836 let current = db.pos().unwrap();
1837 let bytes = std::fs::read(db.ltx_path(0, current.txid, current.txid)).unwrap();
1838 let decoded = ltx::decode_file(&bytes).unwrap();
1839 let present: std::collections::HashSet<u32> = decoded.pgnos.iter().copied().collect();
1840 let lock = lock_pgno(db.page_size);
1841 let missing: Vec<u32> = ((previous_header.commit + 1)..=decoded.header.commit)
1842 .filter(|pgno| *pgno != lock && !present.contains(pgno))
1843 .collect();
1844 assert!(
1845 missing.is_empty(),
1846 "incremental LTX omitted checkpointed growth pages: {missing:?}"
1847 );
1848 }
1849
1850 // TestDB_Verify_WALOffsetAtHeader (db_internal_test.go:565-681): an L0 file
1851 // with WALOffset=32, WALSize=0 and matching salt → snapshotting=false,
1852 // offset=32, no underflow (issue #900).
1853 #[test]
1854 fn verify_wal_offset_at_header_salt_match() {
1855 let (_dir, mut db, w) = open_dbs();
1856 w.execute_batch("CREATE TABLE t (id INT)").unwrap();
1857 db.sync().unwrap();
1858
1859 let wal_hdr = read_wal_header(&db.host, &db.wal_path()).unwrap();
1860 let salt1 = be_u32(&wal_hdr[16..]);
1861 let salt2 = be_u32(&wal_hdr[20..]);
1862
1863 let pos = db.pos().unwrap();
1864 let next = TXID(pos.txid.0 + 1);
1865
1866 // Write an L0 file directly with WALOffset=32, WALSize=0 (the #900 shape).
1867 let header = ltx::Header {
1868 version: ltx::VERSION,
1869 flags: ltx::HEADER_FLAG_NO_CHECKSUM,
1870 page_size: db.page_size,
1871 commit: 2,
1872 min_txid: next,
1873 max_txid: next,
1874 timestamp: 1_000_000,
1875 pre_apply_checksum: 0,
1876 wal_offset: WAL_HEADER_SIZE as i64,
1877 wal_size: 0,
1878 wal_salt1: salt1,
1879 wal_salt2: salt2,
1880 node_id: 0,
1881 };
1882 // A header-only LTX file (no pages) — still decodes for the header read.
1883 let encoded = ltx::encode_file(&header, &[], 0).unwrap();
1884 std::fs::write(db.ltx_path(0, next, next), &encoded).unwrap();
1885 db.invalidate_pos_cache();
1886
1887 let info = db.verify().expect("verify must not error (no underflow)");
1888 assert_eq!(
1889 info.offset, WAL_HEADER_SIZE as i64,
1890 "offset stays at header"
1891 );
1892 assert!(!info.snapshotting, "salt matches => no snapshot");
1893 }
1894
1895 // TestDB_Verify_WALOffsetAtHeader_SaltMismatch (db_internal_test.go:687-805):
1896 // same shape but mismatched salt → snapshotting=true with the exact reason.
1897 #[test]
1898 fn verify_wal_offset_at_header_salt_mismatch() {
1899 let (_dir, mut db, w) = open_dbs();
1900 w.execute_batch("CREATE TABLE t (id INT)").unwrap();
1901 db.sync().unwrap();
1902
1903 let wal_hdr = read_wal_header(&db.host, &db.wal_path()).unwrap();
1904 let salt1 = be_u32(&wal_hdr[16..]);
1905 let salt2 = be_u32(&wal_hdr[20..]);
1906
1907 let pos = db.pos().unwrap();
1908 let next = TXID(pos.txid.0 + 1);
1909
1910 let header = ltx::Header {
1911 version: ltx::VERSION,
1912 flags: ltx::HEADER_FLAG_NO_CHECKSUM,
1913 page_size: db.page_size,
1914 commit: 2,
1915 min_txid: next,
1916 max_txid: next,
1917 timestamp: 1_000_000,
1918 pre_apply_checksum: 0,
1919 wal_offset: WAL_HEADER_SIZE as i64,
1920 wal_size: 0,
1921 wal_salt1: salt1.wrapping_add(1),
1922 wal_salt2: salt2.wrapping_add(1),
1923 node_id: 0,
1924 };
1925 let encoded = ltx::encode_file(&header, &[], 0).unwrap();
1926 std::fs::write(db.ltx_path(0, next, next), &encoded).unwrap();
1927 db.invalidate_pos_cache();
1928
1929 let info = db.verify().expect("verify must not error");
1930 assert_eq!(info.offset, WAL_HEADER_SIZE as i64);
1931 assert!(info.snapshotting, "salt mismatch => snapshot");
1932 assert_eq!(info.reason, "wal header salt reset, snapshotting");
1933 }
1934
1935 // TestDB_CheckpointDoesNotTriggerSnapshot (db_internal_test.go:877-984):
1936 // a checkpoint followed by a write must NOT make verify() request a snapshot
1937 // (issue #927). Run for both TRUNCATE and PASSIVE modes.
1938 fn checkpoint_does_not_trigger_snapshot(mode: CheckpointMode) {
1939 let (_dir, mut db, w) = open_dbs();
1940 db.checkpoint_interval = Duration::ZERO; // disable time-based checkpoints
1941 w.execute_batch("CREATE TABLE t (id INT, data TEXT)")
1942 .unwrap();
1943 for i in 0..100 {
1944 w.execute(
1945 "INSERT INTO t VALUES (?, ?)",
1946 rusqlite::params![i, format!("padding row {i} with content")],
1947 )
1948 .unwrap();
1949 }
1950
1951 db.sync().unwrap();
1952 w.execute("INSERT INTO t VALUES (9999, 'before checkpoint')", [])
1953 .unwrap();
1954 db.sync().unwrap();
1955
1956 let info1 = db.verify().unwrap();
1957 assert!(!info1.snapshotting, "pre-checkpoint sync is incremental");
1958
1959 db.checkpoint(mode).unwrap();
1960
1961 w.execute("INSERT INTO t VALUES (10000, 'after checkpoint')", [])
1962 .unwrap();
1963
1964 let info2 = db.verify().unwrap();
1965 assert!(
1966 !info2.snapshotting,
1967 "checkpoint+sync must not snapshot (mode={mode}, reason={:?})",
1968 info2.reason
1969 );
1970 }
1971
1972 #[test]
1973 fn checkpoint_does_not_trigger_snapshot_truncate() {
1974 checkpoint_does_not_trigger_snapshot(CheckpointMode::Truncate);
1975 }
1976
1977 #[test]
1978 fn checkpoint_does_not_trigger_snapshot_passive() {
1979 checkpoint_does_not_trigger_snapshot(CheckpointMode::Passive);
1980 }
1981
1982 #[test]
1983 fn passive_checkpoint_holds_writer_barrier_through_pragma() {
1984 let (_dir, mut db, w) = open_dbs();
1985 w.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, data BLOB)")
1986 .unwrap();
1987 w.execute("INSERT INTO t VALUES (1, zeroblob(4096))", [])
1988 .unwrap();
1989 db.sync().unwrap();
1990 drop(w);
1991
1992 let path = db.path.clone();
1993 db.passive_checkpoint_barrier_hook = Some(Box::new(move || {
1994 let w = open_writer(&path);
1995 w.busy_timeout(Duration::ZERO).unwrap();
1996 let blocked = match w.execute("INSERT INTO t VALUES (2, zeroblob(4096))", []) {
1997 Ok(_) => false,
1998 Err(error) => matches!(
1999 error.sqlite_error_code(),
2000 Some(rusqlite::ErrorCode::DatabaseBusy)
2001 | Some(rusqlite::ErrorCode::DatabaseLocked)
2002 ),
2003 };
2004 assert!(
2005 blocked,
2006 "a writer was not blocked while the passive checkpoint barrier was held"
2007 );
2008 }));
2009 db.checkpoint(CheckpointMode::Passive).unwrap();
2010
2011 // The barrier transaction rolls back after the checkpoint.
2012 let w = open_writer(db.path());
2013 w.execute("INSERT INTO t VALUES (3, zeroblob(4096))", [])
2014 .unwrap();
2015 }
2016
2017 #[test]
2018 fn truncate_checkpoint_writes_complete_boundary_ltx() {
2019 let (_dir, mut db, w) = open_dbs();
2020 w.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, data BLOB)")
2021 .unwrap();
2022 db.sync().unwrap();
2023 for i in 0..200 {
2024 w.execute(
2025 "INSERT INTO t VALUES (?, ?)",
2026 rusqlite::params![i, vec![i as u8; 4000]],
2027 )
2028 .unwrap();
2029 }
2030
2031 db.checkpoint(CheckpointMode::Truncate).unwrap();
2032
2033 let pos = db.pos().unwrap();
2034 assert_ltx_covers_commit(&db, pos.txid);
2035 }
2036
2037 // TestDB_MultipleCheckpointsWithWrites (db_internal_test.go:989-1061): repeated
2038 // checkpoint+write cycles must trigger at most one snapshot (the initial one).
2039 #[test]
2040 fn multiple_checkpoints_with_writes_snapshot_at_most_once() {
2041 let (_dir, mut db, w) = open_dbs();
2042 db.checkpoint_interval = Duration::ZERO;
2043 w.execute_batch("CREATE TABLE t (id INT, data TEXT)")
2044 .unwrap();
2045
2046 let mut snapshot_count = 0;
2047 for cycle in 0..5 {
2048 for i in 0..10 {
2049 w.execute(
2050 "INSERT INTO t VALUES (?, ?)",
2051 rusqlite::params![cycle * 100 + i, "data"],
2052 )
2053 .unwrap();
2054 }
2055 db.sync().unwrap();
2056 if db.verify().unwrap().snapshotting {
2057 snapshot_count += 1;
2058 }
2059 db.checkpoint(CheckpointMode::Passive).unwrap();
2060 }
2061 assert!(
2062 snapshot_count <= 1,
2063 "too many snapshots: {snapshot_count} (expected <= 1)"
2064 );
2065 }
2066
2067 // TestDB_IdleCheckpointSnapshotLoop (db_internal_test.go:1178-1256): after a
2068 // checkpoint, idle sync cycles must NOT keep incrementing the TXID (issue #997
2069 // — checkpoint decisions use the logical WAL offset, not file size).
2070 #[test]
2071 fn idle_checkpoint_does_not_loop() {
2072 let (_dir, mut db, w) = open_dbs();
2073 db.checkpoint_interval = Duration::ZERO;
2074 db.min_checkpoint_page_n = 10;
2075 w.execute_batch("CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)")
2076 .unwrap();
2077 db.sync().unwrap();
2078
2079 for i in 0..100 {
2080 w.execute(
2081 "INSERT INTO test VALUES (?, ?)",
2082 rusqlite::params![i, "test data padding"],
2083 )
2084 .unwrap();
2085 }
2086 db.sync().unwrap();
2087 db.checkpoint(CheckpointMode::Passive).unwrap();
2088 let after_ckpt = db.pos().unwrap();
2089
2090 for _ in 0..5 {
2091 db.sync().unwrap();
2092 }
2093 let final_pos = db.pos().unwrap();
2094
2095 let growth = final_pos.txid.0 as i64 - after_ckpt.txid.0 as i64;
2096 assert!(
2097 growth <= 1,
2098 "TXID grew by {growth} during idle cycles (expected <= 1) — issue #997"
2099 );
2100 }
2101
2102 // TestDB_Issue994_RunawayDiskUsage (db_internal_test.go:1262-1350): after bulk
2103 // writes + checkpoint, 20 idle sync cycles must add at most ~2 LTX files.
2104 #[test]
2105 fn idle_cycles_do_not_grow_ltx_dir() {
2106 let (_dir, mut db, w) = open_dbs();
2107 db.checkpoint_interval = Duration::ZERO;
2108 db.min_checkpoint_page_n = 10;
2109 w.execute_batch("CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)")
2110 .unwrap();
2111 db.sync().unwrap();
2112
2113 for i in 0..200 {
2114 w.execute(
2115 "INSERT INTO test VALUES (?, ?)",
2116 rusqlite::params![i, "padding data for disk usage test"],
2117 )
2118 .unwrap();
2119 }
2120 db.sync().unwrap();
2121 db.checkpoint(CheckpointMode::Passive).unwrap();
2122
2123 let baseline_files = count_files(&db.ltx_level_dir(0));
2124 for _ in 0..20 {
2125 db.sync().unwrap();
2126 }
2127 let final_files = count_files(&db.ltx_level_dir(0));
2128
2129 let new_files = final_files - baseline_files;
2130 assert!(
2131 new_files <= 2,
2132 "LTX file count grew by {new_files} during 20 idle cycles (expected <= 2) — issue #994"
2133 );
2134 }
2135
2136 fn count_files(dir: &str) -> i64 {
2137 match std::fs::read_dir(dir) {
2138 Ok(entries) => entries.flatten().filter(|e| e.path().is_file()).count() as i64,
2139 Err(_) => 0,
2140 }
2141 }
2142
2143 // ── Checkpoint-policy tests (port of TestDB_Sync sub-tests) ────────────
2144
2145 // TestDB_Sync/MinCheckpointPageN (db_test.go:284-315): exceeding the page
2146 // threshold triggers a PASSIVE checkpoint, advancing to TXID 3.
2147 #[test]
2148 fn min_checkpoint_page_n_triggers_passive_checkpoint() {
2149 let (_dir, mut db, w) = open_dbs();
2150 db.checkpoint_interval = Duration::ZERO; // isolate the page-count trigger
2151 w.execute_batch("CREATE TABLE foo (bar TEXT)").unwrap();
2152 db.sync().unwrap();
2153
2154 for _ in 0..db.min_checkpoint_page_n {
2155 w.execute("INSERT INTO foo (bar) VALUES ('baz')", [])
2156 .unwrap();
2157 }
2158 db.sync().unwrap();
2159
2160 let pos = db.pos().unwrap();
2161 assert_eq!(
2162 pos.txid,
2163 TXID(3),
2164 "TXID 1=initial, 2=after inserts, 3=after PASSIVE checkpoint"
2165 );
2166 }
2167
2168 // TestDB_Sync/TruncatePageN (db_test.go:317-350): with TruncatePageN=1, the
2169 // WAL is truncated back to <=1 page after a sync.
2170 #[test]
2171 fn truncate_page_n_shrinks_wal() {
2172 let (_dir, mut db, w) = open_dbs();
2173 db.truncate_page_n = 1;
2174 db.checkpoint_interval = Duration::ZERO;
2175 w.execute_batch("CREATE TABLE foo (bar TEXT)").unwrap();
2176 db.sync().unwrap();
2177
2178 let payload = "x".repeat(db.page_size as usize);
2179 while wal_page_count(&db) <= 1 {
2180 w.execute("INSERT INTO foo (bar) VALUES (?)", [&payload])
2181 .unwrap();
2182 }
2183 db.sync().unwrap();
2184
2185 assert!(
2186 wal_page_count(&db) <= 1,
2187 "truncate checkpoint should shrink the WAL, pages={}",
2188 wal_page_count(&db)
2189 );
2190 }
2191
2192 // ── CRC64 / snapshot tests ────────────────────────────────────────────
2193
2194 // TestDB_CRC64 (db_test.go:52-103): checksum changes after a WAL write, and
2195 // again after a checkpoint folds the change into the DB.
2196 #[test]
2197 fn crc64_changes_on_write_and_checkpoint() {
2198 let (_dir, mut db, w) = open_dbs();
2199 db.sync().unwrap();
2200
2201 let (chk0, _) = db.crc64().unwrap();
2202
2203 w.execute_batch("CREATE TABLE t (id INT)").unwrap();
2204 let (chk1, _) = db.crc64().unwrap();
2205 assert_ne!(chk0, chk1, "checksum changes after a WAL change");
2206
2207 db.checkpoint(CheckpointMode::Truncate).unwrap();
2208 let (chk2, _) = db.crc64().unwrap();
2209 assert_ne!(chk0, chk2, "checksum changes after a checkpoint");
2210 }
2211
2212 // TestDB_Snapshot (db_test.go:508-551, conformance-critical): the snapshot LTX
2213 // file's CRC64-ISO over its decoded database must equal the local DB CRC64.
2214 #[test]
2215 fn snapshot_checksum_matches_local_db() {
2216 let (_dir, mut db, w) = open_dbs();
2217 w.execute_batch("CREATE TABLE t (id INT)").unwrap();
2218 db.sync().unwrap();
2219 w.execute("INSERT INTO t (id) VALUES (100)", []).unwrap();
2220 db.sync().unwrap();
2221
2222 // The snapshot spans 1..pos.TXID; filename 0…01-0…02.ltx.
2223 let pos = db.pos().unwrap();
2224 assert_eq!(pos.txid, TXID(2), "two syncs => TXID 2");
2225
2226 // Mirror TestDB_Snapshot ordering: take the snapshot FIRST (at TXID 2),
2227 // reconstruct its full database image, then compute the local DB CRC64
2228 // (which forces a RESTART checkpoint folding the WAL into the DB file).
2229 // The snapshot image must equal the post-RESTART database.
2230 let mut buf = Vec::new();
2231 let snap_pos = db.snapshot_to_writer(&mut buf).unwrap();
2232 assert_eq!(snap_pos.txid, TXID(2), "snapshot captured at TXID 2");
2233
2234 let (local_crc, _) = db.crc64().unwrap();
2235
2236 let image = ltx::decode_database_image(&buf).expect("decode snapshot db image");
2237 let mut h = Crc64::new();
2238 h.update(&image);
2239 assert_eq!(
2240 h.sum64(),
2241 local_crc,
2242 "snapshot database checksum must equal local DB CRC64"
2243 );
2244 }
2245
2246 // ── reset_local_state ─────────────────────────────────────────────────
2247
2248 // TestDB_ResetLocalState (db_test.go:1660+): removing the LTX dir + clearing
2249 // the cache resets the position so the next sync snapshots fresh.
2250 #[test]
2251 fn reset_local_state_clears_position() {
2252 let (_dir, mut db, w) = open_dbs();
2253 w.execute_batch("CREATE TABLE t (id INT)").unwrap();
2254 db.sync().unwrap();
2255 assert_eq!(db.pos().unwrap().txid, TXID(1));
2256
2257 db.reset_local_state().unwrap();
2258 assert_eq!(db.pos().unwrap().txid, TXID(0), "position reset to zero");
2259
2260 // The next sync re-snapshots at TXID 1.
2261 db.sync().unwrap();
2262 assert_eq!(db.pos().unwrap().txid, TXID(1));
2263 let bytes = std::fs::read(db.ltx_path(0, TXID(1), TXID(1))).unwrap();
2264 assert!(
2265 ltx::decode_file(&bytes).unwrap().header.is_snapshot(),
2266 "fresh snapshot after reset"
2267 );
2268 }
2269
2270 // ── pos() error mapping ───────────────────────────────────────────────
2271
2272 // TestDB_Pos_VerifyErrorReturnsLTXError (db_internal_test.go:2096-2127):
2273 // a corrupt L0 file makes pos() return an LTXError{op:"verify"} wrapping
2274 // ErrLTXCorrupted, which is auto-recoverable.
2275 #[test]
2276 fn pos_verify_error_returns_ltx_error() {
2277 let dir = tempfile::tempdir().unwrap();
2278 let path = dir.path().join("test.db");
2279 let mut db = Db::open(&path).unwrap();
2280
2281 std::fs::create_dir_all(db.ltx_level_dir(0)).unwrap();
2282 std::fs::write(db.ltx_path(0, TXID(1), TXID(1)), b"not a valid ltx file").unwrap();
2283 db.invalidate_pos_cache();
2284
2285 let err = db.pos().expect_err("expected error");
2286 match err {
2287 Error::Ltx(ref e) => {
2288 assert_eq!(e.op, "verify", "op must be verify");
2289 assert!(e.is_auto_recoverable(), "corruption is auto-recoverable");
2290 }
2291 other => panic!("expected LTXError, got {other:?}"),
2292 }
2293 }
2294}