Diffinery

homeflare/celldpublic

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