Diffinery

homeflare/celldpublic

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