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