Diffinery

homeflare/celldpublic

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