Diffinery

homeflare/celldpublic

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