Diffinery

homeflare/celldpublic

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