| 1 | //! replica.rs — single-replica sync loop + restore orchestration. |
| 2 | //! Ported from [email protected] `replica.go`. |
| 3 | //! |
| 4 | //! A [`Replica`] connects a managed [`crate::db::Db`] to a replication |
| 5 | //! destination via a [`ReplicaClient`]. It drives two halves of replication: |
| 6 | //! |
| 7 | //! * **sync** (`replica.go:132-180`): copy each new L0 LTX file the capture loop |
| 8 | //! wrote locally up to the remote replica, advancing the replicated position |
| 9 | //! one TXID at a time. `calc_pos` (`replica.go:208-214`) recovers the starting |
| 10 | //! position from the newest file already on the replica. |
| 11 | //! * **restore** (`replica.go:533-725`): download the LTX files from the replica |
| 12 | //! in TXID order, merge them (the compactor in `ltx.NewCompactor`, |
| 13 | //! [email protected] compactor.go), and reconstruct the SQLite database file the way |
| 14 | //! `Decoder.DecodeDatabaseTo` ([email protected] decoder.go:223-268) does — pages |
| 15 | //! `1..=commit`, lock page zero-filled, written verbatim — to a temp file that |
| 16 | //! is fsync'd and atomically renamed into place. |
| 17 | //! |
| 18 | //! ## Scope (KEEP set, PLAN.md §2 / D-7): L0-only, single replica |
| 19 | //! The real `litestream v0.5.11` L0-only architecture stores **everything at |
| 20 | //! level 0** — the snapshot (MinTXID==1) and every incremental — under |
| 21 | //! `ltx/0/` (verified against `tests/fixtures/golden/replica`, captured from |
| 22 | //! `litestream replicate -once`). The snapshot level (`SnapshotLevel = 9`, |
| 23 | //! compaction_level.go:9) is empty without compaction. [`calc_restore_plan`] is |
| 24 | //! ported faithfully (snapshot anchor at `SnapshotLevel` + per-level cursors so |
| 25 | //! adding compaction later "just works"), but in this scope the plan is the |
| 26 | //! contiguous L0 chain `1..=N`. |
| 27 | //! |
| 28 | //! ## Deferred (logged in OPEN_QUESTIONS.md — need the background runtime / extra |
| 29 | //! scope, NOT on the G2 round-trip path): |
| 30 | //! * **Follow mode** (`replica.go:730-987`, `applyLTXFile`/`fillFollowGap`): the |
| 31 | //! continuous tail-restore loop. The one-shot G2 gate is a single restore. |
| 32 | //! * **The background monitor goroutine + backoff** (`replica.go:326-441`, |
| 33 | //! footgun F-13) and `Start`/`Stop`: need a Tokio task owning the `Db`; the |
| 34 | //! synchronous `sync()` primitive it would call is implemented and tested here. |
| 35 | //! * **V3 (v0.3.x generation) restore** (`RestoreV3`, replica.go:990-1096): |
| 36 | //! DROPPED (PLAN.md §2 — greenfield, nothing to be backward-compatible with). |
| 37 | //! * **Timestamp / `-txid` targeted restore plumbing through the public API**: |
| 38 | //! [`calc_restore_plan`] honors a target TXID (used by tests), but the |
| 39 | //! timestamp path and `RestoreOptions` surface stay minimal for the one-shot. |
| 40 | |
| 41 | use crate::client::ReplicaClient; |
| 42 | use crate::db::Db; |
| 43 | use crate::error::{new_ltx_error, Error, Result}; |
| 44 | use crate::ltx::{self, FileInfo}; |
| 45 | use crate::{Pos, TXID}; |
| 46 | use std::collections::HashMap; |
| 47 | use std::path::{Path, PathBuf}; |
| 48 | |
| 49 | /// The compaction level which full snapshots are held at. |
| 50 | /// |
| 51 | /// Ported from `SnapshotLevel` (compaction_level.go:9). In the L0-only one-shot |
| 52 | /// scope no files land here (snapshots are written at L0), but |
| 53 | /// [`calc_restore_plan`] still probes it first so the algorithm stays a faithful |
| 54 | /// port that works the moment compaction is added. |
| 55 | pub const SNAPSHOT_LEVEL: i32 = 9; |
| 56 | |
| 57 | /// Whether a sync error means the cached replica position can no longer be |
| 58 | /// trusted and must be re-derived from the store on the next sync. |
| 59 | /// |
| 60 | /// True only for errors that say the local/replica state itself diverged. A |
| 61 | /// transient store or IO error is not one of these: a fenced single writer's |
| 62 | /// position is still valid, and its re-upload is an idempotent overwrite. See |
| 63 | /// [`Replica::sync`] for why celld narrows Litestream's clear-on-any-error. |
| 64 | fn pos_untrustworthy(err: &Error) -> bool { |
| 65 | matches!( |
| 66 | err, |
| 67 | Error::NoSnapshots |
| 68 | | Error::ChecksumMismatch |
| 69 | | Error::LTXCorrupted |
| 70 | | Error::LTXMissing |
| 71 | | Error::TxNotAvailable |
| 72 | ) |
| 73 | } |
| 74 | |
| 75 | /// Connects a database to a replication destination via a [`ReplicaClient`]. |
| 76 | /// |
| 77 | /// Ported from `Replica` (replica.go:30-59). The Go type also owns the |
| 78 | /// background-monitor machinery (`wg`/`cancel`/`f`) and tunables |
| 79 | /// (`SyncInterval`/`MonitorEnabled`); those drive the deferred monitor loop and |
| 80 | /// are intentionally omitted here (see module docs). `auto_recover_enabled` |
| 81 | /// mirrors `AutoRecoverEnabled` (replica.go:58) for the monitor's |
| 82 | /// reset-on-corruption path. |
| 83 | pub struct Replica<C: ReplicaClient> { |
| 84 | /// The database being replicated. `None` for a restore-only replica (the Go |
| 85 | /// `NewReplicaWithClient(nil, client)` shape used by the restore tests). |
| 86 | db: Option<Db>, |
| 87 | |
| 88 | /// Client used to connect to the remote replica. |
| 89 | pub client: C, |
| 90 | |
| 91 | /// Current replicated position (`replica.go:33-34` `pos`). |
| 92 | pos: Pos, |
| 93 | |
| 94 | /// Whether `pos` is known and needs no `calc_pos` listing to re-derive. |
| 95 | /// Seeded true at activation (see [`Self::seed_pos`]); reset false only when |
| 96 | /// a divergence error says the position can no longer be trusted. Upstream |
| 97 | /// has no equivalent -- it lists whenever `pos` is zero -- which is the |
| 98 | /// listing celld's fencing lets it skip. |
| 99 | pos_known: bool, |
| 100 | |
| 101 | /// If true, automatically reset local state when LTX errors are detected |
| 102 | /// (`replica.go:54-58` `AutoRecoverEnabled`). Consulted by the deferred |
| 103 | /// monitor loop; the field is kept so the public surface matches upstream. |
| 104 | pub auto_recover_enabled: bool, |
| 105 | } |
| 106 | |
| 107 | impl<C: ReplicaClient> Replica<C> { |
| 108 | /// Creates a replica that owns `db` and replicates through `client`. |
| 109 | /// |
| 110 | /// Ported from `NewReplicaWithClient` (replica.go:73-77). |
| 111 | pub fn new(db: Db, client: C) -> Self { |
| 112 | Replica { |
| 113 | db: Some(db), |
| 114 | client, |
| 115 | pos: Pos::ZERO, |
| 116 | pos_known: false, |
| 117 | auto_recover_enabled: false, |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// Creates a restore-only replica with no attached database (Go's |
| 122 | /// `NewReplicaWithClient(nil, client)`). |
| 123 | pub fn new_client_only(client: C) -> Self { |
| 124 | Replica { |
| 125 | db: None, |
| 126 | client, |
| 127 | pos: Pos::ZERO, |
| 128 | pos_known: false, |
| 129 | auto_recover_enabled: false, |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// Returns a reference to the attached database, if any. |
| 134 | /// Ported from `Replica.DB` (replica.go:89). |
| 135 | pub fn db(&self) -> Option<&Db> { |
| 136 | self.db.as_ref() |
| 137 | } |
| 138 | |
| 139 | /// Consumes the replica and returns the attached database, if any. Lets a |
| 140 | /// host perform a clean [`Db::close`] (which consumes the `Db`) after a final |
| 141 | /// sync — the shutdown ordering the deferred monitor loop would otherwise own |
| 142 | /// (replica.go `Stop` → `db.Close`). |
| 143 | pub fn into_db(self) -> Option<Db> { |
| 144 | self.db |
| 145 | } |
| 146 | |
| 147 | /// Returns a mutable reference to the attached database, if any. Lets a |
| 148 | /// caller drive `db.sync()` (the local capture half) before `replica.sync()` |
| 149 | /// (the upload half) — the `SyncAndWait` ordering (db.go:500-512). |
| 150 | pub fn db_mut(&mut self) -> Option<&mut Db> { |
| 151 | self.db.as_mut() |
| 152 | } |
| 153 | |
| 154 | /// The current replicated position. Ported from `Replica.Pos` |
| 155 | /// (replica.go:237-241). |
| 156 | pub fn pos(&self) -> Pos { |
| 157 | self.pos |
| 158 | } |
| 159 | |
| 160 | /// Sets the current replicated position. Ported from `Replica.SetPos` |
| 161 | /// (replica.go:244-248). |
| 162 | fn set_pos(&mut self, pos: Pos) { |
| 163 | self.pos = pos; |
| 164 | } |
| 165 | |
| 166 | /// Seed the replicated position from the caller's known-durable state and |
| 167 | /// mark it known, so the next sync skips the `calc_pos` listing. A fresh |
| 168 | /// cell seeds 0; a just-restored cell seeds its restored max. celld always |
| 169 | /// knows this at activation -- local equals remote under epoch fencing -- |
| 170 | /// so the listing that only existed to re-discover the position, and that |
| 171 | /// storms a rate-limiting store, is not issued on the activation path. |
| 172 | pub fn seed_pos(&mut self, pos: Pos) { |
| 173 | self.pos = pos; |
| 174 | self.pos_known = true; |
| 175 | } |
| 176 | |
| 177 | /// Copies new L0 LTX files from the local capture directory to the replica. |
| 178 | /// |
| 179 | /// Ported from `Replica.Sync` (replica.go:132-180). On any error the cached |
| 180 | /// position is cleared so the next sync recomputes it from the replica |
| 181 | /// (replica.go:137-143). Requires an attached database. |
| 182 | pub async fn sync(&mut self) -> Result<()> { |
| 183 | match self.sync_inner().await { |
| 184 | Ok(()) => Ok(()), |
| 185 | Err(e) => { |
| 186 | // Litestream clears the cached position on *any* error so the |
| 187 | // next sync re-derives it with a `calc_pos` listing |
| 188 | // (replica.go:137-143) -- safe there only because it is single- |
| 189 | // node with no fencing. celld fences one writer per epoch |
| 190 | // through the store, so within an epoch a transient store/IO |
| 191 | // error does not invalidate our own position; re-uploads are |
| 192 | // idempotent overwrites. Forget the position only when the |
| 193 | // error says the state itself diverged, else a rate-limiting or |
| 194 | // slow store turns every write into a listing. |
| 195 | if pos_untrustworthy(&e) { |
| 196 | self.pos = Pos::ZERO; |
| 197 | self.pos_known = false; |
| 198 | } |
| 199 | Err(e) |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | async fn sync_inner(&mut self) -> Result<()> { |
| 205 | // Re-derive the replica position with a listing only when it is not |
| 206 | // already known (replica.go:146-152). celld seeds it at activation from |
| 207 | // local state that equals the remote under epoch fencing, so a listing |
| 208 | // -- which only ever re-discovered a position the owner already knows -- |
| 209 | // never runs on the hot path, and a fresh cell's pointless list of an |
| 210 | // empty prefix is skipped entirely. |
| 211 | if !self.pos_known { |
| 212 | let pos = self |
| 213 | .calc_pos() |
| 214 | .await |
| 215 | .map_err(|e| Error::Other(format!("calc pos: {e}").into()))?; |
| 216 | self.set_pos(pos); |
| 217 | self.pos_known = true; |
| 218 | } |
| 219 | |
| 220 | // Find current position of the database (replica.go:155-160). |
| 221 | let dpos = { |
| 222 | let db = self |
| 223 | .db |
| 224 | .as_mut() |
| 225 | .ok_or_else(|| Error::Other("no database attached to replica".into()))?; |
| 226 | db.pos().map_err(|e| { |
| 227 | Error::Other(format!("cannot determine current position: {e}").into()) |
| 228 | })? |
| 229 | }; |
| 230 | if dpos.is_zero() { |
| 231 | return Err(Error::Other("no position, waiting for data".into())); |
| 232 | } |
| 233 | |
| 234 | // Replicate all L0 LTX files since the last replica position |
| 235 | // (replica.go:169-174). Each successful upload advances pos by one TXID; |
| 236 | // re-reading `self.pos()` each iteration mirrors the Go loop exactly. |
| 237 | loop { |
| 238 | let tx_id = TXID(self.pos().txid.0 + 1); |
| 239 | if tx_id > dpos.txid { |
| 240 | break; |
| 241 | } |
| 242 | self.upload_ltx_file(0, tx_id, tx_id).await?; |
| 243 | self.set_pos(Pos::new(tx_id, 0)); |
| 244 | } |
| 245 | |
| 246 | Ok(()) |
| 247 | } |
| 248 | |
| 249 | /// Uploads a single local LTX file to the replica. |
| 250 | /// |
| 251 | /// Ported from `Replica.uploadLTXFile` (replica.go:182-205). A failure to |
| 252 | /// open the local file is wrapped as an `LTXError{op:"open"}` so the monitor |
| 253 | /// can classify auto-recoverable corruption (replica.go:186). The write |
| 254 | /// itself is delegated to the client. |
| 255 | async fn upload_ltx_file(&mut self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<()> { |
| 256 | let db = self |
| 257 | .db |
| 258 | .as_ref() |
| 259 | .ok_or_else(|| Error::Other("no database attached to replica".into()))?; |
| 260 | let filename = db.ltx_path(level as u32, min_txid, max_txid); |
| 261 | |
| 262 | let data = match std::fs::read(&filename) { |
| 263 | Ok(b) => b, |
| 264 | Err(e) => { |
| 265 | return Err(Error::Ltx(Box::new(new_ltx_error( |
| 266 | "open", |
| 267 | &filename, |
| 268 | level, |
| 269 | min_txid.0, |
| 270 | max_txid.0, |
| 271 | e.into(), |
| 272 | )))); |
| 273 | } |
| 274 | }; |
| 275 | |
| 276 | self.client |
| 277 | .write_ltx_file(level, min_txid, max_txid, &data) |
| 278 | .await |
| 279 | .map_err(|e| Error::Other(format!("write ltx file: {e}").into()))?; |
| 280 | |
| 281 | Ok(()) |
| 282 | } |
| 283 | |
| 284 | /// Returns the last position saved to the replica for level 0. |
| 285 | /// |
| 286 | /// Ported from `Replica.calcPos` (replica.go:208-214) + `MaxLTXFileInfo` |
| 287 | /// (replica.go:218-233): scans the L0 listing for the highest `max_txid`. |
| 288 | async fn calc_pos(&self) -> Result<Pos> { |
| 289 | let info = self |
| 290 | .max_ltx_file_info(0) |
| 291 | .await |
| 292 | .map_err(|e| Error::Other(format!("max ltx file: {e}").into()))?; |
| 293 | Ok(Pos::new(info.max_txid, info.post_apply_checksum)) |
| 294 | } |
| 295 | |
| 296 | /// Metadata about the last LTX file for a given level (highest `max_txid`), |
| 297 | /// or a zero `FileInfo` if none exist. Ported from `Replica.MaxLTXFileInfo` |
| 298 | /// (replica.go:218-233). |
| 299 | async fn max_ltx_file_info(&self, level: i32) -> Result<FileInfo> { |
| 300 | let files = self.client.ltx_files(level, TXID(0), false).await?; |
| 301 | let mut info = FileInfo::default(); |
| 302 | for item in files { |
| 303 | if item.max_txid > info.max_txid { |
| 304 | info = item; |
| 305 | } |
| 306 | } |
| 307 | Ok(info) |
| 308 | } |
| 309 | |
| 310 | /// Restores the database from this replica's client into `output_path`. |
| 311 | /// |
| 312 | /// Convenience wrapper over [`restore`] using this replica's client and the |
| 313 | /// most-recent state (no target TXID). Mirrors the common |
| 314 | /// `Replica.Restore(ctx, opt)` call with `OutputPath` set and no TXID |
| 315 | /// (replica.go:533). |
| 316 | pub async fn restore(&self, output_path: impl AsRef<Path>) -> Result<()> { |
| 317 | restore(&self.client, output_path, TXID(0)).await |
| 318 | } |
| 319 | |
| 320 | /// Detects when the local database has been restored to an earlier state |
| 321 | /// than the replica (a lower TXID) and, if so, seeds the local L0 directory |
| 322 | /// with the replica's newest L0 file so the next sync snapshots forward. |
| 323 | /// |
| 324 | /// Ported from `DB.checkDatabaseBehindReplica` (db.go:1211-1294), issue #781. |
| 325 | /// In upstream this runs inside `DB.init()` because the `DB` owns its |
| 326 | /// `Replica`; our synchronous `Db` does not, so the orchestration lives here |
| 327 | /// on `Replica` and a host calls it once after [`Db::open`], before the first |
| 328 | /// sync. The file-writing tail is [`Db::seed_l0_baseline`]. |
| 329 | /// |
| 330 | /// Without this, a hard recovery (restore an old snapshot, reopen, write new |
| 331 | /// data) would silently drop the new writes: the fresh local DB snapshots at |
| 332 | /// TXID 1, but [`Replica::sync`] computes the replica position from the |
| 333 | /// remote's higher `MaxTXID`, so its upload loop (`pos+1 ..= db.pos`) never |
| 334 | /// runs (`pos+1` already exceeds the local DB's TXID). Seeding the remote |
| 335 | /// baseline makes the next [`Db::sync`] see a continuity break and snapshot at |
| 336 | /// the current (post-restore-plus-writes) state, which then uploads. |
| 337 | /// |
| 338 | /// No-op (returns `Ok`) when there is no remote data, when the database is at |
| 339 | /// or ahead of the replica, or when there is no attached database. |
| 340 | pub async fn check_database_behind_replica(&mut self) -> Result<()> { |
| 341 | // Replica position from remote (db.go:1224-1230). Done first so a |
| 342 | // restore-only replica with no DB is a clean no-op. |
| 343 | let replica_info = self.max_ltx_file_info(0).await?; |
| 344 | if replica_info.max_txid == TXID(0) { |
| 345 | return Ok(()); // no remote replica data yet |
| 346 | } |
| 347 | |
| 348 | let db = match self.db.as_mut() { |
| 349 | Some(db) => db, |
| 350 | None => return Ok(()), |
| 351 | }; |
| 352 | |
| 353 | // Database position from local L0 files (db.go:1218-1222). |
| 354 | let db_pos = db |
| 355 | .pos() |
| 356 | .map_err(|e| Error::Other(format!("get database position: {e}").into()))?; |
| 357 | |
| 358 | // If the database is ahead or equal, nothing to do (db.go:1232-1235). |
| 359 | if db_pos.txid >= replica_info.max_txid { |
| 360 | return Ok(()); |
| 361 | } |
| 362 | |
| 363 | // Fetch the latest L0 LTX file from the replica (db.go:1251-1257). |
| 364 | let min_txid = replica_info.min_txid; |
| 365 | let max_txid = replica_info.max_txid; |
| 366 | let data = self |
| 367 | .client |
| 368 | .open_ltx_file(0, min_txid, max_txid, 0, 0) |
| 369 | .await |
| 370 | .map_err(|e| Error::Other(format!("open remote L0 file: {e}").into()))?; |
| 371 | |
| 372 | // Seed it as the local baseline (db.go:1259-1293). |
| 373 | db.seed_l0_baseline(min_txid, max_txid, &data)?; |
| 374 | |
| 375 | // Drop the now-stale cached replica position so the next sync recomputes |
| 376 | // it from the remote (mirrors clearing pos on a state change). |
| 377 | self.pos = Pos::ZERO; |
| 378 | Ok(()) |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// Restores a database from `client` into `output_path`, optionally up to a |
| 383 | /// target `txid` (`TXID(0)` = most recent state). |
| 384 | /// |
| 385 | /// Ported from `Replica.Restore` (replica.go:533-725), LTX path only. Steps: |
| 386 | /// 1. refuse to overwrite an existing output (replica.go:591-595); |
| 387 | /// 2. [`calc_restore_plan`] → the ordered snapshot+incremental file list; |
| 388 | /// 3. download + merge them (compactor semantics) and reconstruct the database |
| 389 | /// image the way `Decoder.DecodeDatabaseTo` does; |
| 390 | /// 4. write to `<output>.tmp`, fsync, and atomically rename (replica.go:657-694). |
| 391 | /// |
| 392 | /// The V3 generation path and follow mode are out of scope (see module docs). |
| 393 | pub async fn restore<C: ReplicaClient>( |
| 394 | client: &C, |
| 395 | output_path: impl AsRef<Path>, |
| 396 | txid: TXID, |
| 397 | ) -> Result<()> { |
| 398 | let output_path = output_path.as_ref(); |
| 399 | |
| 400 | // Ensure output path does not already exist (replica.go:591-595). |
| 401 | match std::fs::metadata(output_path) { |
| 402 | Ok(_) => { |
| 403 | return Err(Error::Other( |
| 404 | format!( |
| 405 | "cannot restore, output path already exists: {}", |
| 406 | output_path.display() |
| 407 | ) |
| 408 | .into(), |
| 409 | )); |
| 410 | } |
| 411 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 412 | Err(e) => return Err(e.into()), |
| 413 | } |
| 414 | |
| 415 | // Build the restore plan (replica.go:611). |
| 416 | let infos = calc_restore_plan(client, txid).await?; |
| 417 | |
| 418 | // Download every planned file's bytes, in plan order (replica.go:627-642). |
| 419 | // Validate each is at least header-sized first (replica.go:628-632). |
| 420 | let mut files: Vec<Vec<u8>> = Vec::with_capacity(infos.len()); |
| 421 | for info in &infos { |
| 422 | if info.size < ltx::HEADER_SIZE as i64 { |
| 423 | return Err(Error::Other( |
| 424 | format!( |
| 425 | "invalid ltx file: level={} min={} max={} has size {} bytes (minimum {})", |
| 426 | info.level, |
| 427 | info.min_txid, |
| 428 | info.max_txid, |
| 429 | info.size, |
| 430 | ltx::HEADER_SIZE |
| 431 | ) |
| 432 | .into(), |
| 433 | )); |
| 434 | } |
| 435 | let data = client |
| 436 | .open_ltx_file(info.level, info.min_txid, info.max_txid, 0, 0) |
| 437 | .await |
| 438 | .map_err(|e| Error::Other(format!("open ltx file: {e}").into()))?; |
| 439 | files.push(data); |
| 440 | } |
| 441 | |
| 442 | if files.is_empty() { |
| 443 | return Err(Error::Other("no matching backup files available".into())); |
| 444 | } |
| 445 | |
| 446 | // Merge the files (compactor) and reconstruct the SQLite database image. |
| 447 | let image = build_database_image(&files)?; |
| 448 | |
| 449 | // Create the parent directory if needed (replica.go:649-655). |
| 450 | if let Some(parent) = output_path.parent() { |
| 451 | if !parent.as_os_str().is_empty() { |
| 452 | std::fs::create_dir_all(parent)?; |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | // Output to a temp file & atomically rename (replica.go:657-694). |
| 457 | let tmp_output_path = append_ext(output_path, "tmp"); |
| 458 | write_file_atomic(&tmp_output_path, output_path, &image)?; |
| 459 | |
| 460 | Ok(()) |
| 461 | } |
| 462 | |
| 463 | /// Returns the ordered list of LTX files needed to restore the database at |
| 464 | /// `txid` (`TXID(0)` = latest). |
| 465 | /// |
| 466 | /// Ported from `CalcRestorePlan` (replica.go:1419-1536). Anchors on the latest |
| 467 | /// snapshot at or before the target, then walks compaction levels |
| 468 | /// `SnapshotLevel-1 ..= 0` with per-level cursors, repeatedly choosing the file |
| 469 | /// that extends the longest contiguous TXID range. In the L0-only scope the |
| 470 | /// snapshot anchor lives at L0 (MinTXID==1) and the only cursor with files is |
| 471 | /// level 0, so the result is the contiguous chain `1..=N` (capped at `txid`). |
| 472 | pub async fn calc_restore_plan<C: ReplicaClient>(client: &C, txid: TXID) -> Result<Vec<FileInfo>> { |
| 473 | let mut infos: Vec<FileInfo> = Vec::new(); |
| 474 | |
| 475 | // Start with the latest snapshot before the target TXID (replica.go:1430-1452). |
| 476 | let snapshot_files = client.ltx_files(SNAPSHOT_LEVEL, TXID(0), false).await?; |
| 477 | let mut snapshot: Option<FileInfo> = None; |
| 478 | for info in snapshot_files { |
| 479 | if txid != TXID(0) && info.max_txid > txid { |
| 480 | continue; |
| 481 | } |
| 482 | snapshot = Some(info); |
| 483 | } |
| 484 | if let Some(s) = snapshot { |
| 485 | infos.push(s); |
| 486 | } |
| 487 | |
| 488 | // Collect candidates across all compaction levels and pick the next file |
| 489 | // from any level that extends the longest contiguous TXID range |
| 490 | // (replica.go:1454-1515). |
| 491 | let max_level = SNAPSHOT_LEVEL - 1; |
| 492 | let start_txid = slice_max_txid(&infos); |
| 493 | let mut current_max = start_txid; |
| 494 | if txid != TXID(0) && current_max >= txid { |
| 495 | return Ok(infos); |
| 496 | } |
| 497 | |
| 498 | // Build a cursor per level, highest level first (replica.go:1463-1473). |
| 499 | let mut cursors: Vec<RestoreLevelCursor> = Vec::with_capacity((max_level + 1) as usize); |
| 500 | for level in (0..=max_level).rev() { |
| 501 | let files = client.ltx_files(level, TXID(0), false).await?; |
| 502 | cursors.push(RestoreLevelCursor::new(files)); |
| 503 | } |
| 504 | |
| 505 | loop { |
| 506 | // Choose the best candidate across all level cursors (replica.go:1483-1494). |
| 507 | let mut next_idx: Option<usize> = None; |
| 508 | for i in 0..cursors.len() { |
| 509 | cursors[i].refresh(current_max, txid); |
| 510 | if cursors[i].candidate.is_none() { |
| 511 | continue; |
| 512 | } |
| 513 | match next_idx { |
| 514 | None => next_idx = Some(i), |
| 515 | Some(ni) => { |
| 516 | let cand = cursors[i].candidate.as_ref().unwrap(); |
| 517 | let best = cursors[ni].candidate.as_ref().unwrap(); |
| 518 | if restore_candidate_better(best, cand) { |
| 519 | next_idx = Some(i); |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | let ni = match next_idx { |
| 526 | Some(ni) => ni, |
| 527 | None => break, |
| 528 | }; |
| 529 | |
| 530 | // Take the chosen candidate (replica.go:1500-1510). |
| 531 | let cand = cursors[ni].candidate.take().unwrap(); |
| 532 | if cand.max_txid <= current_max { |
| 533 | continue; |
| 534 | } |
| 535 | current_max = cand.max_txid; |
| 536 | infos.push(cand); |
| 537 | |
| 538 | if txid != TXID(0) && current_max >= txid { |
| 539 | break; |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | // For a latest/most-recent restore, verify the tail is contiguous |
| 544 | // (replica.go:1517-1526). |
| 545 | if !infos.is_empty() && txid == TXID(0) { |
| 546 | for cursor in cursors.iter_mut() { |
| 547 | cursor.ensure_current(); |
| 548 | if let Some(cur) = &cursor.current { |
| 549 | if cur.min_txid.0 > current_max.0 + 1 { |
| 550 | return Err(Error::Other( |
| 551 | format!( |
| 552 | "non-contiguous ltx files: have up to {} but next file starts at {}", |
| 553 | current_max, cur.min_txid |
| 554 | ) |
| 555 | .into(), |
| 556 | )); |
| 557 | } |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | if infos.is_empty() { |
| 563 | return Err(Error::TxNotAvailable); |
| 564 | } |
| 565 | if txid != TXID(0) && slice_max_txid(&infos) < txid { |
| 566 | return Err(Error::TxNotAvailable); |
| 567 | } |
| 568 | |
| 569 | Ok(infos) |
| 570 | } |
| 571 | |
| 572 | /// A single level's streaming view during restore planning. |
| 573 | /// |
| 574 | /// Ported from `restoreLevelCursor` (replica.go:1538-1603). The Go version |
| 575 | /// streams from a `FileIterator`; here the client already returns a sorted |
| 576 | /// `Vec<FileInfo>`, so the "iterator" is the slice plus a read index. |
| 577 | struct RestoreLevelCursor { |
| 578 | /// Files for this level, sorted ascending (the `LTXFiles` contract). |
| 579 | files: Vec<FileInfo>, |
| 580 | /// Read index into `files` (the iterator cursor). |
| 581 | idx: usize, |
| 582 | /// Last item read but not yet evaluated (`current`, replica.go:1542). |
| 583 | current: Option<FileInfo>, |
| 584 | /// Best eligible file at this level for the current `current_max` |
| 585 | /// (`candidate`, replica.go:1544). |
| 586 | candidate: Option<FileInfo>, |
| 587 | /// True once the iterator is exhausted (`done`, replica.go:1546). |
| 588 | done: bool, |
| 589 | } |
| 590 | |
| 591 | impl RestoreLevelCursor { |
| 592 | fn new(files: Vec<FileInfo>) -> Self { |
| 593 | RestoreLevelCursor { |
| 594 | files, |
| 595 | idx: 0, |
| 596 | current: None, |
| 597 | candidate: None, |
| 598 | done: false, |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | /// Advances the iterator while files could be contiguous with `current_max`, |
| 603 | /// keeping the best eligible candidate. Ported from `refresh` |
| 604 | /// (replica.go:1549-1587). |
| 605 | fn refresh(&mut self, current_max: TXID, txid: TXID) { |
| 606 | if self.done { |
| 607 | return; |
| 608 | } |
| 609 | if let Some(c) = &self.candidate { |
| 610 | if c.max_txid <= current_max { |
| 611 | self.candidate = None; |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | loop { |
| 616 | self.ensure_current(); |
| 617 | if self.done { |
| 618 | return; |
| 619 | } |
| 620 | |
| 621 | let info = self.current.clone().unwrap(); |
| 622 | if info.min_txid.0 > current_max.0 + 1 { |
| 623 | return; |
| 624 | } |
| 625 | self.current = None; |
| 626 | |
| 627 | if info.max_txid <= current_max { |
| 628 | continue; |
| 629 | } |
| 630 | if txid != TXID(0) && info.max_txid > txid { |
| 631 | continue; |
| 632 | } |
| 633 | |
| 634 | match &self.candidate { |
| 635 | None => self.candidate = Some(info), |
| 636 | Some(c) => { |
| 637 | if restore_candidate_better(c, &info) { |
| 638 | self.candidate = Some(info); |
| 639 | } |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | /// Populates `current` with the next item, or marks `done`. Ported from |
| 646 | /// `ensureCurrent` (replica.go:1589-1603). |
| 647 | fn ensure_current(&mut self) { |
| 648 | if self.done || self.current.is_some() { |
| 649 | return; |
| 650 | } |
| 651 | if self.idx >= self.files.len() { |
| 652 | self.done = true; |
| 653 | return; |
| 654 | } |
| 655 | self.current = Some(self.files[self.idx].clone()); |
| 656 | self.idx += 1; |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | /// True if `next` is a strictly better restore candidate than `curr`: longer |
| 661 | /// reach first (`MaxTXID`), then a smaller `MinTXID` (more coverage), then a |
| 662 | /// higher level (more compacted), then an earlier `created_at`. |
| 663 | /// |
| 664 | /// Ported from `restoreCandidateBetter` (replica.go:1605-1616). |
| 665 | fn restore_candidate_better(curr: &FileInfo, next: &FileInfo) -> bool { |
| 666 | if next.max_txid != curr.max_txid { |
| 667 | return next.max_txid > curr.max_txid; |
| 668 | } |
| 669 | if next.min_txid != curr.min_txid { |
| 670 | return next.min_txid < curr.min_txid; |
| 671 | } |
| 672 | if next.level != curr.level { |
| 673 | return next.level > curr.level; |
| 674 | } |
| 675 | // CreatedAt.Before(curr): an unknown (None) timestamp is treated as not |
| 676 | // earlier, matching Go's zero-time comparison being false here. |
| 677 | match (next.created_at, curr.created_at) { |
| 678 | (Some(n), Some(c)) => n < c, |
| 679 | _ => false, |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | /// Maximum `max_txid` across a slice, `TXID(0)` if empty. Mirrors |
| 684 | /// `FileInfoSlice.MaxTXID` (ltx.go:612-619); the slice here is already in plan |
| 685 | /// (ascending) order, but we scan defensively rather than assume. |
| 686 | fn slice_max_txid(infos: &[FileInfo]) -> TXID { |
| 687 | infos.iter().map(|f| f.max_txid).max().unwrap_or(TXID(0)) |
| 688 | } |
| 689 | |
| 690 | /// Merges the LTX `files` (a snapshot followed by incrementals, in plan order) |
| 691 | /// and reconstructs the full SQLite database image. |
| 692 | /// |
| 693 | /// This replaces Go's `ltx.NewCompactor(pw, rdrs)` + `Decoder.DecodeDatabaseTo` |
| 694 | /// (replica.go:667-682). The compactor's contract ([email protected] compactor.go): |
| 695 | /// * page sizes must match across inputs; |
| 696 | /// * the **last** input's `Commit` is the final database size; |
| 697 | /// * for each page number, the **latest** input that carries it wins |
| 698 | /// (compactor.go:198-228 iterates inputs newest-first); |
| 699 | /// * pages numbered beyond the final `Commit` are dropped (truncation). |
| 700 | /// |
| 701 | /// `DecodeDatabaseTo` then writes pages `1..=Commit`, zero-filling the lock page |
| 702 | /// (decoder.go:236-254). Every input is fully decoded + checksum-verified first |
| 703 | /// (`decode_file`), so a corrupt download is caught here. |
| 704 | fn build_database_image(files: &[Vec<u8>]) -> Result<Vec<u8>> { |
| 705 | // Decode + verify each input, gathering its header and pages. |
| 706 | let mut headers: Vec<ltx::Header> = Vec::with_capacity(files.len()); |
| 707 | let mut page_sets: Vec<Vec<(u32, Vec<u8>)>> = Vec::with_capacity(files.len()); |
| 708 | for data in files { |
| 709 | let decoded = ltx::decode_file(data)?; |
| 710 | let pages = ltx::decode_file_pages(data)?; |
| 711 | headers.push(decoded.header); |
| 712 | page_sets.push(pages); |
| 713 | } |
| 714 | |
| 715 | // Validate page sizes match across inputs (compactor.go:95-97). |
| 716 | let page_size = headers[0].page_size; |
| 717 | for h in &headers { |
| 718 | if h.page_size != page_size { |
| 719 | return Err(Error::Other( |
| 720 | format!( |
| 721 | "input files have mismatched page sizes: {} != {}", |
| 722 | page_size, h.page_size |
| 723 | ) |
| 724 | .into(), |
| 725 | )); |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | // The final database size is the last input's Commit (compactor.go:108-118). |
| 730 | let commit = headers[headers.len() - 1].commit; |
| 731 | let page_size_usize = page_size as usize; |
| 732 | let lock = ltx::lock_pgno(page_size); |
| 733 | |
| 734 | // Merge: for each page number, the latest input that carries it wins. Iterate |
| 735 | // inputs in order, overwriting — the last write for a pgno is the newest |
| 736 | // input's, matching the compactor's newest-first selection (compactor.go:203-224). |
| 737 | // Pages beyond the final Commit are skipped (compactor.go:217). |
| 738 | let mut merged: HashMap<u32, Vec<u8>> = HashMap::new(); |
| 739 | for pages in &page_sets { |
| 740 | for (pgno, data) in pages { |
| 741 | if *pgno > commit { |
| 742 | continue; // out of range of the final database size |
| 743 | } |
| 744 | merged.insert(*pgno, data.clone()); |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | // Reconstruct the database image: pages 1..=commit, lock page zero-filled |
| 749 | // (decoder.go:236-254). A non-lock page missing from the merge means the |
| 750 | // backup chain is incomplete. |
| 751 | let mut image = Vec::with_capacity(commit as usize * page_size_usize); |
| 752 | let zero_page = vec![0u8; page_size_usize]; |
| 753 | for pgno in 1..=commit { |
| 754 | if pgno == lock { |
| 755 | image.extend_from_slice(&zero_page); |
| 756 | continue; |
| 757 | } |
| 758 | match merged.get(&pgno) { |
| 759 | Some(data) => image.extend_from_slice(data), |
| 760 | None => { |
| 761 | return Err(Error::Other( |
| 762 | format!("missing page {pgno} in restore plan (incomplete backup)").into(), |
| 763 | )); |
| 764 | } |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | Ok(image) |
| 769 | } |
| 770 | |
| 771 | /// Appends `ext` to `path` as a literal suffix (`p` → `p.tmp`), the way Go's |
| 772 | /// `opt.OutputPath + ".tmp"` does (NOT `Path::set_extension`, which would replace |
| 773 | /// an existing extension). |
| 774 | fn append_ext(path: &Path, ext: &str) -> PathBuf { |
| 775 | let mut s = path.as_os_str().to_owned(); |
| 776 | s.push("."); |
| 777 | s.push(ext); |
| 778 | PathBuf::from(s) |
| 779 | } |
| 780 | |
| 781 | /// Writes `data` to `tmp_path`, fsyncs, then renames onto `final_path` — the |
| 782 | /// crash-consistent atomic-write idiom (replica.go:661-694). On any failure the |
| 783 | /// temp file is removed. |
| 784 | fn write_file_atomic(tmp_path: &Path, final_path: &Path, data: &[u8]) -> Result<()> { |
| 785 | use std::io::Write; |
| 786 | let result = (|| -> Result<()> { |
| 787 | let mut f = std::fs::File::create(tmp_path)?; |
| 788 | f.write_all(data)?; |
| 789 | f.sync_all()?; |
| 790 | drop(f); |
| 791 | std::fs::rename(tmp_path, final_path)?; |
| 792 | Ok(()) |
| 793 | })(); |
| 794 | if result.is_err() { |
| 795 | let _ = std::fs::remove_file(tmp_path); |
| 796 | } |
| 797 | result |
| 798 | } |
| 799 | |
| 800 | #[cfg(test)] |
| 801 | mod tests { |
| 802 | use super::*; |
| 803 | use crate::client::file::FileReplicaClient; |
| 804 | use crate::ltx::{Header, HEADER_FLAG_NO_CHECKSUM, VERSION}; |
| 805 | |
| 806 | /// Builds a single-page incremental LTX file (`NoChecksum`), mirroring the Go |
| 807 | /// `mustBuildIncrementalLTX` helper (replica_internal_test.go:285-315): one |
| 808 | /// page `pgno` filled with `fill`, `commit = pgno`. |
| 809 | fn build_incremental_ltx( |
| 810 | min_txid: TXID, |
| 811 | max_txid: TXID, |
| 812 | page_size: u32, |
| 813 | pgno: u32, |
| 814 | fill: u8, |
| 815 | ) -> Vec<u8> { |
| 816 | let header = Header { |
| 817 | version: VERSION, |
| 818 | flags: HEADER_FLAG_NO_CHECKSUM, |
| 819 | page_size, |
| 820 | commit: pgno, |
| 821 | min_txid, |
| 822 | max_txid, |
| 823 | timestamp: 1_000, |
| 824 | pre_apply_checksum: 0, |
| 825 | wal_offset: 0, |
| 826 | wal_size: 0, |
| 827 | wal_salt1: 0, |
| 828 | wal_salt2: 0, |
| 829 | node_id: 0, |
| 830 | }; |
| 831 | let pages = vec![(pgno, vec![fill; page_size as usize])]; |
| 832 | ltx::encode_file(&header, &pages, 0).expect("encode incremental ltx") |
| 833 | } |
| 834 | |
| 835 | /// Builds a snapshot LTX file (MinTXID==1, tracked checksum) covering pages |
| 836 | /// `1..=commit`, each page filled with a per-page byte. The lock page is |
| 837 | /// skipped, exactly as the capture loop does. |
| 838 | fn build_snapshot_ltx(max_txid: TXID, page_size: u32, commit: u32) -> Vec<u8> { |
| 839 | let lock = ltx::lock_pgno(page_size); |
| 840 | let mut pages: Vec<(u32, Vec<u8>)> = Vec::new(); |
| 841 | let mut rolling = crate::CHECKSUM_FLAG; |
| 842 | for pgno in 1..=commit { |
| 843 | if pgno == lock { |
| 844 | continue; |
| 845 | } |
| 846 | let data = vec![(pgno & 0xff) as u8; page_size as usize]; |
| 847 | rolling = crate::CHECKSUM_FLAG | (rolling ^ ltx::checksum_page(pgno, &data)); |
| 848 | pages.push((pgno, data)); |
| 849 | } |
| 850 | let header = Header { |
| 851 | version: VERSION, |
| 852 | flags: 0, |
| 853 | page_size, |
| 854 | commit, |
| 855 | min_txid: TXID(1), |
| 856 | max_txid, |
| 857 | timestamp: 1_000, |
| 858 | pre_apply_checksum: 0, |
| 859 | wal_offset: 0, |
| 860 | wal_size: 0, |
| 861 | wal_salt1: 0, |
| 862 | wal_salt2: 0, |
| 863 | node_id: 0, |
| 864 | }; |
| 865 | ltx::encode_file(&header, &pages, rolling).expect("encode snapshot ltx") |
| 866 | } |
| 867 | |
| 868 | // Port of TestReplica_UploadLTXFile_OpenErrorReturnsLTXError/MissingFile |
| 869 | // (replica_internal_test.go:143-160): a missing local LTX file makes |
| 870 | // uploadLTXFile return an LTXError{op:"open"}. |
| 871 | #[tokio::test] |
| 872 | async fn upload_ltx_file_missing_returns_ltx_error() { |
| 873 | let dir = tempfile::tempdir().unwrap(); |
| 874 | let db = Db::open(dir.path().join("test.db")).unwrap(); |
| 875 | let client = |
| 876 | FileReplicaClient::new(dir.path().join("replica").to_string_lossy().into_owned()); |
| 877 | let mut r = Replica::new(db, client); |
| 878 | |
| 879 | // No local LTX file for TXID 1 exists yet (we never synced the Db). |
| 880 | let err = r |
| 881 | .upload_ltx_file(0, TXID(1), TXID(1)) |
| 882 | .await |
| 883 | .expect_err("expected error for missing LTX file"); |
| 884 | match err { |
| 885 | Error::Ltx(e) => assert_eq!(e.op, "open", "op must be open"), |
| 886 | other => panic!("expected LTXError, got {other:?}"), |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | // check_database_behind_replica is a NO-OP when the replica is empty: it must |
| 891 | // never disturb local state just because there is nothing remote (issue #781 |
| 892 | // guard, db.go:1228-1230). A restore-only replica (no DB) is also a clean |
| 893 | // no-op (the `db is None` branch). |
| 894 | #[tokio::test] |
| 895 | async fn check_behind_replica_noop_when_remote_empty() { |
| 896 | let dir = tempfile::tempdir().unwrap(); |
| 897 | let db = Db::open(dir.path().join("test.db")).unwrap(); |
| 898 | let client = |
| 899 | FileReplicaClient::new(dir.path().join("replica").to_string_lossy().into_owned()); |
| 900 | let mut r = Replica::new(db, client); |
| 901 | // Empty remote → Ok, no panic, no state change. |
| 902 | r.check_database_behind_replica() |
| 903 | .await |
| 904 | .expect("empty remote is a clean no-op"); |
| 905 | |
| 906 | // Same for a client-only replica with no DB. |
| 907 | let client2 = |
| 908 | FileReplicaClient::new(dir.path().join("replica2").to_string_lossy().into_owned()); |
| 909 | let mut r2 = Replica::new_client_only(client2); |
| 910 | r2.check_database_behind_replica() |
| 911 | .await |
| 912 | .expect("no-DB replica is a clean no-op"); |
| 913 | } |
| 914 | |
| 915 | // When the database is already at or ahead of the replica, the check is a |
| 916 | // no-op and must NOT delete the local L0 chain (db.go:1232-1235). We build a |
| 917 | // tiny local+remote pair at the same TXID and assert the local snapshot |
| 918 | // survives the call. |
| 919 | #[tokio::test] |
| 920 | async fn check_behind_replica_noop_when_db_ahead_preserves_local() { |
| 921 | let dir = tempfile::tempdir().unwrap(); |
| 922 | let db = Db::open(dir.path().join("test.db")).unwrap(); |
| 923 | let client = |
| 924 | FileReplicaClient::new(dir.path().join("replica").to_string_lossy().into_owned()); |
| 925 | let mut r = Replica::new(db, client); |
| 926 | |
| 927 | // Seed BOTH local and remote with a snapshot at TXID 1 (DB == replica). |
| 928 | let page_size = 512u32; |
| 929 | let snap = build_snapshot_ltx(TXID(1), page_size, 2); |
| 930 | // Local L0 file (so db.pos() == 1). |
| 931 | let local_path = r.db().unwrap().ltx_path(0, TXID(1), TXID(1)); |
| 932 | std::fs::create_dir_all(Path::new(&local_path).parent().unwrap()).unwrap(); |
| 933 | std::fs::write(&local_path, &snap).unwrap(); |
| 934 | // Remote L0 file at the same TXID. |
| 935 | r.client |
| 936 | .write_ltx_file(0, TXID(1), TXID(1), &snap) |
| 937 | .await |
| 938 | .unwrap(); |
| 939 | |
| 940 | let before = std::fs::read(&local_path).unwrap(); |
| 941 | r.check_database_behind_replica() |
| 942 | .await |
| 943 | .expect("db == replica is a no-op"); |
| 944 | let after = std::fs::read(&local_path).expect("local L0 file must survive"); |
| 945 | assert_eq!( |
| 946 | before, after, |
| 947 | "local L0 chain untouched when DB is not behind" |
| 948 | ); |
| 949 | } |
| 950 | |
| 951 | // build_database_image merges a snapshot + incrementals like the compactor: |
| 952 | // the latest input wins per page, and the final Commit bounds the size. |
| 953 | #[test] |
| 954 | fn build_image_latest_page_wins_and_commit_bounds() { |
| 955 | let page_size = 512u32; |
| 956 | // Snapshot: 3 pages (commit=3), page bytes 1,2,3. |
| 957 | let snap = build_snapshot_ltx(TXID(1), page_size, 3); |
| 958 | // Incremental at TXID 2 rewrites page 2 to 0xEE (commit stays 2 in the |
| 959 | // helper, but the final image size is the LAST input's commit). |
| 960 | let inc2 = build_incremental_ltx(TXID(2), TXID(2), page_size, 2, 0xEE); |
| 961 | // Incremental at TXID 3 grows to page 4 (commit=4), page 4 = 0x44. |
| 962 | let inc3 = build_incremental_ltx(TXID(3), TXID(3), page_size, 4, 0x44); |
| 963 | |
| 964 | let image = build_database_image(&[snap, inc2, inc3]).expect("merge"); |
| 965 | assert_eq!( |
| 966 | image.len(), |
| 967 | 4 * page_size as usize, |
| 968 | "final commit=4 bounds size" |
| 969 | ); |
| 970 | |
| 971 | let page = |
| 972 | |n: u32| &image[(n - 1) as usize * page_size as usize..n as usize * page_size as usize]; |
| 973 | assert_eq!(page(1)[0], 1, "page 1 from snapshot"); |
| 974 | assert_eq!( |
| 975 | page(2)[0], |
| 976 | 0xEE, |
| 977 | "page 2 overwritten by the latest input (TXID 2)" |
| 978 | ); |
| 979 | assert_eq!(page(3)[0], 3, "page 3 from snapshot, untouched"); |
| 980 | assert_eq!(page(4)[0], 0x44, "page 4 added by TXID 3"); |
| 981 | } |
| 982 | |
| 983 | // A page beyond the final commit is dropped (compactor truncation, |
| 984 | // compactor.go:217). |
| 985 | #[test] |
| 986 | fn build_image_drops_pages_beyond_final_commit() { |
| 987 | let page_size = 512u32; |
| 988 | // Snapshot has 5 pages; the final incremental shrinks commit to 2. |
| 989 | let snap = build_snapshot_ltx(TXID(1), page_size, 5); |
| 990 | let inc = build_incremental_ltx(TXID(2), TXID(2), page_size, 2, 0xAB); |
| 991 | let image = build_database_image(&[snap, inc]).expect("merge"); |
| 992 | assert_eq!( |
| 993 | image.len(), |
| 994 | 2 * page_size as usize, |
| 995 | "shrunk to commit=2; pages 3-5 dropped" |
| 996 | ); |
| 997 | } |
| 998 | |
| 999 | // restore() reconstructs a DB byte-image equal to decoding the snapshot alone |
| 1000 | // when there are no incrementals (the single-file plan). |
| 1001 | #[test] |
| 1002 | fn build_image_single_snapshot_matches_decode_database_image() { |
| 1003 | let page_size = 1024u32; |
| 1004 | let snap = build_snapshot_ltx(TXID(1), page_size, 4); |
| 1005 | let via_merge = build_database_image(std::slice::from_ref(&snap)).expect("merge"); |
| 1006 | let via_decoder = ltx::decode_database_image(&snap).expect("decode image"); |
| 1007 | assert_eq!( |
| 1008 | via_merge, via_decoder, |
| 1009 | "single-file merge == DecodeDatabaseTo" |
| 1010 | ); |
| 1011 | } |
| 1012 | |
| 1013 | // A corrupt input is rejected by build_database_image (decode_file verifies |
| 1014 | // the file checksum before any page is used). |
| 1015 | #[test] |
| 1016 | fn build_image_rejects_corrupt_input() { |
| 1017 | let page_size = 512u32; |
| 1018 | let mut snap = build_snapshot_ltx(TXID(1), page_size, 2); |
| 1019 | let mid = ltx::HEADER_SIZE + (snap.len() - ltx::HEADER_SIZE) / 2; |
| 1020 | snap[mid] ^= 0x01; |
| 1021 | let err = build_database_image(&[snap]).expect_err("corruption must be caught"); |
| 1022 | assert!( |
| 1023 | matches!(err, Error::ChecksumMismatch | Error::LTXCorrupted), |
| 1024 | "corrupt LTX rejected, got {err:?}" |
| 1025 | ); |
| 1026 | } |
| 1027 | |
| 1028 | // calc_restore_plan over a file client with an L0-only chain returns the |
| 1029 | // contiguous snapshot+incrementals in TXID order, and refusing to restore |
| 1030 | // when nothing is present returns TxNotAvailable. |
| 1031 | #[tokio::test] |
| 1032 | async fn calc_restore_plan_l0_chain_and_empty() { |
| 1033 | let dir = tempfile::tempdir().unwrap(); |
| 1034 | let client = FileReplicaClient::new(dir.path().to_string_lossy().into_owned()); |
| 1035 | |
| 1036 | // Empty replica -> TxNotAvailable. |
| 1037 | let err = calc_restore_plan(&client, TXID(0)) |
| 1038 | .await |
| 1039 | .expect_err("empty replica"); |
| 1040 | assert!( |
| 1041 | matches!(err, Error::TxNotAvailable), |
| 1042 | "empty -> TxNotAvailable" |
| 1043 | ); |
| 1044 | |
| 1045 | // Write a snapshot at TXID 1 (L0) + two incrementals. |
| 1046 | let page_size = 512u32; |
| 1047 | let snap = build_snapshot_ltx(TXID(1), page_size, 2); |
| 1048 | client |
| 1049 | .write_ltx_file(0, TXID(1), TXID(1), &snap) |
| 1050 | .await |
| 1051 | .unwrap(); |
| 1052 | let inc2 = build_incremental_ltx(TXID(2), TXID(2), page_size, 2, 0x22); |
| 1053 | client |
| 1054 | .write_ltx_file(0, TXID(2), TXID(2), &inc2) |
| 1055 | .await |
| 1056 | .unwrap(); |
| 1057 | let inc3 = build_incremental_ltx(TXID(3), TXID(3), page_size, 2, 0x33); |
| 1058 | client |
| 1059 | .write_ltx_file(0, TXID(3), TXID(3), &inc3) |
| 1060 | .await |
| 1061 | .unwrap(); |
| 1062 | |
| 1063 | let plan = calc_restore_plan(&client, TXID(0)).await.expect("plan"); |
| 1064 | let txids: Vec<u64> = plan.iter().map(|f| f.max_txid.0).collect(); |
| 1065 | assert_eq!(txids, vec![1, 2, 3], "contiguous L0 chain in TXID order"); |
| 1066 | |
| 1067 | // Targeted restore to TXID 2 stops the plan at 2. |
| 1068 | let plan2 = calc_restore_plan(&client, TXID(2)).await.expect("plan@2"); |
| 1069 | let txids2: Vec<u64> = plan2.iter().map(|f| f.max_txid.0).collect(); |
| 1070 | assert_eq!(txids2, vec![1, 2], "plan capped at the target TXID"); |
| 1071 | } |
| 1072 | |
| 1073 | // After a continuity break, the L0-only capture loop re-emits a FULL snapshot |
| 1074 | // at a later TXID (MinTXID==1, MaxTXID==N) alongside the earlier per-txn |
| 1075 | // files. calc_restore_plan must select that wider snapshot (it extends the |
| 1076 | // longest contiguous range), exactly as the compactor needs — and the merged |
| 1077 | // image must reconstruct correctly from snapshot 1-3 + incremental 4. |
| 1078 | #[tokio::test] |
| 1079 | async fn calc_restore_plan_prefers_wider_reemitted_snapshot() { |
| 1080 | let dir = tempfile::tempdir().unwrap(); |
| 1081 | let client = FileReplicaClient::new(dir.path().to_string_lossy().into_owned()); |
| 1082 | let page_size = 512u32; |
| 1083 | |
| 1084 | // Original chain: snapshot 1-1 + incrementals 2,3 (each rewrites page 2). |
| 1085 | client |
| 1086 | .write_ltx_file( |
| 1087 | 0, |
| 1088 | TXID(1), |
| 1089 | TXID(1), |
| 1090 | &build_snapshot_ltx(TXID(1), page_size, 2), |
| 1091 | ) |
| 1092 | .await |
| 1093 | .unwrap(); |
| 1094 | client |
| 1095 | .write_ltx_file( |
| 1096 | 0, |
| 1097 | TXID(2), |
| 1098 | TXID(2), |
| 1099 | &build_incremental_ltx(TXID(2), TXID(2), page_size, 2, 0x22), |
| 1100 | ) |
| 1101 | .await |
| 1102 | .unwrap(); |
| 1103 | client |
| 1104 | .write_ltx_file( |
| 1105 | 0, |
| 1106 | TXID(3), |
| 1107 | TXID(3), |
| 1108 | &build_incremental_ltx(TXID(3), TXID(3), page_size, 2, 0x33), |
| 1109 | ) |
| 1110 | .await |
| 1111 | .unwrap(); |
| 1112 | // Continuity break: a re-emitted snapshot 1-3 (covers the whole DB at TXID 3). |
| 1113 | client |
| 1114 | .write_ltx_file( |
| 1115 | 0, |
| 1116 | TXID(1), |
| 1117 | TXID(3), |
| 1118 | &build_snapshot_ltx(TXID(3), page_size, 2), |
| 1119 | ) |
| 1120 | .await |
| 1121 | .unwrap(); |
| 1122 | // A new incremental on top of the re-emitted snapshot. |
| 1123 | client |
| 1124 | .write_ltx_file( |
| 1125 | 0, |
| 1126 | TXID(4), |
| 1127 | TXID(4), |
| 1128 | &build_incremental_ltx(TXID(4), TXID(4), page_size, 2, 0x44), |
| 1129 | ) |
| 1130 | .await |
| 1131 | .unwrap(); |
| 1132 | |
| 1133 | let plan = calc_restore_plan(&client, TXID(0)).await.expect("plan"); |
| 1134 | // The wider snapshot (1-3) is chosen over snapshot 1-1, then incremental 4 |
| 1135 | // extends it — a contiguous, minimal chain reaching TXID 4. |
| 1136 | let pairs: Vec<(u64, u64)> = plan.iter().map(|f| (f.min_txid.0, f.max_txid.0)).collect(); |
| 1137 | assert_eq!( |
| 1138 | pairs, |
| 1139 | vec![(1, 3), (4, 4)], |
| 1140 | "wider re-emitted snapshot anchors the plan; incremental 4 extends it" |
| 1141 | ); |
| 1142 | |
| 1143 | // And the merge reconstructs: page 2 takes incremental 4's 0x44. |
| 1144 | let mut datas = Vec::new(); |
| 1145 | for info in &plan { |
| 1146 | datas.push( |
| 1147 | client |
| 1148 | .open_ltx_file(info.level, info.min_txid, info.max_txid, 0, 0) |
| 1149 | .await |
| 1150 | .unwrap(), |
| 1151 | ); |
| 1152 | } |
| 1153 | let image = build_database_image(&datas).expect("merge re-emitted chain"); |
| 1154 | assert_eq!(image.len(), 2 * page_size as usize, "commit=2"); |
| 1155 | assert_eq!( |
| 1156 | image[page_size as usize], 0x44, |
| 1157 | "page 2 reflects the newest incremental" |
| 1158 | ); |
| 1159 | } |
| 1160 | |
| 1161 | // A client that fails the first `write_ltx_file` with a preloaded error and |
| 1162 | // then delegates, so a single sync's upload can be made to fail on demand. |
| 1163 | // `poison_list` makes every `ltx_files` (the `calc_pos` listing) fail, so a |
| 1164 | // test can prove a seeded sync never lists. |
| 1165 | struct FaultyClient { |
| 1166 | inner: FileReplicaClient, |
| 1167 | fail_first_write: std::sync::Mutex<Option<Error>>, |
| 1168 | poison_list: bool, |
| 1169 | } |
| 1170 | |
| 1171 | impl FaultyClient { |
| 1172 | fn new(inner: FileReplicaClient, err: Error) -> Self { |
| 1173 | Self { |
| 1174 | inner, |
| 1175 | fail_first_write: std::sync::Mutex::new(Some(err)), |
| 1176 | poison_list: false, |
| 1177 | } |
| 1178 | } |
| 1179 | fn poisoning_list(inner: FileReplicaClient) -> Self { |
| 1180 | Self { |
| 1181 | inner, |
| 1182 | fail_first_write: std::sync::Mutex::new(None), |
| 1183 | poison_list: true, |
| 1184 | } |
| 1185 | } |
| 1186 | } |
| 1187 | |
| 1188 | #[async_trait::async_trait] |
| 1189 | impl ReplicaClient for FaultyClient { |
| 1190 | fn type_name(&self) -> &str { |
| 1191 | "faulty" |
| 1192 | } |
| 1193 | async fn ltx_files(&self, l: i32, s: TXID, m: bool) -> Result<Vec<FileInfo>> { |
| 1194 | if self.poison_list { |
| 1195 | return Err(Error::Other("list poisoned".into())); |
| 1196 | } |
| 1197 | self.inner.ltx_files(l, s, m).await |
| 1198 | } |
| 1199 | async fn open_ltx_file( |
| 1200 | &self, |
| 1201 | l: i32, |
| 1202 | mn: TXID, |
| 1203 | mx: TXID, |
| 1204 | o: i64, |
| 1205 | s: i64, |
| 1206 | ) -> Result<Vec<u8>> { |
| 1207 | self.inner.open_ltx_file(l, mn, mx, o, s).await |
| 1208 | } |
| 1209 | async fn write_ltx_file(&self, l: i32, mn: TXID, mx: TXID, d: &[u8]) -> Result<FileInfo> { |
| 1210 | if let Some(e) = self.fail_first_write.lock().unwrap().take() { |
| 1211 | return Err(e); |
| 1212 | } |
| 1213 | self.inner.write_ltx_file(l, mn, mx, d).await |
| 1214 | } |
| 1215 | async fn delete_ltx_files(&self, f: &[FileInfo]) -> Result<()> { |
| 1216 | self.inner.delete_ltx_files(f).await |
| 1217 | } |
| 1218 | async fn delete_all(&self) -> Result<()> { |
| 1219 | self.inner.delete_all().await |
| 1220 | } |
| 1221 | } |
| 1222 | |
| 1223 | // The classifier that decides whether a sync error invalidates the cached |
| 1224 | // position: only state-divergence errors do; transient store/IO ones do not. |
| 1225 | #[test] |
| 1226 | fn pos_untrustworthy_splits_divergence_from_transient() { |
| 1227 | assert!(pos_untrustworthy(&Error::ChecksumMismatch)); |
| 1228 | assert!(pos_untrustworthy(&Error::LTXCorrupted)); |
| 1229 | assert!(pos_untrustworthy(&Error::LTXMissing)); |
| 1230 | assert!(pos_untrustworthy(&Error::TxNotAvailable)); |
| 1231 | assert!(pos_untrustworthy(&Error::NoSnapshots)); |
| 1232 | assert!(!pos_untrustworthy(&Error::Other("429 slow down".into()))); |
| 1233 | assert!(!pos_untrustworthy(&Error::Io(std::io::Error::from( |
| 1234 | std::io::ErrorKind::TimedOut |
| 1235 | )))); |
| 1236 | } |
| 1237 | |
| 1238 | // A failed upload must NOT discard the cached position: a fenced single |
| 1239 | // writer keeps it and retries (an idempotent overwrite) rather than re- |
| 1240 | // deriving it with a `calc_pos` listing. `sync_inner` wraps every store |
| 1241 | // error as `Error::Other`, so this is the shape every real upload/list |
| 1242 | // failure takes -- the exact case the old clear-on-any-error turned into a |
| 1243 | // listing storm on a rate-limiting store. |
| 1244 | #[tokio::test] |
| 1245 | async fn transient_upload_error_keeps_position() { |
| 1246 | let dir = tempfile::tempdir().unwrap(); |
| 1247 | let db = Db::open(dir.path().join("test.db")).unwrap(); |
| 1248 | let inner = |
| 1249 | FileReplicaClient::new(dir.path().join("replica").to_string_lossy().into_owned()); |
| 1250 | let mut r = Replica::new(db, FaultyClient::new(inner, Error::Other("s3: 503".into()))); |
| 1251 | // One decodable L0 file at TXID 2 makes db.pos()==2 and is the local |
| 1252 | // file the upload reads before the client write is rigged to fail. |
| 1253 | let l0 = r.db().unwrap().ltx_path(0, TXID(2), TXID(2)); |
| 1254 | std::fs::create_dir_all(Path::new(&l0).parent().unwrap()).unwrap(); |
| 1255 | std::fs::write(&l0, build_incremental_ltx(TXID(2), TXID(2), 512, 2, 0x22)).unwrap(); |
| 1256 | // Seed TXID 1 as known-replicated, so sync tries to upload TXID 2. |
| 1257 | r.seed_pos(Pos::new(TXID(1), 0)); |
| 1258 | r.sync().await.expect_err("upload was rigged to fail"); |
| 1259 | assert_eq!( |
| 1260 | r.pos().txid, |
| 1261 | TXID(1), |
| 1262 | "a transient error keeps the position" |
| 1263 | ); |
| 1264 | } |
| 1265 | |
| 1266 | // A seeded position skips the `calc_pos` listing entirely: with listing |
| 1267 | // poisoned, an unseeded replica's first sync would fail there, but a seeded |
| 1268 | // one uploads without ever listing. This is the fix for the activation |
| 1269 | // listing that storms a rate-limiting store on every fresh cell. |
| 1270 | #[tokio::test] |
| 1271 | async fn seeded_position_skips_calc_pos_listing() { |
| 1272 | let dir = tempfile::tempdir().unwrap(); |
| 1273 | let db = Db::open(dir.path().join("test.db")).unwrap(); |
| 1274 | let inner = |
| 1275 | FileReplicaClient::new(dir.path().join("replica").to_string_lossy().into_owned()); |
| 1276 | let mut r = Replica::new(db, FaultyClient::poisoning_list(inner)); |
| 1277 | // Local L0 snapshot at TXID 1: db.pos()==1 and a file to upload. |
| 1278 | let l0 = r.db().unwrap().ltx_path(0, TXID(1), TXID(1)); |
| 1279 | std::fs::create_dir_all(Path::new(&l0).parent().unwrap()).unwrap(); |
| 1280 | std::fs::write(&l0, build_snapshot_ltx(TXID(1), 512, 2)).unwrap(); |
| 1281 | // Seed as a fresh cell (known 0); the first sync must not list. |
| 1282 | r.seed_pos(Pos::ZERO); |
| 1283 | r.sync() |
| 1284 | .await |
| 1285 | .expect("a seeded sync must not list, so the poisoned list is never hit"); |
| 1286 | assert_eq!(r.pos().txid, TXID(1), "uploaded TXID 1 with no listing"); |
| 1287 | } |
| 1288 | } |