Diffinery

homeflare/celldpublic

2562 lines · 107.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//! The highest-risk interaction is a long-running read transaction with a manual
6//! `PRAGMA wal_checkpoint`, so the implementation uses independently tested steps.
7//!
8//! ## Async/blocking shape
9//! `rusqlite::Connection` is `!Sync` and a `rusqlite::Transaction` borrows its
10//! `Connection`. Rather than thread a borrow across `.await`, this module keeps
11//! the capture API **synchronous** and owns the connection directly: the
12//! long-running read transaction is held with raw `BEGIN`/`ROLLBACK` SQL plus a
13//! `read_lock_held` flag — exactly as Go does (`acquireReadLock` runs `BEGIN` +
14//! `SELECT COUNT(1)`, db.go:956-976; `releaseReadLock` rolls back, db.go:979-992).
15//! `Replica` drives `sync()` and `checkpoint()` from a blocking context
16//! (`spawn_blocking` or a dedicated DB thread). This sidesteps the !Sync/borrow
17//! problem entirely and makes the idempotent-release behavior (issue #934) a
18//! trivial flag check.
19//!
20//! ## What this implements (the functional capture path)
21//! - `open`/`init`: WAL-mode DSN, `wal_autocheckpoint(0)`, control tables, read
22//! page size, acquire the read lock, ensure the WAL has ≥1 frame.
23//! - `acquire_read_lock`/`release_read_lock`: the checkpoint takeover; release is
24//! idempotent (db.go:979-992 / issue #934).
25//! - `sync` → `verify` → `sync_inner` → `write_ltx_from_wal`/`write_ltx_from_db`:
26//! diff the real WAL against the last LTX position and write the next L0 LTX
27//! file (`db.go:1517-1723`), with atomic tmp→rename and the pos cache.
28//! - `verify`: the snapshot-on-continuity-break branch lattice
29//! (`db.go:1296-1436`), including the issue #900 / #927 edge cases.
30//! - `checkpoint`/`exec_checkpoint`: release→`PRAGMA wal_checkpoint(<mode>)`→
31//! re-acquire (`db.go:1875-1919`) and the two-phase WAL-restart handling
32//! (`db.go:1808-1873`).
33//! - `checkpoint_if_needed`: the 3-tier policy + the three anti-feedback flags
34//! (`synced_since_checkpoint`/`synced_to_wal_end`/`last_synced_wal_offset`,
35//! issues #896/#927/#997).
36//! - Litestream #1292 / celld #150: seal passive checkpoints with a writer
37//! barrier, retain database-growth pages, and snapshot truncate boundaries.
38//! - `crc64`, `pos` (cached + `LTXError` mapping), `reset_local_state`,
39//! `snapshot_to_writer`.
40//!
41//! ## Deferred work outside the functional path
42//! - `setPersistWAL` (the `unsafe` `sqlite3_file_control(SQLITE_FCNTL_PERSIST_WAL)`
43//! FFI): 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, `ensure_exists`, `sync_status`, `sync_and_wait`,
46//! retention, and retry behavior are not implemented.
47//! - A `loom` model of the lock protocol.
48
49use crate::error::{new_ltx_error, Error, Result};
50use crate::ltx::{self, lock_pgno, Crc64};
51use crate::wal::{WalError, WalReader};
52use crate::{
53 ltx_file_path, ltx_level_dir, Pos, CHECKPOINT_MODE_PASSIVE, CHECKPOINT_MODE_RESTART,
54 CHECKPOINT_MODE_TRUNCATE, META_DIR_SUFFIX, TXID, WAL_FRAME_HEADER_SIZE, WAL_HEADER_SIZE,
55};
56use rusqlite::ffi;
57use rusqlite::Connection;
58use rusqlite::OpenFlags;
59use std::collections::HashMap;
60use std::ffi::c_int;
61use std::path::{Path, PathBuf};
62use std::time::{Duration, SystemTime, UNIX_EPOCH};
63
64/// Maps a `rusqlite::Error` into the crate error type.
65fn sql_err(e: rusqlite::Error) -> Error {
66 Error::Other(Box::new(e))
67}
68
69fn disable_lookaside(conn: &Connection) -> Result<()> {
70 // SQLite's default lookaside arena reserves 48 KiB for each connection.
71 // Every resident cell owns both connections below, so the unused arenas
72 // repeat a fixed cost at fleet density. LTX prepares a fixed, small SQL
73 // vocabulary, and the measured durable-write throughput stays flat when
74 // general allocations replace these arenas.
75 //
76 // SAFETY: the caller passes a newly opened connection before its first
77 // SQLite operation, so no lookaside slot can be in use.
78 let result = unsafe {
79 ffi::sqlite3_db_config(
80 conn.handle(),
81 ffi::SQLITE_DBCONFIG_LOOKASIDE,
82 std::ptr::null_mut::<std::ffi::c_void>(),
83 0,
84 0,
85 )
86 };
87 if result != ffi::SQLITE_OK {
88 return Err(Error::Other(
89 format!("disable SQLite lookaside failed: {result}").into(),
90 ));
91 }
92 Ok(())
93}
94
95/// SQLite checkpoint mode. Replaces Go's stringly-typed `mode` param; `Display`
96/// interpolates straight into `PRAGMA wal_checkpoint(<mode>)` (db.go:1905), so it
97/// must render exactly `PASSIVE`/`FULL`/`RESTART`/`TRUNCATE`.
98///
99/// Ported from [email protected] litestream.go:22-28. RESTART was removed from
100/// automatic use (issue #724) but is still callable (`crc64` forces it), so all
101/// four variants are kept.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum CheckpointMode {
104 /// Non-blocking checkpoint; skips if there are active transactions.
105 Passive,
106 /// Like RESTART but does not block new transactions before flushing.
107 Full,
108 /// Blocks new transactions, flushes, and restarts the WAL.
109 Restart,
110 /// Like RESTART plus truncates the WAL file to zero length.
111 Truncate,
112}
113
114/// The three columns of `PRAGMA wal_checkpoint`: whether a lock stopped the
115/// checkpoint, the frames in the WAL, and the frames backfilled.
116#[derive(Clone, Copy, Debug)]
117struct CheckpointPragma {
118 busy: i64,
119 wal_frames: i64,
120 backfilled: i64,
121}
122
123impl std::fmt::Display for CheckpointMode {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 let s = match self {
126 CheckpointMode::Passive => CHECKPOINT_MODE_PASSIVE,
127 CheckpointMode::Full => crate::CHECKPOINT_MODE_FULL,
128 CheckpointMode::Restart => CHECKPOINT_MODE_RESTART,
129 CheckpointMode::Truncate => CHECKPOINT_MODE_TRUNCATE,
130 };
131 f.write_str(s)
132 }
133}
134
135/// `verify()`'s decision result (db.go:1509-1515).
136#[derive(Debug, Clone, Default)]
137struct SyncInfo {
138 /// End of the previous LTX read (byte offset into the WAL).
139 offset: i64,
140 salt1: u32,
141 salt2: u32,
142 /// Database page count recorded by the previous LTX file.
143 prev_commit: u32,
144 /// If true, a full snapshot is required.
145 snapshotting: bool,
146 /// Reason for the snapshot, for logging and diagnostics.
147 reason: String,
148}
149
150/// Databases larger than this many pages (4 MiB at 4 KiB) must outgrow
151/// themselves in the WAL before a TRUNCATE checkpoint, since the checkpoint
152/// ends in a boundary image of the whole database. Smaller ones keep the
153/// absolute `truncate_page_n` threshold.
154const RELATIVE_TRUNCATE_PAGES: u32 = 1024;
155
156/// A SQLite database managed for replication.
157///
158/// Owns the connection (WAL mode, auto-checkpoint disabled) so litestream — not
159/// SQLite — decides when the WAL is checkpointed, and holds the long-running read
160/// transaction that takes over checkpointing.
161///
162/// Ported from `DB` (db.go:64-198). The synchronous `!Sync` connection stays on
163/// the thread that drives it.
164/// What `verify` reads back from the last L0 this instance wrote: the
165/// header fields, plus the final consumed WAL frame's page. The ported
166/// check decodes the whole L0 and searches its pages for that frame; the
167/// L0's entry for the final frame's page IS that frame (page-map keeps
168/// the last write per page, and nothing follows the final frame), so
169/// comparing against the cached frame answers the same question — and a
170/// spurious mismatch only forces a snapshot, the safe direction.
171fn snapshot_reason_code(reason: &str) -> u8 {
172 match reason {
173 "" => 1, // first sync leaves the default reason empty
174 "wal truncated by another process" => 2,
175 "wal header salt reset, snapshotting" => 3,
176 "last page does not exist in last ltx file, wal overwritten by another process" => 4,
177 "full or restart checkpoint detected, snapshotting" => 5,
178 "checkpoint boundary snapshot" => 6,
179 "WAL restarted before passive checkpoint barrier" => 8,
180 _ => 7,
181 }
182}
183
184#[derive(Clone, Debug)]
185struct LastL0Header {
186 wal_offset: i64,
187 wal_size: i64,
188 wal_salt1: u32,
189 wal_salt2: u32,
190 commit: u32,
191 final_pgno: u32,
192 final_page: Vec<u8>,
193}
194
195/// Per-phase wall time of one `Db::sync` call, in microseconds.
196#[derive(Clone, Copy, Debug, Default)]
197pub struct SyncTiming {
198 /// Control-table self-heal and WAL existence checks.
199 pub prepare_us: u64,
200 /// The two halves of `prepare_us`: the schema-version pragma (plus
201 /// the DDL when it fires) and the WAL existence stat, so a field
202 /// inflation names its syscall.
203 pub schema_check_us: u64,
204 pub wal_exists_us: u64,
205 /// `verify`: the WAL scan and continuity validation.
206 pub verify_us: u64,
207 /// `sync_inner` minus the fsync: WAL page reads, LTX encode, the file
208 /// write and rename.
209 pub encode_write_us: u64,
210 /// The sub-phases of `encode_write_us`, so a field inflation names its
211 /// line instead of hiding in the aggregate: position resolution, the
212 /// WAL read (tail or full), page-map plus page collection, the LTX
213 /// encode, and the file write-and-rename.
214 pub pos_us: u64,
215 pub wal_read_us: u64,
216 pub map_collect_us: u64,
217 pub ltx_encode_us: u64,
218 pub file_write_us: u64,
219 /// The WAL length seen by this call, for scaling.
220 pub wal_len_bytes: u64,
221 /// True when this call snapshotted (the full-database path).
222 pub snapshot: bool,
223 /// Which WAL read ran: 0 valid tail, 1 full because snapshotting, 2 valid
224 /// prefix because the offset sat at the WAL start, 3 full because the
225 /// bounded read fell back. `wal_read_bytes` is what that read actually
226 /// transferred, including a bounded probe past the valid checksum chain.
227 pub wal_read_kind: u8,
228 pub wal_read_bytes: u64,
229 /// The bytes the sync allocated to hold what it read: the tail plus the
230 /// header on the tail path, the file otherwise.
231 pub wal_image_bytes: u64,
232 /// Which verify branch forced the snapshot: 0 none, 1 first sync,
233 /// 2 wal truncated by another process, 3 salt reset, 4 last page
234 /// missing from the last L0, 5 full or restart checkpoint detected,
235 /// 6 checkpoint boundary, 7 other, 8 WAL restarted before the passive
236 /// checkpoint barrier.
237 pub snapshot_reason: u8,
238 /// The cut file's fsync (zero under lazy capture).
239 pub fsync_us: u64,
240 /// `checkpoint_if_needed`: SQLite's checkpoint, including its own
241 /// writes and fsyncs through the SQLite VFS.
242 pub checkpoint_us: u64,
243 /// One when this call ran a checkpoint pragma or swallowed its busy
244 /// error, else zero. Counters rather than flags, so the round ledger
245 /// sums them across cells like every other field here. A Queue soak
246 /// showed 14% of checkpoint rounds repeating on the next round with only
247 /// the sealing frame captured, and `checkpoint_us` alone could not say
248 /// whether the backfill was short, the pragma was busy, or the sealing
249 /// write failed to restart the WAL.
250 pub checkpoint_runs: u64,
251 /// The frames the WAL held when the pragma ran and the frames it had
252 /// backfilled when it returned: `PRAGMA wal_checkpoint`'s second and
253 /// third columns. Equal for a complete backfill; a shortfall names a
254 /// reader that pinned the WAL.
255 pub checkpoint_wal_frames: u64,
256 pub checkpoint_backfilled: u64,
257 /// One when the pragma reported a lock it could not take (its first
258 /// column), and one when the checkpoint path failed with `SQLITE_BUSY`
259 /// and the sync swallowed the error.
260 pub checkpoint_busy: u64,
261 pub checkpoint_busy_errors: u64,
262 /// One when the WAL header changed across the sealing write, so the
263 /// logical WAL restarted at its header.
264 pub checkpoint_restarts: u64,
265}
266
267pub struct Db {
268 host: crate::LtxHost,
269 path: PathBuf,
270 meta_path: PathBuf,
271 /// Main connection: writes, PRAGMAs, checkpoints, page-size reads.
272 conn: Connection,
273 /// Dedicated connection that holds the long-running read transaction.
274 ///
275 /// Go's `db.db` is a `*sql.DB` **connection pool**: the read lock (`db.rtx`)
276 /// lives on one pooled connection while every other `db.db.Exec` grabs a
277 /// *different* connection from the pool. A single `rusqlite::Connection`
278 /// cannot do that — an `INSERT` issued on the same connection that holds the
279 /// read transaction would be buffered in that transaction and not flushed to
280 /// the WAL (it would not write a fresh WAL page after a TRUNCATE checkpoint).
281 /// So the read lock gets its own connection, mirroring the pool's separation.
282 rtx_conn: Connection,
283 page_size: u32,
284
285 /// `true` while the long-running read transaction is open (db.go:70 `rtx`).
286 /// We track a flag rather than holding a borrowing `rusqlite::Transaction`.
287 read_lock_held: bool,
288
289 /// The last `sync` call's per-phase wall time. Telemetry only: the
290 /// closed-book capture ledger reads it; nothing branches on it.
291 last_sync_timing: SyncTiming,
292
293 // ── Tunables (db.go:131-197) ────────────────────────────────────────────
294 /// PASSIVE checkpoint threshold, in pages (db.go:34 default 1000).
295 pub min_checkpoint_page_n: u32,
296 /// TRUNCATE checkpoint threshold, in pages; 0 disables (db.go:35 default).
297 pub truncate_page_n: u32,
298 /// Time-based PASSIVE checkpoint interval; 0 disables (db.go:32 default 60s).
299 pub checkpoint_interval: Duration,
300 /// Busy timeout for SQLite locks (db.go:33 default 1s).
301 pub busy_timeout: Duration,
302
303 // ── Anti-feedback-loop bookkeeping (issues #896/#927/#997) ──────────────
304 /// True once data has synced since the last checkpoint (#896, db.go:80).
305 synced_since_checkpoint: bool,
306 /// True if the last sync reached the exact WAL EOF (#927, db.go:88).
307 synced_to_wal_end: bool,
308 /// Logical end of WAL content after the last sync = `WALOffset + WALSize`
309 /// from the last LTX (#997, db.go:96). Used for checkpoint thresholds
310 /// instead of file size (stale post-checkpoint frames inflate file size).
311 last_synced_wal_offset: i64,
312 /// The database's page count as the last capture saw it, for the
313 /// truncate guard: a second stat per sync would break the syscall
314 /// ledger, and the capture already read the size.
315 last_db_pages: u32,
316 /// Logical WAL offset through which the last checkpoint backfilled the
317 /// database, in the current WAL's coordinates; `WAL_HEADER_SIZE` after
318 /// a restart and 0 before any checkpoint. The passive threshold counts
319 /// frames appended past this point. The port compared the whole logical
320 /// size, which re-fired the checkpoint on every sync after a checkpoint
321 /// whose sealing write could not restart the WAL: the backfilled frames
322 /// kept counting, so a Queue owner paid a writer barrier, a sealing
323 /// write, and a fresh LTX per round until a restart succeeded.
324 checkpointed_wal_offset: i64,
325 /// The schema version `ensure_control_tables` last verified. The
326 /// self-heal exists for a swept `sqlite_schema`, and any sweep bumps
327 /// SQLite's schema version, so an unchanged version proves the tables
328 /// still stand without re-running DDL through the parser every capture
329 /// (~0.8 ms per sync in the 2026-08-25 closed-book ledger).
330 verified_schema_version: Option<i64>,
331 /// The header fields of the last L0 this instance wrote, keyed by its
332 /// TXID. `verify` needs exactly these to place the next incremental
333 /// read; re-reading the whole L0 file to parse its header cost more
334 /// than the header is long. A miss (restore, compaction, reopen)
335 /// falls back to the file.
336 last_l0_header: Option<(TXID, LastL0Header)>,
337
338 /// Cached L0 position; `None` = invalid (db.go:106-109).
339 pos_cache: Option<Pos>,
340 /// The L0 level directory exists: created on the first cut (or after a
341 /// `NotFound` on a later one), not probed with `mkdir` on every sync.
342 l0_dir_ready: bool,
343 /// The WAL, opened once. Every sync used to open it three times and stat
344 /// it five; each was a path walk on a directory the node fsyncs thousands
345 /// of times a second. See [`Db::with_wal_file`].
346 wal_file: Option<crate::HostFile>,
347 /// Last L0 `FileInfo` (db.go:99-102; only L0 is tracked in the one-shot).
348 max_l0_file_info: Option<ltx::FileInfo>,
349}
350
351/// DDL for the replication control tables managed inside each database:
352/// `_litestream_seq` forces WAL writes when empty; `_litestream_lock` forces
353/// a write lock during sync (db.go:857-864). The text is byte-visible:
354/// `sqlite_schema` stores it verbatim in a replicated page, so it must stay
355/// character-identical to litestream's, and one copy serves every creation
356/// site.
357const CONTROL_TABLES_DDL: &str =
358 "CREATE TABLE IF NOT EXISTS _litestream_seq (id INTEGER PRIMARY KEY, seq INTEGER);\
359 CREATE TABLE IF NOT EXISTS _litestream_lock (id INTEGER);";
360
361/// True for exactly the two control tables above, compared without case the
362/// way SQLite compares identifiers. Application-facing paths (deleteAll
363/// sweeps, the SQL authorizer) must exempt these names, so the predicate
364/// lives here with the tables. Exact names, not a `_litestream_` prefix:
365/// ltx is a port of a pinned litestream, and workerd reserves only `_cf_`,
366/// so any other name stays reachable by application SQL.
367pub fn is_control_table(name: &str) -> bool {
368 name.eq_ignore_ascii_case("_litestream_seq") || name.eq_ignore_ascii_case("_litestream_lock")
369}
370
371impl Db {
372 /// Default minimum-checkpoint page count (`DefaultMinCheckpointPageN`,
373 /// db.go:34).
374 pub const DEFAULT_MIN_CHECKPOINT_PAGE_N: u32 = 1000;
375 /// Default truncate page count (`DefaultTruncatePageN`, db.go:35).
376 pub const DEFAULT_TRUNCATE_PAGE_N: u32 = 121_359;
377
378 /// Default checkpoint interval (`DefaultCheckpointInterval`, db.go:32).
379 pub const DEFAULT_CHECKPOINT_INTERVAL: Duration = Duration::from_secs(60);
380 /// Default busy timeout (`DefaultBusyTimeout`, db.go:33).
381 pub const DEFAULT_BUSY_TIMEOUT: Duration = Duration::from_secs(1);
382
383 /// Opens and initializes the database with litestream's WAL-mode setup and
384 /// acquires the long-running read lock.
385 ///
386 /// The host must complete this call successfully before opening any
387 /// other SQLite connection that can write to this database. After a
388 /// crash, an earlier write can hide a torn WAL header, so resumed capture
389 /// can skip new commits when existing LTX files retain the previous
390 /// capture position. An incomplete recovery checkpoint returns an error,
391 /// including when another connection keeps the checkpoint busy.
392 ///
393 /// Ported from `DB.init` (db.go:795-911) — the connection-setup half plus the
394 /// read-lock acquire and `ensureWALExists`.
395 pub fn open(path: impl AsRef<Path>) -> Result<Db> {
396 Self::open_with_host(path, crate::LtxHost::default())
397 }
398
399 /// Opens the database with an injected clock and executor host.
400 ///
401 /// This call must succeed before another writer opens the database.
402 /// See [`Db::open`] for the startup ordering requirement.
403 pub fn open_with_host(path: impl AsRef<Path>, host: crate::LtxHost) -> Result<Db> {
404 Self::open_with_host_and_optional_vfs(path, host, None)
405 }
406
407 /// Opens both managed connections through a named SQLite VFS. Used by the
408 /// fault-injection VFS in tests and by paged restore's fault-in VFS.
409 ///
410 /// This call must succeed before another writer opens the database.
411 /// See [`Db::open`] for the startup ordering requirement.
412 pub fn open_with_host_and_vfs(
413 path: impl AsRef<Path>,
414 host: crate::LtxHost,
415 vfs: &str,
416 ) -> Result<Db> {
417 Self::open_with_host_and_optional_vfs(path, host, Some(vfs))
418 }
419
420 fn open_with_host_and_optional_vfs(
421 path: impl AsRef<Path>,
422 host: crate::LtxHost,
423 vfs: Option<&str>,
424 ) -> Result<Db> {
425 let path = path.as_ref().to_path_buf();
426 let meta_path = Self::meta_path_for(&path);
427
428 let open = |path: &Path| match vfs {
429 Some(vfs) => Connection::open_with_flags_and_vfs(path, OpenFlags::default(), vfs),
430 None => Connection::open(path),
431 };
432 let conn = open(&path).map_err(sql_err)?;
433 disable_lookaside(&conn)?;
434 // Cap the page cache at 64 KiB; SQLite's default (-2000) lets each
435 // connection grow to 2 MiB, and every resident cell owns this
436 // connection, so the default repeats a dead-weight cost at fleet
437 // density. The connection only runs PRAGMAs, the sealing write to
438 // the control tables, and checkpoints, and a checkpoint streams WAL
439 // frames into the database without revisiting pages, so a larger
440 // cache buys no reuse. 16 default-size pages still cover the
441 // control tables and their schema pages.
442 conn.pragma_update(None, "cache_size", -64)
443 .map_err(sql_err)?;
444
445 // DSN pragmas: busy_timeout + wal_autocheckpoint(0) (db.go:818).
446 // autocheckpoint MUST be 0 because litestream owns checkpointing.
447 // Per-connection, not per-file: the cell's own writer
448 // connection keeps SQLite's default 1000-page autocheckpoint, which
449 // is safe because this connection's long-running read transaction
450 // pins a WAL read mark, so a PASSIVE checkpoint elsewhere can
451 // backfill but never reset or truncate the WAL under the reader.
452 conn.busy_timeout(Self::DEFAULT_BUSY_TIMEOUT)
453 .map_err(sql_err)?;
454 conn.pragma_update(None, "wal_autocheckpoint", 0)
455 .map_err(sql_err)?;
456
457 // Enable WAL; SQLite returns the new mode on success (db.go:849-853).
458 let mode: String = conn
459 .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0))
460 .map_err(sql_err)?;
461 if mode != "wal" {
462 return Err(Error::Other(
463 format!("enable wal failed, mode={mode:?}").into(),
464 ));
465 }
466
467 // Dedicated read-lock connection (mirrors a second pooled connection).
468 let rtx_conn = open(&path).map_err(sql_err)?;
469 disable_lookaside(&rtx_conn)?;
470 // This connection runs one tiny read to take the read lock and then
471 // idles for the whole residency, so SQLite's default page-cache limit
472 // (-2000 = up to 2 MiB) is dead weight repeated per resident cell.
473 // Cap it at a few pages; no user query or checkpoint runs here, so a
474 // smaller cache cannot slow either path.
475 rtx_conn
476 .pragma_update(None, "cache_size", -16)
477 .map_err(sql_err)?;
478 rtx_conn
479 .busy_timeout(Self::DEFAULT_BUSY_TIMEOUT)
480 .map_err(sql_err)?;
481
482 let mut db = Db {
483 host,
484 path,
485 meta_path,
486 conn,
487 rtx_conn,
488 page_size: 0,
489 read_lock_held: false,
490 last_sync_timing: SyncTiming::default(),
491 min_checkpoint_page_n: Self::DEFAULT_MIN_CHECKPOINT_PAGE_N,
492 truncate_page_n: Self::DEFAULT_TRUNCATE_PAGE_N,
493 checkpoint_interval: Self::DEFAULT_CHECKPOINT_INTERVAL,
494 busy_timeout: Self::DEFAULT_BUSY_TIMEOUT,
495 synced_since_checkpoint: false,
496 synced_to_wal_end: false,
497 last_synced_wal_offset: 0,
498 last_db_pages: 0,
499 checkpointed_wal_offset: 0,
500 verified_schema_version: None,
501 last_l0_header: None,
502 pos_cache: None,
503 l0_dir_ready: false,
504 wal_file: None,
505 max_l0_file_info: None,
506 };
507
508 // Recover before any DDL can rewrite a torn header with reused salts,
509 // and before our long-lived reader can block the checkpoint.
510 db.recover_wal_header()?;
511 db.conn.execute_batch(CONTROL_TABLES_DDL).map_err(sql_err)?;
512
513 // Start the long-running read transaction (db.go:867-871).
514 db.acquire_read_lock()?;
515
516 // Read page size (db.go:874-878).
517 let page_size: i64 = db
518 .conn
519 .query_row("PRAGMA page_size", [], |r| r.get(0))
520 .map_err(sql_err)?;
521 if page_size <= 0 {
522 return Err(Error::Other(
523 format!("invalid db page size: {page_size}").into(),
524 ));
525 }
526 // Validated > 0 above; SQLite page sizes are <= 65536.
527 db.page_size = page_size as u32;
528
529 // Ensure the meta directory exists (db.go:880-883).
530 db.host.create_dir_all(&db.meta_path)?;
531
532 // Clear crash-leftover temp files (db.go:576).
533 remove_tmp_files(&db.host, &db.meta_path)?;
534
535 // Ensure the WAL has at least one frame (db.go:886-888).
536 db.ensure_wal_exists()?;
537
538 Ok(db)
539 }
540
541 // ── Paths ──────────────────────────────────────────────────────────────
542
543 /// Computes the litestream meta-directory path (`.<file>-litestream`) for a
544 /// database file path, without opening it. Public so a host can locate (e.g.
545 /// to wipe, during a hard recovery) the meta dir of a database it no longer
546 /// has an open [`Db`] handle for. Mirrors `DB.MetaPath` (db.go:292) at the
547 /// path level.
548 pub fn meta_path_for_path(path: impl AsRef<Path>) -> PathBuf {
549 Self::meta_path_for(path.as_ref())
550 }
551
552 fn meta_path_for(path: &Path) -> PathBuf {
553 // Go: filepath.Join(dir, "."+file+MetaDirSuffix) (db.go:206).
554 let dir = path.parent();
555 let file = path.file_name().map(|s| s.to_owned()).unwrap_or_default();
556 let mut name = std::ffi::OsString::from(".");
557 name.push(&file);
558 name.push(META_DIR_SUFFIX);
559 match dir {
560 Some(d) if !d.as_os_str().is_empty() => d.join(name),
561 _ => PathBuf::from(name),
562 }
563 }
564
565 /// The database file path. Ported from `DB.Path` (db.go:275).
566 pub fn path(&self) -> &Path {
567 &self.path
568 }
569
570 /// Path to the litestream meta directory (`.<file>-litestream`).
571 /// Ported from `DB.MetaPath` (db.go:292).
572 pub fn meta_path(&self) -> &Path {
573 &self.meta_path
574 }
575
576 /// Path to SQLite's WAL sidecar file (`<db>-wal`).
577 /// Ported from `DB.WALPath` (db.go:287-289).
578 pub fn wal_path(&self) -> PathBuf {
579 let mut s = self.path.clone().into_os_string();
580 s.push("-wal");
581 PathBuf::from(s)
582 }
583
584 /// Root LTX directory (`<meta>/ltx`). Ported from `DB.LTXDir` (db.go:302).
585 fn ltx_dir(&self) -> String {
586 crate::ltx_dir(&self.meta_path.to_string_lossy())
587 }
588
589 /// LTX level sub-directory. Ported from `DB.LTXLevelDir` (db.go:332).
590 fn ltx_level_dir(&self, level: u32) -> String {
591 ltx_level_dir(&self.meta_path.to_string_lossy(), level)
592 }
593
594 /// Local path of a single LTX file. Ported from `DB.LTXPath` (db.go:338).
595 ///
596 /// `pub` so the [`crate::replica::Replica`] can read the local L0 LTX files
597 /// the capture loop wrote and upload them (the Go exported `DB.LTXPath`,
598 /// used by `Replica.uploadLTXFile`, replica.go:183).
599 pub fn ltx_path(&self, level: u32, min_txid: TXID, max_txid: TXID) -> String {
600 ltx_file_path(&self.meta_path.to_string_lossy(), level, min_txid, max_txid)
601 }
602
603 /// Reads one local LTX file through the host filesystem.
604 pub fn read_ltx_file(&self, level: u32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> {
605 let path = self.ltx_path(level, min_txid, max_txid);
606 Ok(self.host.read(Path::new(&path))?)
607 }
608
609 /// The SQLite page size, in bytes. Ported from `DB.PageSize` (db.go:445).
610 pub fn page_size(&self) -> u32 {
611 self.page_size
612 }
613
614 // ── Read-lock takeover (checkpoint prevention) ─────────────────────────
615
616 /// Begins a long-running read transaction to prevent external checkpoints.
617 ///
618 /// Ported from `acquireReadLock` (db.go:956-976): `BEGIN` then `SELECT
619 /// COUNT(1) FROM _litestream_seq` to obtain the SHARED read lock. Held with
620 /// raw SQL + a flag instead of a borrowing `rusqlite::Transaction` (see
621 /// module docs). Idempotent: a no-op if already held.
622 fn acquire_read_lock(&mut self) -> Result<()> {
623 if self.read_lock_held {
624 return Ok(());
625 }
626 self.rtx_conn
627 .prepare_cached("BEGIN")
628 .and_then(|mut statement| statement.execute([]))
629 .map_err(sql_err)?;
630 // Execute a read query to obtain the read lock. On failure, roll back.
631 if let Err(e) = self
632 .rtx_conn
633 .query_row("SELECT COUNT(1) FROM _litestream_seq", [], |r| {
634 r.get::<_, i64>(0)
635 })
636 {
637 let _ = self.rtx_conn.execute_batch("ROLLBACK");
638 return Err(sql_err(e));
639 }
640 self.read_lock_held = true;
641 Ok(())
642 }
643
644 /// Rolls back the long-running read transaction.
645 ///
646 /// Ported from `releaseReadLock` (db.go:979-992). Uses the `rollback` helper
647 /// semantics: a "no transaction is active" / "already rolled back" error is
648 /// swallowed (issue #934) — a double release must return
649 /// `Ok(())`. The `read_lock_held` flag is cleared regardless.
650 fn release_read_lock(&mut self) -> Result<()> {
651 if !self.read_lock_held {
652 return Ok(());
653 }
654 self.read_lock_held = false;
655 rollback(&self.rtx_conn)
656 }
657
658 // ── WAL bootstrap ──────────────────────────────────────────────────────
659
660 /// Recreates the control tables if they are missing. They are created at
661 /// open, but an application-level sweep of `sqlite_schema` can drop them
662 /// (they do not carry the protected `_cf_` prefix); `CREATE TABLE IF NOT
663 /// EXISTS` on an existing table is a no-op, so this is safe to run on
664 /// every capture.
665 fn ensure_control_tables(&mut self) -> Result<()> {
666 // A swept control table is a schema change, and every schema change
667 // bumps SQLite's schema version — so an unchanged version proves
668 // the last verification still holds and the DDL (a full parse and
669 // execute per statement) can be skipped on the hot capture path.
670 // Through the statement cache: this guard runs on every sync, and a
671 // fresh `PRAGMA` per sync was one SQL compilation per capture on the
672 // fleet profile.
673 let version: i64 = self
674 .conn
675 .prepare_cached("PRAGMA schema_version")
676 .and_then(|mut statement| statement.query_row([], |row| row.get(0)))
677 .map_err(sql_err)?;
678 if self.verified_schema_version == Some(version) {
679 return Ok(());
680 }
681 self.conn
682 .execute_batch(CONTROL_TABLES_DDL)
683 .map_err(sql_err)?;
684 let verified: i64 = self
685 .conn
686 .prepare_cached("PRAGMA schema_version")
687 .and_then(|mut statement| statement.query_row([], |row| row.get(0)))
688 .map_err(sql_err)?;
689 self.verified_schema_version = Some(verified);
690 Ok(())
691 }
692
693 /// Runs `op` on the held WAL handle, opening it on first use. A WAL that
694 /// SQLite recreated, or that a truncation shortened under a read, surfaces
695 /// as `NotFound` or `UnexpectedEof`; the handle is dropped and `op` runs
696 /// once more on a fresh open, so a stale handle costs one retry, never a
697 /// wrong answer. Any other error also drops the handle.
698 fn with_wal_file<T>(
699 &mut self,
700 op: impl Fn(&mut crate::HostFile) -> std::io::Result<T>,
701 ) -> std::io::Result<T> {
702 let mut attempt = 0;
703 loop {
704 if self.wal_file.is_none() {
705 self.wal_file = Some(self.host.open(&self.wal_path())?);
706 }
707 let file = self.wal_file.as_mut().expect("opened above");
708 match op(file) {
709 Ok(value) => return Ok(value),
710 Err(error) => {
711 self.wal_file = None;
712 let retry = attempt == 0
713 && matches!(
714 error.kind(),
715 std::io::ErrorKind::NotFound | std::io::ErrorKind::UnexpectedEof
716 );
717 if !retry {
718 return Err(error);
719 }
720 attempt += 1;
721 }
722 }
723 }
724 }
725
726 /// The 32-byte WAL header through the held handle (`readWALHeader`,
727 /// litestream.go:138-148: an error if the file is missing or short).
728 fn wal_header_bytes(&mut self) -> Result<[u8; WAL_HEADER_SIZE]> {
729 let bytes = self.with_wal_file(|file| file.read_exact_at(0, WAL_HEADER_SIZE))?;
730 Ok(bytes
731 .try_into()
732 .expect("the exact read has the header size"))
733 }
734
735 /// `n` bytes at `offset` of the WAL through the held handle
736 /// (`readWALFileAt`, litestream.go:152-166: a short read is an error).
737 fn wal_bytes_at(&mut self, offset: i64, n: i64) -> Result<Vec<u8>> {
738 Ok(self.with_wal_file(|file| file.read_exact_at(offset as u64, n as usize))?)
739 }
740
741 /// Resets a WAL with an invalid header checksum before initialization writes.
742 fn recover_wal_header(&mut self) -> Result<()> {
743 let header = match self.wal_header_bytes() {
744 Ok(header) => header,
745 // The later ensure_wal_exists call initializes missing or
746 // short WALs. Other I/O errors must remain visible to the caller.
747 Err(Error::Io(error))
748 if matches!(
749 error.kind(),
750 std::io::ErrorKind::NotFound | std::io::ErrorKind::UnexpectedEof
751 ) =>
752 {
753 return Ok(())
754 }
755 Err(error) => return Err(error),
756 };
757 match WalReader::new(&header) {
758 Ok(_) => return Ok(()),
759 Err(WalError::Eof) => {}
760 // SQLite rejects invalid magic before copying the salts or nCkpt.
761 // With nCkpt still zero, its next write chooses fresh salts, so
762 // verify detects the new generation without this checkpoint.
763 // Capture still rejects the invalid header until that write.
764 Err(WalError::InvalidMagic(_)) => return Ok(()),
765 // SQLite normally rejects an unsupported version while enabling
766 // WAL; keep any remaining header-reader errors visible.
767 Err(error) => return Err(error.into()),
768 }
769
770 // The host must open capture before other SQLite writers. After a
771 // crash, an earlier write can reuse salts and hide the torn header.
772 // SQLite rejects the torn WAL contents but retains the header's
773 // salts and checkpoint sequence. A bootstrap write alone can reuse
774 // those salts. The stale tail then lets an existing LTX cursor skip
775 // new commits. SQLite's TRUNCATE checkpoint changes the salts and
776 // removes that tail even if this process stops before its first
777 // capture. No volatile recovery flag can protect that gap.
778 // If control-table DDL is a no-op, ensure_wal_exists supplies the
779 // first write in the new generation.
780 // Only open checks the header, so live syncs keep their cheap check.
781 let checkpoint = self.run_checkpoint_pragma(CheckpointMode::Truncate)?;
782 if checkpoint.busy != 0 {
783 // A busy checkpoint leaves recovery incomplete, so opening must fail.
784 return Err(sql_err(rusqlite::Error::SqliteFailure(
785 ffi::Error::new(ffi::SQLITE_BUSY),
786 Some("torn WAL recovery checkpoint is busy".to_string()),
787 )));
788 }
789 Ok(())
790 }
791
792 /// Ensures the real WAL exists and has a header.
793 ///
794 /// Ported from `ensureWALExists` (db.go:1199-1209): exit early if the WAL
795 /// header is present; otherwise force a write to `_litestream_seq`.
796 fn ensure_wal_exists(&mut self) -> Result<()> {
797 if self.wal_file_size()? >= WAL_HEADER_SIZE as i64 {
798 return Ok(());
799 }
800 self.conn
801 .execute_batch(
802 "INSERT INTO _litestream_seq (id, seq) VALUES (1, 1) \
803 ON CONFLICT (id) DO UPDATE SET seq = seq + 1",
804 )
805 .map_err(sql_err)?;
806 Ok(())
807 }
808
809 /// Size of the WAL file in bytes, 0 if absent. Ported from `walFileSize`
810 /// (db.go:1183-1191).
811 fn wal_file_size(&mut self) -> Result<i64> {
812 match self.with_wal_file(|file| file.file_len()) {
813 Ok(len) => Ok(len as i64),
814 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
815 Err(e) => Err(e.into()),
816 }
817 }
818
819 /// The size of the main database file in bytes, 0 if absent.
820 fn db_file_size(&self) -> Result<i64> {
821 match self.host.metadata(&self.path) {
822 Ok(md) => Ok(md.len as i64),
823 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
824 Err(e) => Err(e.into()),
825 }
826 }
827
828 // ── Position ───────────────────────────────────────────────────────────
829
830 /// The highest `(min,max)` TXID pair in the L0 directory, `(0,0)` if none.
831 /// Ported from `DB.MaxLTX` (db.go:363-380).
832 fn max_ltx(&self) -> Result<(TXID, TXID)> {
833 let dir = self.ltx_level_dir(0);
834 let entries = match self.host.read_dir(Path::new(&dir)) {
835 Ok(e) => e,
836 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((TXID(0), TXID(0))),
837 Err(e) => return Err(e.into()),
838 };
839 let mut min_txid = TXID(0);
840 let mut max_txid = TXID(0);
841 for ent in entries {
842 let name = ent.file_name;
843 let name = name.to_string_lossy();
844 if let Ok((mn, mx)) = ltx::parse_filename(&name) {
845 if mx > max_txid {
846 min_txid = mn;
847 max_txid = mx;
848 }
849 }
850 }
851 Ok((min_txid, max_txid))
852 }
853
854 /// The current replication position (cached; recomputed from the max L0 file).
855 ///
856 /// Ported from `DB.Pos` (db.go:392-425). Wraps fs/decode failures in
857 /// `LTXError` (db.go:412,418).
858 pub fn pos(&mut self) -> Result<Pos> {
859 if let Some(p) = self.pos_cache {
860 return Ok(p);
861 }
862
863 let (min_txid, max_txid) = self.max_ltx()?;
864 if min_txid == TXID(0) {
865 return Ok(Pos::ZERO); // no replication yet
866 }
867
868 let ltx_path = self.ltx_path(0, min_txid, max_txid);
869 let bytes = match self.host.read(Path::new(&ltx_path)) {
870 Ok(b) => b,
871 Err(e) => {
872 return Err(Error::Ltx(Box::new(new_ltx_error(
873 "open",
874 &ltx_path,
875 0,
876 min_txid.0,
877 max_txid.0,
878 e.into(),
879 ))));
880 }
881 };
882
883 let decoded = match ltx::decode_file(&bytes) {
884 Ok(d) => d,
885 Err(_e) => {
886 // Decode/verify failure indicates corruption (db.go:417-419).
887 return Err(Error::Ltx(Box::new(new_ltx_error(
888 "verify",
889 &ltx_path,
890 0,
891 min_txid.0,
892 max_txid.0,
893 Error::LTXCorrupted,
894 ))));
895 }
896 };
897
898 let pos = Pos::new(decoded.header.max_txid, decoded.trailer.post_apply_checksum);
899 self.pos_cache = Some(pos);
900 Ok(pos)
901 }
902
903 /// Clears the cached position so the next `pos()` recomputes from disk.
904 /// Ported from `invalidatePosCache` (db.go:430-434).
905 fn invalidate_pos_cache(&mut self) {
906 self.pos_cache = None;
907 }
908
909 /// Removes local LTX files, forcing a fresh snapshot on the next sync.
910 /// Ported from `DB.ResetLocalState` (db.go:309-328).
911 pub fn reset_local_state(&mut self) -> Result<()> {
912 match self.host.remove_dir_all(Path::new(&self.ltx_dir())) {
913 Ok(()) => {}
914 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
915 Err(e) => return Err(e.into()),
916 }
917 self.max_l0_file_info = None;
918 self.invalidate_pos_cache();
919 Ok(())
920 }
921
922 /// Clears the local L0 directory and seeds it with a single baseline L0 LTX
923 /// file (`data` for the `min_txid`..`max_txid` range), atomically. The next
924 /// [`Db::sync`] then sees the baseline does not match the real WAL and writes
925 /// a fresh snapshot at the current database state.
926 ///
927 /// This is the file-writing tail of `checkDatabaseBehindReplica`
928 /// (db.go:1241-1293): clear L0, invalidate the pos cache, write the fetched
929 /// remote L0 file to its local path via a temp-file + fsync + rename, then
930 /// invalidate the cache again. The *detection* half (compare DB pos vs replica
931 /// pos and fetch the bytes) lives on [`crate::replica::Replica`] because the
932 /// synchronous `Db` has no `ReplicaClient` handle of its own. Used by
933 /// [`crate::replica::Replica::check_database_behind_replica`] (issue #781).
934 pub fn seed_l0_baseline(&mut self, min_txid: TXID, max_txid: TXID, data: &[u8]) -> Result<()> {
935 // Clear local L0 files (db.go:1241-1249).
936 let l0_dir = self.ltx_level_dir(0);
937 match self.host.remove_dir_all(Path::new(&l0_dir)) {
938 Ok(()) => {}
939 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
940 Err(e) => return Err(e.into()),
941 }
942 self.max_l0_file_info = None;
943 self.invalidate_pos_cache();
944 self.host.create_dir_all(Path::new(&l0_dir))?;
945
946 // Write the baseline file atomically (db.go:1260-1286).
947 let local_path = self.ltx_path(0, min_txid, max_txid);
948 let tmp_path = format!("{local_path}.tmp");
949 let _ = write_file_atomic(&self.host, &tmp_path, &local_path, data)?;
950 self.last_l0_header = None;
951 self.invalidate_pos_cache();
952 Ok(())
953 }
954
955 /// Continues a chain at `txid`, whose database has `commit` pages: the
956 /// next sync captures a delta at `txid + 1`, not the whole database. A
957 /// zero-page L0 at `txid` is the local baseline verify reads back; its
958 /// WAL fields name the start of the WAL as it stands, so the first
959 /// capture begins at the WAL header. The WAL must exist: an activation
960 /// writes the control tables before this runs. Returns the baseline's
961 /// bytes: the caller uploads the same object as the epoch's marker, so
962 /// the epoch is never empty (CelldPersistencePaged.tla, `BreakNoMarker`).
963 /// A whole-database opener is what a paged cell cannot afford: on the
964 /// 2 GB fleet whale it took minutes through the fault path, the
965 /// durability gate timed out, and every re-activation started it over.
966 pub fn seed_continuation(&mut self, txid: TXID, commit: u32) -> Result<Vec<u8>> {
967 let wal = self.wal_header_bytes()?;
968 let header = ltx::Header {
969 version: ltx::VERSION,
970 flags: ltx::HEADER_FLAG_NO_CHECKSUM,
971 page_size: self.page_size,
972 commit,
973 min_txid: txid,
974 max_txid: txid,
975 timestamp: self.host.now_unix_millis(),
976 pre_apply_checksum: 0,
977 wal_offset: WAL_HEADER_SIZE as i64,
978 wal_size: 0,
979 wal_salt1: be_u32(&wal[16..]),
980 wal_salt2: be_u32(&wal[20..]),
981 node_id: 0,
982 };
983 let baseline = ltx::encode_file(&header, &[], 0)?;
984 self.seed_l0_baseline(txid, txid, &baseline)?;
985 Ok(baseline)
986 }
987
988 // ── Capture loop ───────────────────────────────────────────────────────
989
990 /// Where one `sync` call's wall time went, phase by phase. The phases
991 /// sum to the call's wall time minus only dispatch overhead, so a
992 /// capture ledger built on this closes its books. `checkpoint_us` is
993 /// SQLite's own checkpoint (its writes and fsyncs run through the
994 /// SQLite VFS, invisible to the LTX host filesystem), measured here
995 /// because no other layer can see it.
996 pub fn last_sync_timing(&self) -> SyncTiming {
997 self.last_sync_timing
998 }
999
1000 /// Copies pending data from the WAL into the next L0 LTX file and applies
1001 /// the checkpoint policy.
1002 ///
1003 /// Ported from `DB.Sync` (db.go:994-1056). The public entry point of the
1004 /// capture loop. This function is synchronous as described in the module docs.
1005 pub fn sync(&mut self) -> Result<()> {
1006 self.sync_with_verify_hook(None)
1007 }
1008
1009 /// `sync` with an optional hook that runs between `verify` and the
1010 /// capture read — the window a concurrent WAL change would land in.
1011 /// Test-only through `internal::sync_with_verify_hook`; production
1012 /// passes `None`.
1013 fn sync_with_verify_hook(&mut self, hook: Option<Box<dyn FnOnce()>>) -> Result<()> {
1014 self.last_sync_timing = SyncTiming::default();
1015 let phase = crate::host::telemetry_us();
1016 // Self-heal: recreate the control tables if something swept them out
1017 // of `sqlite_schema` from under the replicator — without them every
1018 // capture fails until the database is reopened. A no-op when the
1019 // tables exist (no schema change, no WAL write).
1020 self.ensure_control_tables()?;
1021 let schema_done = crate::host::telemetry_us();
1022 self.last_sync_timing.schema_check_us = schema_done.saturating_sub(phase);
1023
1024 // Ensure the WAL has at least one frame (db.go:1017-1020).
1025 self.ensure_wal_exists()?;
1026 self.last_sync_timing.wal_exists_us =
1027 crate::host::telemetry_us().saturating_sub(schema_done);
1028 self.last_sync_timing.prepare_us = crate::host::telemetry_us().saturating_sub(phase);
1029
1030 let (orig_wal_size, new_wal_size, synced) = self.verify_and_sync(hook)?;
1031
1032 // Track that data was synced for time-based checkpoint decisions.
1033 if synced {
1034 self.synced_since_checkpoint = true;
1035 }
1036
1037 let phase = crate::host::telemetry_us();
1038 self.checkpoint_if_needed(orig_wal_size, new_wal_size)?;
1039 self.last_sync_timing.checkpoint_us = crate::host::telemetry_us().saturating_sub(phase);
1040
1041 // Recompute the cached position (kept for parity with db.go:1037-1041).
1042 let _ = self.pos()?;
1043
1044 Ok(())
1045 }
1046
1047 /// Verifies the last sync against the current WAL, then syncs.
1048 ///
1049 /// Ported from `DB.verifyAndSync` (db.go:1058-1090). Returns
1050 /// `(orig_wal_size, new_wal_size, synced)` where the sizes are the **logical**
1051 /// WAL offset (`WALOffset+WALSize` of the last LTX), not file size (#997).
1052 fn verify_and_sync(&mut self, between: Option<Box<dyn FnOnce()>>) -> Result<(i64, i64, bool)> {
1053 // Use the last synced WAL offset as the logical size for checkpoint
1054 // decisions; on the first sync fall back to file size (db.go:1062-1069).
1055 let mut orig_wal_size = self.last_synced_wal_offset;
1056 if orig_wal_size == 0 {
1057 orig_wal_size = self.wal_file_size()?;
1058 }
1059
1060 let phase = crate::host::telemetry_us();
1061 let info = self.verify()?;
1062 self.last_sync_timing.verify_us = crate::host::telemetry_us().saturating_sub(phase);
1063 if let Some(between) = between {
1064 between();
1065 }
1066 let phase = crate::host::telemetry_us();
1067 let synced = self.sync_inner(info)?;
1068 self.last_sync_timing.encode_write_us = crate::host::telemetry_us()
1069 .saturating_sub(phase)
1070 .saturating_sub(self.last_sync_timing.fsync_us);
1071
1072 let new_wal_size = self.last_synced_wal_offset;
1073 Ok((orig_wal_size, new_wal_size, synced))
1074 }
1075
1076 /// Ensures the LTX state matches where it left off from the real WAL.
1077 ///
1078 /// Ported branch-for-branch from `DB.verify` (db.go:1296-1436).
1079 /// This is the snapshot-on-continuity-break brain — do not refactor for
1080 /// elegance on pass one.
1081 fn verify(&mut self) -> Result<SyncInfo> {
1082 let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64;
1083 let mut info = SyncInfo {
1084 snapshotting: true,
1085 ..Default::default()
1086 };
1087
1088 let pos = self.pos()?;
1089 if pos.txid == TXID(0) {
1090 info.offset = WAL_HEADER_SIZE as i64;
1091 return Ok(info); // first sync
1092 }
1093
1094 // Determine the last WAL offset we saved from: the header of the
1095 // last L0 (db.go:1311-1326). This instance wrote that header one
1096 // sync ago, so the cache answers without re-reading the file; a
1097 // key miss (restore, compaction, reopen) reads and parses as the
1098 // port always did.
1099 let cache_hit = matches!(&self.last_l0_header, Some((txid, _)) if *txid == pos.txid);
1100 let (hdr, ltx_bytes) = if cache_hit {
1101 let (_, cached) = self.last_l0_header.as_ref().expect("matched above");
1102 (cached.clone(), None)
1103 } else {
1104 let ltx_path = self.ltx_path(0, pos.txid, pos.txid);
1105 let ltx_bytes = match self.host.read(Path::new(&ltx_path)) {
1106 Ok(b) => b,
1107 Err(e) => {
1108 return Err(Error::Ltx(Box::new(new_ltx_error(
1109 "open",
1110 &ltx_path,
1111 0,
1112 pos.txid.0,
1113 pos.txid.0,
1114 e.into(),
1115 ))));
1116 }
1117 };
1118 let parsed = match ltx::Header::parse(&ltx_bytes) {
1119 Ok(h) => h,
1120 Err(_) => {
1121 return Err(Error::Ltx(Box::new(new_ltx_error(
1122 "decode",
1123 &ltx_path,
1124 0,
1125 pos.txid.0,
1126 pos.txid.0,
1127 Error::LTXCorrupted,
1128 ))));
1129 }
1130 };
1131 (
1132 LastL0Header {
1133 wal_offset: parsed.wal_offset,
1134 wal_size: parsed.wal_size,
1135 wal_salt1: parsed.wal_salt1,
1136 wal_salt2: parsed.wal_salt2,
1137 commit: parsed.commit,
1138 final_pgno: 0,
1139 final_page: Vec::new(),
1140 },
1141 Some(ltx_bytes),
1142 )
1143 };
1144 info.offset = hdr.wal_offset + hdr.wal_size;
1145 info.salt1 = hdr.wal_salt1;
1146 info.salt2 = hdr.wal_salt2;
1147 info.prev_commit = hdr.commit;
1148
1149 // If the LTX WAL offset exceeds the real WAL size, the WAL was truncated.
1150 let wal_size = self.wal_file_size()?;
1151 if info.offset > wal_size {
1152 // If we previously synced to the exact WAL end, this truncation is an
1153 // expected checkpoint: reset to the header and continue incrementally
1154 // rather than snapshotting (issue #927, db.go:1335-1355).
1155 if self.synced_to_wal_end {
1156 self.synced_to_wal_end = false;
1157
1158 let wal_hdr = self.wal_header_bytes()?;
1159 info.offset = WAL_HEADER_SIZE as i64;
1160 info.salt1 = be_u32(&wal_hdr[16..]);
1161 info.salt2 = be_u32(&wal_hdr[20..]);
1162 info.snapshotting = false;
1163 info.reason = String::new();
1164 return Ok(info);
1165 }
1166
1167 info.reason = "wal truncated by another process".to_string();
1168 return Ok(info);
1169 }
1170
1171 // Compare WAL headers; restart from the beginning of the WAL if different.
1172 let wal_hdr = self.wal_header_bytes()?;
1173 let salt1 = be_u32(&wal_hdr[16..]);
1174 let salt2 = be_u32(&wal_hdr[20..]);
1175 let salt_match = salt1 == hdr.wal_salt1 && salt2 == hdr.wal_salt2;
1176
1177 // Edge case: LTX represents the start of the WAL (WALOffset=32, WALSize=0).
1178 // Handle this before computing prev_wal_offset to avoid underflow
1179 // (32 - 4120 = -4088). See issue #900 (db.go:1375-1383).
1180 if info.offset == WAL_HEADER_SIZE as i64 {
1181 if salt_match {
1182 info.snapshotting = false;
1183 return Ok(info);
1184 }
1185 info.reason = "wal header salt reset, snapshotting".to_string();
1186 return Ok(info);
1187 }
1188
1189 // If the offset is at the start of the first page, we can't check the
1190 // previous page (db.go:1386-1399).
1191 let prev_wal_offset = info.offset - frame_size;
1192 if prev_wal_offset == WAL_HEADER_SIZE as i64 {
1193 if salt_match {
1194 info.snapshotting = false;
1195 return Ok(info);
1196 }
1197 info.reason = "wal header salt reset, snapshotting".to_string();
1198 return Ok(info);
1199 } else if prev_wal_offset < WAL_HEADER_SIZE as i64 {
1200 return Err(Error::Other(
1201 format!("prev WAL offset is less than the header size: {prev_wal_offset}").into(),
1202 ));
1203 }
1204
1205 // If we can't verify the last page is in the last LTX file, snapshot.
1206 let last_page_match = match &ltx_bytes {
1207 Some(bytes) => self.last_page_match(bytes, &hdr, prev_wal_offset, frame_size)?,
1208 None => self.last_page_match_cached(&hdr, prev_wal_offset, frame_size)?,
1209 };
1210 if !last_page_match {
1211 info.reason =
1212 "last page does not exist in last ltx file, wal overwritten by another process"
1213 .to_string();
1214 return Ok(info);
1215 }
1216
1217 // Salt changed (possible FULL/RESTART checkpoint). With a last-page match
1218 // we assume the WAL was not overwritten (db.go:1412-1431).
1219 if !salt_match {
1220 info.offset = WAL_HEADER_SIZE as i64;
1221 info.salt1 = salt1;
1222 info.salt2 = salt2;
1223
1224 let detected =
1225 self.detect_full_checkpoint(&[(salt1, salt2), (hdr.wal_salt1, hdr.wal_salt2)])?;
1226 if detected {
1227 info.reason = "full or restart checkpoint detected, snapshotting".to_string();
1228 } else {
1229 info.snapshotting = false;
1230 }
1231 return Ok(info);
1232 }
1233
1234 info.snapshotting = false;
1235 Ok(info)
1236 }
1237
1238 /// Checks whether the last page read in the WAL exists in the last LTX file.
1239 ///
1240 /// Ported from `DB.lastPageMatch` (db.go:1438-1475). Re-reads the last synced
1241 /// WAL frame and searches the last LTX file's pages for a matching
1242 /// `(pgno, data)` pair.
1243 fn last_page_match(
1244 &mut self,
1245 ltx_bytes: &[u8],
1246 hdr: &LastL0Header,
1247 prev_wal_offset: i64,
1248 frame_size: i64,
1249 ) -> Result<bool> {
1250 if prev_wal_offset <= WAL_HEADER_SIZE as i64 {
1251 return Ok(false);
1252 }
1253
1254 let frame = self.wal_bytes_at(prev_wal_offset, frame_size)?;
1255 let pgno = be_u32(&frame[0..]);
1256 let fsalt1 = be_u32(&frame[8..]);
1257 let fsalt2 = be_u32(&frame[12..]);
1258 let data = &frame[WAL_FRAME_HEADER_SIZE..];
1259
1260 if fsalt1 != hdr.wal_salt1 || fsalt2 != hdr.wal_salt2 {
1261 return Ok(false);
1262 }
1263
1264 // Verify the last WAL page exists, byte-for-byte, in the last LTX file.
1265 // Decode the full file and compare the decompressed page bytes.
1266 let pages = ltx::decode_file_pages(ltx_bytes).map_err(|_| Error::LTXCorrupted)?;
1267 for (p, page_data) in &pages {
1268 if *p == pgno && page_data.as_slice() == data {
1269 return Ok(true);
1270 }
1271 }
1272 Ok(false)
1273 }
1274
1275 /// The cache-backed page check: compares the WAL frame at
1276 /// `prev_wal_offset` against the final frame the previous sync
1277 /// consumed. Equivalent to the ported search when the WAL is
1278 /// unchanged (the L0's entry for that page IS that frame), and
1279 /// strictly more conservative when it is not — a mismatch forces a
1280 /// snapshot, never an incremental read over rewritten history.
1281 fn last_page_match_cached(
1282 &mut self,
1283 hdr: &LastL0Header,
1284 prev_wal_offset: i64,
1285 frame_size: i64,
1286 ) -> Result<bool> {
1287 if prev_wal_offset <= WAL_HEADER_SIZE as i64 || hdr.final_page.is_empty() {
1288 return Ok(false);
1289 }
1290 let frame = self.wal_bytes_at(prev_wal_offset, frame_size)?;
1291 let pgno = be_u32(&frame[0..]);
1292 let fsalt1 = be_u32(&frame[8..]);
1293 let fsalt2 = be_u32(&frame[12..]);
1294 let data = &frame[WAL_FRAME_HEADER_SIZE..];
1295 Ok(fsalt1 == hdr.wal_salt1
1296 && fsalt2 == hdr.wal_salt2
1297 && pgno == hdr.final_pgno
1298 && data == hdr.final_page.as_slice())
1299 }
1300
1301 /// Detects whether a FULL or RESTART checkpoint occurred (we may have missed
1302 /// frames). Ported from `DB.detectFullCheckpoint` (db.go:1477-1507).
1303 fn detect_full_checkpoint(&self, known_salts: &[(u32, u32)]) -> Result<bool> {
1304 let wal_bytes = self.host.read(&self.wal_path())?;
1305 let rd = WalReader::new(&wal_bytes).map_err(Error::from)?;
1306 let last_known = known_salts.last().copied().unwrap_or((0, 0));
1307 let mut m = rd.frame_salts_until(last_known);
1308 for s in known_salts {
1309 m.remove(s);
1310 }
1311 Ok(!m.is_empty())
1312 }
1313
1314 /// Read an incremental WAL image through the first invalid frame.
1315 ///
1316 /// SQLite can retain stale frames after a checkpoint restarts the logical
1317 /// WAL. The frame checksum chain is the format's end marker, so grow a
1318 /// prefix geometrically and stop when `WalReader` stops before the bytes
1319 /// that were read. The geometric window keeps parsing linear overall and
1320 /// reads at most one prior window past the valid end. The returned byte
1321 /// count includes that discarded probe for an honest I/O ledger.
1322 fn read_valid_wal_image(&mut self, info: &SyncInfo, start: usize) -> Result<(WalImage, usize)> {
1323 let frame_size = self.page_size as usize + WAL_FRAME_HEADER_SIZE;
1324 let offset = info.offset;
1325 let salt1 = info.salt1;
1326 let salt2 = info.salt2;
1327 Ok(self.with_wal_file(|file| {
1328 let file_len = file.file_len()? as usize;
1329 if file_len < WAL_HEADER_SIZE || start < WAL_HEADER_SIZE || start >= file_len {
1330 return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof));
1331 }
1332 let complete_end =
1333 WAL_HEADER_SIZE + ((file_len - WAL_HEADER_SIZE) / frame_size) * frame_size;
1334 if start >= complete_end || !(start - WAL_HEADER_SIZE).is_multiple_of(frame_size) {
1335 return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof));
1336 }
1337
1338 let tail_base = if start == WAL_HEADER_SIZE { 0 } else { start };
1339 let mut bytes = file.read_exact_at(0, WAL_HEADER_SIZE)?;
1340 let mut read_bytes = bytes.len();
1341 let mut cursor = start;
1342 let mut target_frames = 1_usize;
1343 loop {
1344 let target_end = start
1345 .saturating_add(target_frames.saturating_mul(frame_size))
1346 .min(complete_end);
1347 if target_end > cursor {
1348 let chunk = file.read_exact_at(cursor as u64, target_end - cursor)?;
1349 read_bytes += chunk.len();
1350 bytes.extend_from_slice(&chunk);
1351 cursor = target_end;
1352 }
1353
1354 let valid_end = {
1355 let parsed = if offset == WAL_HEADER_SIZE as i64 {
1356 WalReader::new(&bytes)
1357 } else if tail_base == 0 {
1358 WalReader::new_with_offset(&bytes, offset, salt1, salt2)
1359 } else {
1360 WalReader::new_with_offset_over_tail(
1361 &bytes,
1362 tail_base as i64,
1363 offset,
1364 salt1,
1365 salt2,
1366 )
1367 };
1368 let mut reader = parsed.map_err(|error| {
1369 std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string())
1370 })?;
1371 reader.page_map().map_err(|error| {
1372 std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string())
1373 })?;
1374 if reader.offset() == 0 {
1375 WAL_HEADER_SIZE
1376 } else {
1377 reader.offset() as usize + frame_size
1378 }
1379 };
1380
1381 if valid_end < cursor {
1382 let keep = if tail_base == 0 {
1383 valid_end
1384 } else {
1385 WAL_HEADER_SIZE + valid_end.saturating_sub(tail_base)
1386 };
1387 bytes.truncate(keep);
1388 return Ok((
1389 WalImage {
1390 bytes,
1391 tail_base,
1392 file_len,
1393 },
1394 read_bytes,
1395 ));
1396 }
1397 if cursor == complete_end {
1398 return Ok((
1399 WalImage {
1400 bytes,
1401 tail_base,
1402 file_len,
1403 },
1404 read_bytes,
1405 ));
1406 }
1407 target_frames = target_frames.saturating_mul(2);
1408 }
1409 })?)
1410 }
1411
1412 /// Copies pending bytes from the real WAL into a new L0 LTX file.
1413 ///
1414 /// Ported from `DB.sync` (db.go:1517-1723). Returns `true` if an LTX file was
1415 /// written (there were new pages or we were snapshotting). Atomic
1416 /// tmp→fsync→rename with the pos cache + anti-feedback flags updated after.
1417 fn sync_inner(&mut self, mut info: SyncInfo) -> Result<bool> {
1418 let phase = crate::host::telemetry_us();
1419 // A capture that starts at the WAL header reads a logical WAL with no
1420 // backfilled prefix: the first sync, a restart, or a boundary image.
1421 // The checkpoint trigger counts from the backfilled boundary, so it
1422 // must not carry an offset from the WAL that just ended, or the new
1423 // WAL would grow past that offset before its first checkpoint.
1424 if info.offset == WAL_HEADER_SIZE as i64 {
1425 self.checkpointed_wal_offset = WAL_HEADER_SIZE as i64;
1426 }
1427 let pos = self.pos()?;
1428 let tx_id = TXID(pos.txid.0 + 1);
1429 let filename = self.ltx_path(0, tx_id, tx_id);
1430
1431 let db_size = self.db_file_size()?;
1432 let mut commit = (db_size / self.page_size as i64) as u32;
1433 self.last_db_pages = commit;
1434 self.last_sync_timing.pos_us = crate::host::telemetry_us().saturating_sub(phase);
1435 let phase = crate::host::telemetry_us();
1436
1437 // The incremental path reads only the valid checksum chain: the
1438 // 32-byte WAL header, the previous frame when there is one, and the
1439 // frames from `info.offset` on. A passive or restart checkpoint can
1440 // leave a large physical suffix after SQLite restarts the logical WAL
1441 // at its beginning. Reading to the physical file length made every
1442 // Queue capture re-read that stale suffix because Queue cells cannot
1443 // use size-triggered TRUNCATE checkpoints. The progressive reader
1444 // doubles its valid-prefix window, then drops the bounded look-ahead
1445 // after the first salt or checksum failure. The sparse image keeps
1446 // every offset absolute, so the reader and page collectors remain
1447 // unchanged. An I/O race or a previous-frame mismatch falls back to
1448 // the full read the port always did.
1449 let frame_size_bytes = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64;
1450 let mut wal = if info.snapshotting {
1451 self.last_sync_timing.wal_read_kind = 1;
1452 let bytes = self.host.read(&self.wal_path())?;
1453 self.last_sync_timing.wal_read_bytes = bytes.len() as u64;
1454 self.last_sync_timing.wal_len_bytes = bytes.len() as u64;
1455 WalImage::whole(bytes)
1456 } else {
1457 let start = if info.offset <= WAL_HEADER_SIZE as i64 + frame_size_bytes {
1458 WAL_HEADER_SIZE
1459 } else {
1460 (info.offset - frame_size_bytes) as usize
1461 };
1462 match self.read_valid_wal_image(&info, start) {
1463 Ok((image, read_bytes)) => {
1464 self.last_sync_timing.wal_read_kind =
1465 if start == WAL_HEADER_SIZE { 2 } else { 0 };
1466 self.last_sync_timing.wal_read_bytes = read_bytes as u64;
1467 self.last_sync_timing.wal_len_bytes = image.file_len as u64;
1468 image
1469 }
1470 Err(_) => {
1471 self.last_sync_timing.wal_read_kind = 3;
1472 let bytes = self.host.read(&self.wal_path())?;
1473 self.last_sync_timing.wal_read_bytes = bytes.len() as u64;
1474 self.last_sync_timing.wal_len_bytes = bytes.len() as u64;
1475 WalImage::whole(bytes)
1476 }
1477 }
1478 };
1479
1480 self.last_sync_timing.wal_read_us = crate::host::telemetry_us().saturating_sub(phase);
1481 self.last_sync_timing.wal_image_bytes = wal.bytes.len() as u64;
1482 self.last_sync_timing.snapshot = info.snapshotting;
1483 self.last_sync_timing.snapshot_reason = if info.snapshotting {
1484 snapshot_reason_code(&info.reason)
1485 } else {
1486 0
1487 };
1488 let phase = crate::host::telemetry_us();
1489
1490 // Choose the WAL reader start: from the header, or seek to info.offset.
1491 // A previous-frame mismatch falls back to a full read (snapshot),
1492 // mirroring NewWALReaderWithOffset's PrevFrameMismatchError handling
1493 // (db.go:1565-1581).
1494 // A previous-frame mismatch restarts the read from the header. The
1495 // sparse tail image is zero-filled below `start`, so a from-header
1496 // reader over it would see no valid frame and report "nothing to
1497 // capture" — a silent miss the ship loop would then credit. The
1498 // mismatch path therefore re-reads the complete WAL first, which is
1499 // exactly the port's former full-read behavior on this branch.
1500 let mismatch = !(info.offset == WAL_HEADER_SIZE as i64)
1501 && matches!(
1502 wal.reader_at(info.offset, info.salt1, info.salt2),
1503 Err(crate::wal::WalError::PrevFrameMismatch)
1504 );
1505 if mismatch {
1506 info.offset = WAL_HEADER_SIZE as i64;
1507 if self.last_sync_timing.wal_read_kind == 0 {
1508 let bytes = self.host.read(&self.wal_path())?;
1509 self.last_sync_timing.wal_read_kind = 3;
1510 self.last_sync_timing.wal_read_bytes = bytes.len() as u64;
1511 self.last_sync_timing.wal_len_bytes = bytes.len() as u64;
1512 self.last_sync_timing.wal_image_bytes = bytes.len() as u64;
1513 wal = WalImage::whole(bytes);
1514 }
1515 }
1516 let mut rd = if info.offset == WAL_HEADER_SIZE as i64 {
1517 WalReader::new(&wal.bytes).map_err(Error::from)?
1518 } else {
1519 wal.reader_at(info.offset, info.salt1, info.salt2)
1520 .map_err(Error::from)?
1521 };
1522
1523 let (page_map, max_offset, wal_commit) = rd.page_map().map_err(Error::from)?;
1524 if wal_commit > 0 {
1525 commit = wal_commit;
1526 }
1527
1528 let sz = if max_offset > 0 {
1529 max_offset - info.offset
1530 } else {
1531 0
1532 };
1533 if sz < 0 {
1534 return Err(Error::Other(
1535 format!(
1536 "wal size must be positive: sz={sz}, maxOffset={max_offset}, info.offset={}",
1537 info.offset
1538 )
1539 .into(),
1540 ));
1541 }
1542
1543 // Exit if there are no new WAL pages and we are not snapshotting
1544 // (db.go:1603-1607).
1545 if !info.snapshotting && sz == 0 {
1546 return Ok(false);
1547 }
1548
1549 let (rd_salt1, rd_salt2) = rd.salt();
1550
1551 // Build the page set for the encoder.
1552 let pages: Vec<(u32, Vec<u8>)> = if info.snapshotting {
1553 self.collect_snapshot_pages(&wal, &page_map, commit)?
1554 } else {
1555 self.collect_wal_pages(&wal, &page_map, info.prev_commit, commit)?
1556 };
1557 self.last_sync_timing.map_collect_us = crate::host::telemetry_us().saturating_sub(phase);
1558 let phase = crate::host::telemetry_us();
1559
1560 let header = ltx::Header {
1561 version: ltx::VERSION,
1562 flags: ltx::HEADER_FLAG_NO_CHECKSUM,
1563 page_size: self.page_size,
1564 commit,
1565 min_txid: tx_id,
1566 max_txid: tx_id,
1567 timestamp: self.host.now_unix_millis(),
1568 pre_apply_checksum: 0,
1569 wal_offset: info.offset,
1570 wal_size: sz,
1571 wal_salt1: rd_salt1,
1572 wal_salt2: rd_salt2,
1573 node_id: 0,
1574 };
1575
1576 // Encode the LTX file (with HeaderFlagNoChecksum, so post-apply is 0).
1577 let encoded = ltx::encode_file(&header, &pages, 0)?;
1578 self.last_sync_timing.ltx_encode_us = crate::host::telemetry_us().saturating_sub(phase);
1579 let phase = crate::host::telemetry_us();
1580
1581 // Atomic tmp → fsync → rename (db.go:1609-1685).
1582 let tmp_filename = format!("{filename}.tmp");
1583 let parent = Path::new(&tmp_filename).parent().map(Path::to_path_buf);
1584 if !self.l0_dir_ready {
1585 if let Some(parent) = &parent {
1586 self.host.create_dir_all(parent)?;
1587 }
1588 self.l0_dir_ready = true;
1589 }
1590 // On rename failure, clear the L0 cache + invalidate pos
1591 // (db.go:1680-1684); the error path below does that. A directory
1592 // that vanished under a ready flag is recreated once and the cut
1593 // retried, so the flag saves a `mkdir` per sync without trusting it.
1594 self.last_sync_timing.fsync_us =
1595 match write_file_atomic(&self.host, &tmp_filename, &filename, &encoded) {
1596 Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
1597 if let Some(parent) = &parent {
1598 self.host.create_dir_all(parent)?;
1599 }
1600 write_file_atomic(&self.host, &tmp_filename, &filename, &encoded)?
1601 }
1602 other => other?,
1603 };
1604 self.last_sync_timing.file_write_us = crate::host::telemetry_us()
1605 .saturating_sub(phase)
1606 .saturating_sub(self.last_sync_timing.fsync_us);
1607 // The next verify reads exactly these fields back; caching them —
1608 // plus the final consumed WAL frame for the page check — is what
1609 // spares it re-reading the file it just watched being written.
1610 let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64;
1611 let final_frame_offset = max_offset - frame_size;
1612 let (final_pgno, final_page) = match (final_frame_offset >= WAL_HEADER_SIZE as i64)
1613 .then(|| wal.slice(final_frame_offset, frame_size as usize))
1614 .flatten()
1615 {
1616 Some(frame) => (be_u32(&frame[0..]), frame[WAL_FRAME_HEADER_SIZE..].to_vec()),
1617 None => (0, Vec::new()),
1618 };
1619 self.last_l0_header = Some((
1620 tx_id,
1621 LastL0Header {
1622 wal_offset: info.offset,
1623 wal_size: sz,
1624 wal_salt1: rd_salt1,
1625 wal_salt2: rd_salt2,
1626 commit,
1627 final_pgno,
1628 final_page,
1629 },
1630 ));
1631
1632 // Update the L0 file-info cache and the cached position (db.go:1687-1702).
1633 self.max_l0_file_info = Some(ltx::FileInfo {
1634 level: 0,
1635 min_txid: tx_id,
1636 max_txid: tx_id,
1637 pre_apply_checksum: 0,
1638 post_apply_checksum: 0,
1639 size: encoded.len() as i64,
1640 created_at: Some(system_time_from_unix_millis(self.host.now_unix_millis())),
1641 });
1642 // The encoder's post-apply pos: for a NoChecksum file the post-apply
1643 // checksum is 0; the position is (tx_id, 0).
1644 self.pos_cache = Some(Pos::new(tx_id, 0));
1645
1646 // Track the logical end of WAL content for checkpoint decisions
1647 // (db.go:1704-1718, issues #997/#927).
1648 let final_offset = info.offset + sz;
1649 self.last_synced_wal_offset = final_offset;
1650 self.synced_to_wal_end = match self.wal_file_size() {
1651 Ok(wal_size) => final_offset == wal_size,
1652 Err(_) => false,
1653 };
1654
1655 Ok(true)
1656 }
1657
1658 /// Collects the page set for an incremental sync, in ascending page-number
1659 /// order. Pages absent from the WAL growth range come from the database file
1660 /// (Litestream #1292 / celld #150).
1661 fn collect_wal_pages(
1662 &self,
1663 wal: &WalImage,
1664 page_map: &HashMap<u32, i64>,
1665 prev_commit: u32,
1666 commit: u32,
1667 ) -> Result<Vec<(u32, Vec<u8>)>> {
1668 let mut pgnos: Vec<u32> = page_map.keys().copied().collect();
1669 let lock = lock_pgno(self.page_size);
1670 if commit > prev_commit {
1671 for pgno in (prev_commit + 1)..=commit {
1672 if pgno != lock && !page_map.contains_key(&pgno) {
1673 pgnos.push(pgno);
1674 }
1675 }
1676 }
1677 pgnos.sort_unstable();
1678
1679 let mut out = Vec::with_capacity(pgnos.len());
1680 for pgno in pgnos {
1681 let data = match page_map.get(&pgno) {
1682 Some(&offset) => wal.page(offset, self.page_size)?,
1683 None => self.read_db_page(pgno)?,
1684 };
1685 out.push((pgno, data));
1686 }
1687 Ok(out)
1688 }
1689
1690 /// Collects the full page set for a snapshot: every page `1..=commit`
1691 /// (skipping the lock page), reading from the WAL where present, else the DB
1692 /// file. Ported from `DB.writeLTXFromDB` (db.go:1725-1770).
1693 fn collect_snapshot_pages(
1694 &self,
1695 wal: &WalImage,
1696 page_map: &HashMap<u32, i64>,
1697 commit: u32,
1698 ) -> Result<Vec<(u32, Vec<u8>)>> {
1699 let lock = lock_pgno(self.page_size);
1700 let mut out = Vec::with_capacity(commit as usize);
1701 for pgno in (1..=commit).filter(|pgno| *pgno != lock) {
1702 let data = match page_map.get(&pgno) {
1703 Some(&offset) => wal.page(offset, self.page_size)?,
1704 None => self.read_db_page(pgno)?,
1705 };
1706 out.push((pgno, data));
1707 }
1708 Ok(out)
1709 }
1710
1711 /// Reads one page of the main database through the connection's VFS file,
1712 /// never through a host read of the path. A paged cell's file is a sparse
1713 /// cache of its cut, and the host read returned every unfaulted page as
1714 /// zeros: each paged epoch's opener snapshot shipped holes, and the next
1715 /// epoch restored a database whose integrity_check named every overflow
1716 /// chain (fleet, 2026-09-02). The VFS faults the page in instead.
1717 fn read_db_page(&self, pgno: u32) -> Result<Vec<u8>> {
1718 let mut file: *mut ffi::sqlite3_file = std::ptr::null_mut();
1719 // SAFETY: `conn` is open, and FILE_POINTER hands out the main file,
1720 // which lives as long as the connection.
1721 let rc = unsafe {
1722 ffi::sqlite3_file_control(
1723 self.conn.handle(),
1724 c"main".as_ptr(),
1725 ffi::SQLITE_FCNTL_FILE_POINTER,
1726 (&mut file as *mut *mut ffi::sqlite3_file).cast(),
1727 )
1728 };
1729 if rc != ffi::SQLITE_OK || file.is_null() {
1730 return Err(std::io::Error::other("no main database file").into());
1731 }
1732 let n = self.page_size as usize;
1733 let mut page = vec![0u8; n];
1734 let offset = i64::from(pgno - 1) * i64::from(self.page_size);
1735 // SAFETY: `file` is the live main file and `page` holds `n` bytes.
1736 let rc = unsafe {
1737 let read = (*(*file).pMethods).xRead.expect("xRead");
1738 read(file, page.as_mut_ptr().cast(), n as c_int, offset)
1739 };
1740 if rc != ffi::SQLITE_OK {
1741 return Err(std::io::Error::other(format!("read page {pgno}: sqlite rc {rc}")).into());
1742 }
1743 Ok(page)
1744 }
1745
1746 // ── Checkpointing ──────────────────────────────────────────────────────
1747
1748 /// Performs a checkpoint based on the configured thresholds (3-tier policy).
1749 ///
1750 /// Ported from `DB.checkpointIfNeeded` (db.go:1092-1156). Checks
1751 /// in priority order: TruncatePageN (TRUNCATE, blocking) → MinCheckpointPageN
1752 /// (PASSIVE) → CheckpointInterval (PASSIVE, gated on `synced_since_checkpoint`).
1753 fn checkpoint_if_needed(&mut self, orig_wal_size: i64, new_wal_size: i64) -> Result<()> {
1754 if self.page_size == 0 {
1755 return Ok(());
1756 }
1757
1758 // Priority 1: emergency TRUNCATE (blocking) on the *original* logical
1759 // size. A truncate ends in a boundary image of the whole database
1760 // (see `checkpoint`). For a small database that image is the cheap
1761 // price the threshold was tuned for, so below `RELATIVE_TRUNCATE_PAGES`
1762 // the threshold is absolute, as upstream's. Above it the WAL must also
1763 // have grown past the database before a truncate: the image then costs
1764 // at most what the WAL it replaces did, and the chain stays within 2x
1765 // of the writes. A fixed threshold made a 1MB-row whale pay a
1766 // database-sized capture every write, and its chain grew as the
1767 // square of its size.
1768 if self.truncate_page_n > 0 {
1769 let relative = if self.last_db_pages > RELATIVE_TRUNCATE_PAGES {
1770 self.last_db_pages
1771 } else {
1772 0
1773 };
1774 let threshold = self.truncate_page_n.max(relative);
1775 if orig_wal_size >= calc_wal_size(self.page_size, threshold) {
1776 return self.checkpoint(CheckpointMode::Truncate);
1777 }
1778 }
1779
1780 // Priority 2: PASSIVE once the frames appended since the last
1781 // backfill reach the threshold. See `checkpointed_wal_offset` for why
1782 // this is not the whole logical size: a checkpoint whose sealing
1783 // write could not restart the WAL must cost one retry at the next
1784 // threshold, not a checkpoint per sync.
1785 let backfilled_through = self.checkpointed_wal_offset.clamp(
1786 WAL_HEADER_SIZE as i64,
1787 new_wal_size.max(WAL_HEADER_SIZE as i64),
1788 );
1789 let threshold =
1790 calc_wal_size(self.page_size, self.min_checkpoint_page_n) - WAL_HEADER_SIZE as i64;
1791 if new_wal_size - backfilled_through >= threshold {
1792 return self.checkpoint_passive_swallowing_busy();
1793 }
1794
1795 // Priority 3: time-based PASSIVE, gated on data synced since last
1796 // checkpoint (#896). Uses the DB-file mtime and a logical-size guard so an
1797 // idle DB does not spin LTX files (db.go:1133-1153).
1798 if self.checkpoint_interval > Duration::ZERO && self.synced_since_checkpoint {
1799 let elapsed = self.host.file_age(&self.path)?;
1800 if elapsed > self.checkpoint_interval && new_wal_size > calc_wal_size(self.page_size, 1)
1801 {
1802 return self.checkpoint_passive_swallowing_busy();
1803 }
1804 }
1805
1806 Ok(())
1807 }
1808
1809 /// PASSIVE checkpoint that swallows SQLITE_BUSY (log-and-continue, the one
1810 /// sanctioned best-effort case, db.go:1118-1124).
1811 fn checkpoint_passive_swallowing_busy(&mut self) -> Result<()> {
1812 match self.checkpoint(CheckpointMode::Passive) {
1813 Ok(()) => Ok(()),
1814 Err(e) if is_sqlite_busy_error(&e) => {
1815 self.last_sync_timing.checkpoint_runs = 1;
1816 self.last_sync_timing.checkpoint_busy_errors = 1;
1817 Ok(())
1818 }
1819 Err(e) => Err(e),
1820 }
1821 }
1822
1823 /// Performs a checkpoint on the WAL.
1824 ///
1825 /// Ported from `DB.Checkpoint`/`DB.checkpoint` (db.go:1801-1873).
1826 /// A passive checkpoint seals the WAL under a short writer barrier before
1827 /// it runs. If any checkpoint restarts the WAL, a post-checkpoint write lock
1828 /// protects either an incremental sync or a full boundary snapshot.
1829 ///
1830 /// The upstream `chkMu.TryLock` snapshot-vs-checkpoint gate is unnecessary in
1831 /// the synchronous `Db`. `&mut self` serializes `sync`, `checkpoint`, and
1832 /// `snapshot`, and one blocking thread owns the `Db`.
1833 pub fn checkpoint(&mut self, mode: CheckpointMode) -> Result<()> {
1834 self.checkpoint_with_passive_hooks(mode, None, None, None)
1835 }
1836
1837 fn checkpoint_with_passive_hooks(
1838 &mut self,
1839 mode: CheckpointMode,
1840 passive_hook: Option<Box<dyn FnOnce() + Send>>,
1841 passive_unlocked_hook: Option<Box<dyn FnOnce() + Send>>,
1842 post_barrier_hook: Option<Box<dyn FnOnce() + Send>>,
1843 ) -> Result<()> {
1844 // Self-heal, as in `sync`: `checkpoint` writes to both control tables
1845 // and re-acquires the read lock through `_litestream_seq`, and the
1846 // invariant is that the tables exist before any control-table
1847 // statement — not only before a capture.
1848 self.ensure_control_tables()?;
1849
1850 // Read the WAL header before the checkpoint to detect a restart.
1851 let hdr = self.wal_header_bytes()?;
1852
1853 // Copy the end of the WAL before the checkpoint to capture as much as
1854 // possible (db.go:1823-1826).
1855 self.verify_and_sync(None)?;
1856
1857 let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64;
1858 let pre_checkpoint_frame_n = if self.last_synced_wal_offset > WAL_HEADER_SIZE as i64 {
1859 (self.last_synced_wal_offset - WAL_HEADER_SIZE as i64) / frame_size
1860 } else {
1861 0
1862 };
1863
1864 // A passive checkpoint does not acquire SQLite's writer lock. Hold a
1865 // short write transaction on the dedicated read-lock connection, then
1866 // sync again to seal every commit before running the checkpoint on the
1867 // main connection. Keep the barrier until the checkpoint completes.
1868 let pragma = if mode == CheckpointMode::Passive {
1869 self.exec_passive_checkpoint_with_barrier(hdr, passive_hook, passive_unlocked_hook)?
1870 } else {
1871 self.exec_checkpoint(mode)?
1872 };
1873 self.last_sync_timing.checkpoint_runs = 1;
1874 self.last_sync_timing.checkpoint_wal_frames = pragma.wal_frames.max(0) as u64;
1875 self.last_sync_timing.checkpoint_backfilled = pragma.backfilled.max(0) as u64;
1876 self.last_sync_timing.checkpoint_busy = u64::from(pragma.busy != 0);
1877 // The backfilled boundary in this WAL's coordinates. A short backfill
1878 // (a reader pinned the WAL) leaves the remainder counting toward the
1879 // next threshold, so a pinned WAL retries at the threshold and an
1880 // unpinned one does not retry at all.
1881 self.checkpointed_wal_offset =
1882 WAL_HEADER_SIZE as i64 + pragma.backfilled.max(0) * frame_size;
1883 if let Some(hook) = post_barrier_hook {
1884 hook();
1885 }
1886
1887 // Force a write so a restarted WAL has a new header and at least one
1888 // frame that verify can read.
1889 self.conn
1890 .execute_batch(
1891 "INSERT INTO _litestream_seq (id, seq) VALUES (1, 1) \
1892 ON CONFLICT (id) DO UPDATE SET seq = seq + 1",
1893 )
1894 .map_err(sql_err)?;
1895
1896 // If the WAL header is unchanged, the WAL did not restart — done.
1897 let other = self.wal_header_bytes()?;
1898 if hdr == other {
1899 self.synced_since_checkpoint = false;
1900 return Ok(());
1901 }
1902 self.last_sync_timing.checkpoint_restarts = 1;
1903
1904 // The WAL restarted. Grab the write lock, then either copy the new WAL
1905 // tail or take a complete boundary image. TRUNCATE always needs the
1906 // boundary image because SQLite reports zero frames after resetting the
1907 // WAL. A forced checkpoint also needs one if it covered more frames than
1908 // the sealed pre-checkpoint sync observed.
1909 self.conn
1910 .prepare_cached("BEGIN")
1911 .and_then(|mut statement| statement.execute([]))
1912 .map_err(sql_err)?;
1913 let post = (|| -> Result<()> {
1914 self.conn
1915 .prepare_cached("INSERT INTO _litestream_lock (id) VALUES (1)")
1916 .and_then(|mut statement| statement.execute([]))
1917 .map_err(sql_err)?;
1918 if mode == CheckpointMode::Truncate
1919 || (mode != CheckpointMode::Passive && pragma.wal_frames > pre_checkpoint_frame_n)
1920 {
1921 let info = SyncInfo {
1922 offset: WAL_HEADER_SIZE as i64,
1923 salt1: be_u32(&other[16..]),
1924 salt2: be_u32(&other[20..]),
1925 snapshotting: true,
1926 reason: "checkpoint boundary snapshot".to_string(),
1927 ..Default::default()
1928 };
1929 self.sync_inner(info)?;
1930 } else {
1931 self.verify_and_sync(None)?;
1932 }
1933 Ok(())
1934 })();
1935 // Always roll back the write transaction (db.go:1849,1867).
1936 let rb = rollback(&self.conn);
1937 post?;
1938 rb?;
1939
1940 self.synced_since_checkpoint = false;
1941 Ok(())
1942 }
1943
1944 /// Seals and runs a passive checkpoint while holding SQLite's writer lock.
1945 ///
1946 /// The long-lived read transaction uses `rtx_conn`, so this method releases
1947 /// that read lock and temporarily reuses the same connection for the writer
1948 /// barrier. The checkpoint itself runs through `conn`, as SQLite does not
1949 /// permit a checkpoint on the connection that owns the write transaction.
1950 fn exec_passive_checkpoint_with_barrier(
1951 &mut self,
1952 pre_checkpoint_header: [u8; WAL_HEADER_SIZE],
1953 hook: Option<Box<dyn FnOnce() + Send>>,
1954 unlocked_hook: Option<Box<dyn FnOnce() + Send>>,
1955 ) -> Result<CheckpointPragma> {
1956 self.release_read_lock()?;
1957 if let Some(hook) = unlocked_hook {
1958 hook();
1959 }
1960
1961 let result = (|| -> Result<CheckpointPragma> {
1962 self.rtx_conn
1963 .prepare_cached("BEGIN")
1964 .and_then(|mut statement| statement.execute([]))
1965 .map_err(sql_err)?;
1966 self.rtx_conn
1967 .prepare_cached("INSERT INTO _litestream_lock (id) VALUES (1)")
1968 .and_then(|mut statement| statement.execute([]))
1969 .map_err(sql_err)?;
1970
1971 // Writers can cross their own autocheckpoint threshold after the
1972 // read lock is released but before this barrier wins SQLite's
1973 // writer lock. A changed WAL header means some of those commits
1974 // can already live only in the database file. The normal
1975 // synced-to-end shortcut cannot distinguish that race from our own
1976 // completed checkpoint, so an incremental LTX can omit the
1977 // checkpointed pages and produce a malformed restore. Seal the
1978 // complete boundary while the writer lock makes the database file
1979 // and the new WAL tail a stable pair. The cost is one database-size
1980 // LTX file only when another checkpoint wins this narrow gap.
1981 let barrier_header = self.wal_header_bytes()?;
1982 if barrier_header != pre_checkpoint_header {
1983 let info = SyncInfo {
1984 offset: WAL_HEADER_SIZE as i64,
1985 salt1: be_u32(&barrier_header[16..]),
1986 salt2: be_u32(&barrier_header[20..]),
1987 snapshotting: true,
1988 reason: "WAL restarted before passive checkpoint barrier".to_string(),
1989 ..Default::default()
1990 };
1991 self.sync_inner(info)?;
1992 } else {
1993 // Commits can land between the earlier sync and acquisition of
1994 // the barrier. This second sync seals them before the
1995 // checkpoint.
1996 self.verify_and_sync(None)?;
1997 }
1998 if let Some(hook) = hook {
1999 hook();
2000 }
2001 self.run_checkpoint_pragma(CheckpointMode::Passive)
2002 })();
2003
2004 // Release the writer barrier before restoring the long-lived read lock.
2005 // Preserve the operation error if both the operation and cleanup fail.
2006 let rollback_result = rollback(&self.rtx_conn);
2007 let reacquire_result = self.acquire_read_lock();
2008 match result {
2009 Err(error) => Err(error),
2010 Ok(pragma) => {
2011 rollback_result?;
2012 reacquire_result?;
2013 Ok(pragma)
2014 }
2015 }
2016 }
2017
2018 /// Releases the read lock, runs `PRAGMA wal_checkpoint(<mode>)`, and
2019 /// re-acquires the read lock — re-acquiring even on error.
2020 ///
2021 /// Ported from `DB.execCheckpoint` (db.go:1875-1919). The exact
2022 /// release→checkpoint→re-acquire sequence is load-bearing.
2023 fn exec_checkpoint(&mut self, mode: CheckpointMode) -> Result<CheckpointPragma> {
2024 // Ensure the read lock is removed before the checkpoint; defer the
2025 // re-acquire so it runs even on early return.
2026 self.release_read_lock()?;
2027
2028 let result = self.run_checkpoint_pragma(mode);
2029
2030 // Re-acquire the read lock immediately after the checkpoint (the deferred
2031 // re-acquire in Go). If the pragma succeeded, propagate any re-acquire
2032 // error; otherwise surface the original pragma error.
2033 let reacquire = self.acquire_read_lock();
2034 match (result, reacquire) {
2035 (Ok(pragma), Ok(())) => Ok(pragma),
2036 (Ok(_), Err(e)) => Err(e),
2037 (Err(e), _) => Err(e),
2038 }
2039 }
2040
2041 /// Runs the raw `PRAGMA wal_checkpoint(<mode>)` and reads its 3-int result.
2042 fn run_checkpoint_pragma(&self, mode: CheckpointMode) -> Result<CheckpointPragma> {
2043 let sql = format!("PRAGMA wal_checkpoint({mode})");
2044 self.conn
2045 .prepare_cached(&sql)
2046 .map_err(sql_err)?
2047 .query_row([], |row| {
2048 Ok(CheckpointPragma {
2049 busy: row.get::<_, i64>(0)?,
2050 wal_frames: row.get::<_, i64>(1)?,
2051 backfilled: row.get::<_, i64>(2)?,
2052 })
2053 })
2054 .map_err(sql_err)
2055 }
2056
2057 // ── CRC64 ──────────────────────────────────────────────────────────────
2058
2059 /// Returns a CRC-64/ISO checksum of the database file and its current
2060 /// position, after forcing a RESTART checkpoint so the DB sits at the WAL
2061 /// start. Ported from `DB.CRC64` (db.go:2329-2359).
2062 pub fn crc64(&mut self) -> Result<(u64, Pos)> {
2063 // Force a RESTART checkpoint to ensure the DB is at the start of the WAL.
2064 self.checkpoint(CheckpointMode::Restart)?;
2065
2066 let pos = self.pos()?;
2067
2068 // Checksum the whole database (CRC64-ISO), page by page through the
2069 // VFS like every other database read.
2070 let pages = self.db_file_size()? / i64::from(self.page_size);
2071 let mut h = Crc64::new();
2072 for pgno in 1..=u32::try_from(pages).expect("page count") {
2073 h.update(&self.read_db_page(pgno)?);
2074 }
2075 Ok((h.sum64(), pos))
2076 }
2077
2078 // ── Snapshot ───────────────────────────────────────────────────────────
2079
2080 /// Writes a full database snapshot as an LTX file to `w` and returns the
2081 /// snapshot position. Ported from `DB.SnapshotReader` (db.go:1922-2021),
2082 /// buffered rather than streamed, as described in `client/mod.rs`.
2083 ///
2084 /// The snapshot spans `MinTXID=1 .. MaxTXID=pos.TXID` (db.go:1996-1997). Its
2085 /// page set is the full DB (lock page skipped), and — being a snapshot — the
2086 /// rolling post-apply checksum **is** tracked.
2087 pub fn snapshot_to_writer<W: std::io::Write>(&mut self, w: &mut W) -> Result<Pos> {
2088 if self.page_size == 0 {
2089 return Err(Error::Other(
2090 "db not ready: page size not initialized".into(),
2091 ));
2092 }
2093
2094 let pos = self.pos()?;
2095
2096 let db_size = self.db_file_size()?;
2097 let mut commit = (db_size / self.page_size as i64) as u32;
2098
2099 let wal = WalImage::whole(self.host.read(&self.wal_path())?);
2100 let mut rd = WalReader::new(&wal.bytes).map_err(Error::from)?;
2101 let (page_map, max_offset, wal_commit) = rd.page_map().map_err(Error::from)?;
2102 if wal_commit > 0 {
2103 commit = wal_commit;
2104 }
2105 let wal_offset = rd.offset();
2106 let sz = if max_offset > 0 {
2107 max_offset - wal_offset
2108 } else {
2109 0
2110 };
2111 let (salt1, salt2) = rd.salt();
2112
2113 let pages = self.collect_snapshot_pages(&wal, &page_map, commit)?;
2114
2115 // A snapshot tracks the rolling post-apply checksum (MinTXID==1, no
2116 // NoChecksum flag) — compute it the way decode_file verifies it.
2117 let lock = lock_pgno(self.page_size);
2118 let mut rolling: crate::Checksum = crate::CHECKSUM_FLAG;
2119 for (p, d) in &pages {
2120 if *p != lock {
2121 rolling = crate::CHECKSUM_FLAG | (rolling ^ ltx::checksum_page(*p, d));
2122 }
2123 }
2124
2125 let header = ltx::Header {
2126 version: ltx::VERSION,
2127 flags: 0,
2128 page_size: self.page_size,
2129 commit,
2130 min_txid: TXID(1),
2131 max_txid: pos.txid,
2132 timestamp: self.host.now_unix_millis(),
2133 pre_apply_checksum: 0,
2134 wal_offset,
2135 wal_size: sz,
2136 wal_salt1: salt1,
2137 wal_salt2: salt2,
2138 node_id: 0,
2139 };
2140
2141 let encoded = ltx::encode_file(&header, &pages, rolling)?;
2142 w.write_all(&encoded)?;
2143
2144 Ok(Pos::new(pos.txid, rolling))
2145 }
2146
2147 /// Closes the database, releasing the read lock first so other processes can
2148 /// checkpoint. Ported from the read-lock-release + connection-close portion of
2149 /// `DB.Close` (db.go:623-647).
2150 pub fn close(mut self) -> Result<()> {
2151 self.release_read_lock()?;
2152 // The connection is dropped here, closing it.
2153 Ok(())
2154 }
2155}
2156
2157// ── free functions ─────────────────────────────────────────────────────────
2158
2159/// Returns the size of the WAL for a given page size & count, in i64 math to
2160/// avoid u32 overflow with large page sizes. Ported from `calcWALSize`
2161/// (db.go:1193-1197).
2162fn calc_wal_size(page_size: u32, page_n: u32) -> i64 {
2163 WAL_HEADER_SIZE as i64 + (WAL_FRAME_HEADER_SIZE as i64 + page_size as i64) * page_n as i64
2164}
2165
2166/// `true` if the error indicates an SQLITE_BUSY condition. Ported from
2167/// `isSQLiteBusyError` (db.go:1158-1167). Matches both the rusqlite busy code and
2168/// the Go substrings.
2169fn is_sqlite_busy_error(err: &Error) -> bool {
2170 // Prefer matching the rusqlite error code when present.
2171 if let Error::Other(b) = err {
2172 if let Some(re) = b.downcast_ref::<rusqlite::Error>() {
2173 if let Some(code) = re.sqlite_error_code() {
2174 if code == rusqlite::ErrorCode::DatabaseBusy
2175 || code == rusqlite::ErrorCode::DatabaseLocked
2176 {
2177 return true;
2178 }
2179 }
2180 }
2181 }
2182 let s = err.to_string();
2183 s.contains("database is locked") || s.contains("SQLITE_BUSY")
2184}
2185
2186/// `true` if the error indicates disk space issues (ENOSPC/EDQUOT). Ported from
2187/// `isDiskFullError` (db.go:1169-1180) — case-insensitive substring
2188/// match for parity with the Go table. This classifier matches the background
2189/// monitor's disk-full temporary-file cleanup behavior (db.go:2304-2309).
2190#[cfg_attr(not(test), allow(dead_code))]
2191fn is_disk_full_error(err_msg: &str) -> bool {
2192 let s = err_msg.to_lowercase();
2193 s.contains("no space left on device")
2194 || s.contains("disk quota exceeded")
2195 || s.contains("enospc")
2196 || s.contains("edquot")
2197}
2198
2199/// Rolls back the connection's current transaction, swallowing the
2200/// "already rolled back" / "no transaction is active" errors (issue #934).
2201/// Ported from `rollback` (litestream.go:130-135), adapted to rusqlite's message.
2202fn rollback(conn: &Connection) -> Result<()> {
2203 match conn
2204 .prepare_cached("ROLLBACK")
2205 .and_then(|mut statement| statement.execute([]).map(|_| ()))
2206 {
2207 Ok(()) => Ok(()),
2208 Err(e) => {
2209 let msg = e.to_string();
2210 // Go swallows "transaction has already been committed or rolled back".
2211 // rusqlite/SQLite reports "cannot rollback - no transaction is active".
2212 if msg.contains("transaction has already been committed or rolled back")
2213 || msg.contains("no transaction is active")
2214 || msg.contains("cannot rollback")
2215 {
2216 Ok(())
2217 } else {
2218 Err(sql_err(e))
2219 }
2220 }
2221 }
2222}
2223
2224/// Reads the 32-byte WAL header. Ported from `readWALHeader`
2225/// (litestream.go:138-148): returns the header bytes; errors if the file is
2226/// missing or shorter than 32 bytes.
2227fn read_wal_header(host: &crate::LtxHost, path: &Path) -> Result<[u8; WAL_HEADER_SIZE]> {
2228 let mut file = host.open(path)?;
2229 let bytes = file.read_exact_at(0, WAL_HEADER_SIZE)?;
2230 Ok(bytes
2231 .try_into()
2232 .expect("the exact read has the header size"))
2233}
2234
2235/// Reads one page's worth of bytes from an in-memory WAL buffer at the frame
2236/// `offset` (the offset is the start of the *frame header*; the page data follows
2237/// the 24-byte frame header). Mirrors `walFile.ReadAt(data, offset+WALFrameHeaderSize)`
2238/// (db.go:1745,1787).
2239/// What one sync read of the WAL: the whole file (`tail_base` 0), or the
2240/// 32-byte header followed by the file's bytes from `tail_base` onward.
2241/// Offsets stay absolute at every consumer; the image maps them.
2242struct WalImage {
2243 bytes: Vec<u8>,
2244 tail_base: usize,
2245 file_len: usize,
2246}
2247
2248impl WalImage {
2249 fn whole(bytes: Vec<u8>) -> Self {
2250 let file_len = bytes.len();
2251 Self {
2252 bytes,
2253 tail_base: 0,
2254 file_len,
2255 }
2256 }
2257
2258 /// A reader positioned at `offset`, over whichever shape this image has.
2259 fn reader_at(
2260 &self,
2261 offset: i64,
2262 salt1: u32,
2263 salt2: u32,
2264 ) -> std::result::Result<WalReader<'_>, crate::wal::WalError> {
2265 if self.tail_base == 0 {
2266 WalReader::new_with_offset(&self.bytes, offset, salt1, salt2)
2267 } else {
2268 WalReader::new_with_offset_over_tail(
2269 &self.bytes,
2270 self.tail_base as i64,
2271 offset,
2272 salt1,
2273 salt2,
2274 )
2275 }
2276 }
2277
2278 /// `n` bytes at absolute file `offset`, or `None` when the image does not
2279 /// hold them (a short read, or the gap between the header and the tail).
2280 fn slice(&self, offset: i64, n: usize) -> Option<&[u8]> {
2281 if offset < 0 {
2282 return None;
2283 }
2284 let offset = offset as usize;
2285 let start = if self.tail_base == 0 || offset < WAL_HEADER_SIZE {
2286 offset
2287 } else {
2288 WAL_HEADER_SIZE + offset.checked_sub(self.tail_base)?
2289 };
2290 let end = start.checked_add(n)?;
2291 (end <= self.bytes.len()).then(|| &self.bytes[start..end])
2292 }
2293
2294 /// One page's worth of bytes at frame `offset` (the offset is the start of
2295 /// the *frame header*; the page data follows it).
2296 fn page(&self, offset: i64, page_size: u32) -> Result<Vec<u8>> {
2297 self.slice(offset + WAL_FRAME_HEADER_SIZE as i64, page_size as usize)
2298 .map(<[u8]>::to_vec)
2299 .ok_or_else(|| {
2300 Error::Io(std::io::Error::new(
2301 std::io::ErrorKind::UnexpectedEof,
2302 format!("short read wal page @ {offset}"),
2303 ))
2304 })
2305 }
2306}
2307
2308/// Writes `data` to `tmp_path`, fsyncs, then renames to `final_path` — the
2309/// crash-consistent atomic-write idiom. On any failure the temp
2310/// file is removed.
2311fn write_file_atomic(
2312 host: &crate::LtxHost,
2313 tmp_path: &str,
2314 final_path: &str,
2315 data: &[u8],
2316) -> Result<u64> {
2317 let result = (|| -> Result<u64> {
2318 let mut file = host.create(Path::new(tmp_path))?;
2319 file.write_all(data)?;
2320 let fsync = crate::host::telemetry_us();
2321 file.sync_all()?;
2322 let fsync_us = crate::host::telemetry_us().saturating_sub(fsync);
2323 drop(file);
2324 host.rename(Path::new(tmp_path), Path::new(final_path))?;
2325 Ok(fsync_us)
2326 })();
2327 if result.is_err() {
2328 let _ = host.remove_file(Path::new(tmp_path));
2329 }
2330 result
2331}
2332
2333/// Recursively removes `.tmp` files under `root`. Ported from `removeTmpFiles`
2334/// (litestream.go:169-182): missing root / errored entries are skipped.
2335fn remove_tmp_files(host: &crate::LtxHost, root: &Path) -> Result<()> {
2336 fn walk(host: &crate::LtxHost, dir: &Path) {
2337 let entries = match host.read_dir(dir) {
2338 Ok(e) => e,
2339 Err(_) => return,
2340 };
2341 for ent in entries {
2342 let path = ent.path;
2343 if ent.is_dir {
2344 walk(host, &path);
2345 } else if path.extension().and_then(|e| e.to_str()) == Some("tmp") {
2346 let _ = host.remove_file(&path);
2347 }
2348 }
2349 }
2350 walk(host, root);
2351 Ok(())
2352}
2353
2354fn system_time_from_unix_millis(milliseconds: i64) -> SystemTime {
2355 if milliseconds >= 0 {
2356 UNIX_EPOCH + Duration::from_millis(milliseconds as u64)
2357 } else {
2358 UNIX_EPOCH - Duration::from_millis(milliseconds.unsigned_abs())
2359 }
2360}
2361
2362/// Big-endian `u32` from the first four bytes of `b`.
2363#[inline]
2364fn be_u32(b: &[u8]) -> u32 {
2365 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
2366}
2367
2368#[doc(hidden)]
2369pub mod internal {
2370 /// Returns active lookaside slots while SQLite compiles a statement on
2371 /// each connection owned by the managed database.
2372 pub fn lookaside_used_while_preparing(db: &super::Db) -> super::Result<(i32, i32)> {
2373 fn current(conn: &rusqlite::Connection) -> super::Result<i32> {
2374 let mut statement = std::ptr::null_mut();
2375 // SAFETY: the connection is live, SQLite owns the prepared
2376 // statement until the matching finalize, and the SQL includes its
2377 // trailing NUL.
2378 let result = unsafe {
2379 rusqlite::ffi::sqlite3_prepare_v2(
2380 conn.handle(),
2381 c"SELECT 1".as_ptr(),
2382 -1,
2383 &mut statement,
2384 std::ptr::null_mut(),
2385 )
2386 };
2387 if result != rusqlite::ffi::SQLITE_OK {
2388 return Err(super::Error::Other(
2389 "failed to prepare lookaside probe".into(),
2390 ));
2391 }
2392
2393 let mut active = 0;
2394 let mut highwater = 0;
2395 // SAFETY: the connection and output pointers remain live for this
2396 // call. The status operation does not own either output value.
2397 let result = unsafe {
2398 rusqlite::ffi::sqlite3_db_status(
2399 conn.handle(),
2400 rusqlite::ffi::SQLITE_DBSTATUS_LOOKASIDE_USED,
2401 &mut active,
2402 &mut highwater,
2403 0,
2404 )
2405 };
2406 // SAFETY: prepare returned this statement exclusively to this
2407 // helper, including when the status operation fails.
2408 unsafe { rusqlite::ffi::sqlite3_finalize(statement) };
2409 if result != rusqlite::ffi::SQLITE_OK {
2410 return Err(super::Error::Other(
2411 "failed to read SQLite lookaside status".into(),
2412 ));
2413 }
2414 Ok(active)
2415 }
2416
2417 Ok((current(&db.conn)?, current(&db.rtx_conn)?))
2418 }
2419
2420 /// Counts SQL compilations on the capture's connections: SQLite runs the
2421 /// authorizer once per compilation, so the counter moves for a fresh
2422 /// `prepare` and for a re-prepare, and stays still for a cached statement.
2423 /// (Installing the authorizer expires the statements compiled so far, so
2424 /// the first sync after this call compiles once more.)
2425 pub fn count_sql_compilations(db: &super::Db) -> std::sync::Arc<std::sync::atomic::AtomicU64> {
2426 use rusqlite::hooks::{AuthContext, Authorization};
2427 let counter = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
2428 for conn in [&db.conn, &db.rtx_conn] {
2429 let counter = counter.clone();
2430 conn.authorizer(Some(move |_: AuthContext<'_>| {
2431 counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2432 Authorization::Allow
2433 }));
2434 }
2435 counter
2436 }
2437
2438 use super::*;
2439
2440 pub struct VerifyInfo {
2441 inner: SyncInfo,
2442 pub offset: i64,
2443 pub prev_commit: u32,
2444 pub snapshotting: bool,
2445 pub reason: String,
2446 }
2447
2448 pub fn calc_wal_size(page_size: u32, page_n: u32) -> i64 {
2449 super::calc_wal_size(page_size, page_n)
2450 }
2451
2452 pub fn is_sqlite_busy_error(error: &Error) -> bool {
2453 super::is_sqlite_busy_error(error)
2454 }
2455
2456 pub fn is_disk_full_error(message: &str) -> bool {
2457 super::is_disk_full_error(message)
2458 }
2459
2460 pub fn read_lock_held(db: &Db) -> bool {
2461 db.read_lock_held
2462 }
2463
2464 /// Run one `sync` with `hook` invoked between `verify` and the capture
2465 /// read — the only window in which a WAL change can reach the
2466 /// previous-frame check without `verify` seeing it first.
2467 pub fn sync_with_verify_hook(db: &mut Db, hook: impl FnOnce() + 'static) -> Result<()> {
2468 db.sync_with_verify_hook(Some(Box::new(hook)))
2469 }
2470
2471 pub fn wal_journal_mode(db: &Db) -> Result<String> {
2472 db.conn
2473 .query_row("PRAGMA journal_mode", [], |row| row.get(0))
2474 .map_err(sql_err)
2475 }
2476
2477 pub fn wal_autocheckpoint(db: &Db) -> Result<i64> {
2478 db.conn
2479 .query_row("PRAGMA wal_autocheckpoint", [], |row| row.get(0))
2480 .map_err(sql_err)
2481 }
2482
2483 /// The effective `PRAGMA cache_size` of the writer connection.
2484 pub fn writer_cache_size(db: &Db) -> Result<i64> {
2485 db.conn
2486 .query_row("PRAGMA cache_size", [], |row| row.get(0))
2487 .map_err(sql_err)
2488 }
2489
2490 pub fn read_lock_connection_cache_size(db: &Db) -> Result<i64> {
2491 db.rtx_conn
2492 .query_row("PRAGMA cache_size", [], |row| row.get(0))
2493 .map_err(sql_err)
2494 }
2495
2496 pub fn rollback_read_lock_connection(db: &Db) -> Result<()> {
2497 db.rtx_conn.execute_batch("ROLLBACK").map_err(sql_err)
2498 }
2499
2500 pub fn release_read_lock(db: &mut Db) -> Result<()> {
2501 db.release_read_lock()
2502 }
2503
2504 pub fn acquire_read_lock(db: &mut Db) -> Result<()> {
2505 db.acquire_read_lock()
2506 }
2507
2508 pub fn verify(db: &mut Db) -> Result<VerifyInfo> {
2509 let inner = db.verify()?;
2510 Ok(VerifyInfo {
2511 offset: inner.offset,
2512 prev_commit: inner.prev_commit,
2513 snapshotting: inner.snapshotting,
2514 reason: inner.reason.clone(),
2515 inner,
2516 })
2517 }
2518
2519 pub fn sync_inner(db: &mut Db, info: VerifyInfo) -> Result<bool> {
2520 db.sync_inner(info.inner)
2521 }
2522
2523 pub fn read_wal_header(db: &Db) -> Result<[u8; WAL_HEADER_SIZE]> {
2524 super::read_wal_header(&db.host, &db.wal_path())
2525 }
2526
2527 pub fn invalidate_pos_cache(db: &mut Db) {
2528 db.invalidate_pos_cache();
2529 }
2530
2531 pub fn ltx_level_dir(db: &Db, level: u32) -> String {
2532 db.ltx_level_dir(level)
2533 }
2534
2535 pub fn checkpoint_passive_with_barrier_hook(
2536 db: &mut Db,
2537 hook: Box<dyn FnOnce() + Send>,
2538 ) -> Result<()> {
2539 db.checkpoint_with_passive_hooks(CheckpointMode::Passive, Some(hook), None, None)
2540 }
2541
2542 pub fn checkpoint_passive_with_unlocked_hook(
2543 db: &mut Db,
2544 hook: Box<dyn FnOnce() + Send>,
2545 ) -> Result<()> {
2546 db.checkpoint_with_passive_hooks(CheckpointMode::Passive, None, Some(hook), None)
2547 }
2548
2549 /// Run a passive checkpoint with `hook` invoked after the writer barrier
2550 /// dropped and before the sealing write: the window in which another
2551 /// writer can take the lock and restart the WAL itself.
2552 pub fn checkpoint_passive_with_post_barrier_hook(
2553 db: &mut Db,
2554 hook: Box<dyn FnOnce() + Send>,
2555 ) -> Result<()> {
2556 db.checkpoint_with_passive_hooks(CheckpointMode::Passive, None, None, Some(hook))
2557 }
2558
2559 pub fn be_u32(bytes: &[u8]) -> u32 {
2560 super::be_u32(bytes)
2561 }
2562}