Diffinery

homeflare/celldpublic

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