wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar — a library. Like Litestream, but embedded.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
/// Restore engine — rebuilds the local SQLite database from bucket state.
///
/// # Restore flow
///
/// 1. Download the manifest from the bucket
/// 2. If no manifest exists, create a fresh one from local WAL salts
/// 3. If manifest exists, apply the configured `RestoreBehavior`:
///    - `UploadLocalIfNewer`: upload local if newer, otherwise download
///    - `AlwaysRestoreFromBucket`: always download from bucket
///    - `Recoverable`: download from bucket, tolerate checksum mismatch
///    - `ErrorIfConflict`: error if local is newer
/// 4. Download the snapshot and WAL segments
/// 5. Reconstruct the WAL file on disk
///
/// # Memory usage
///
/// Segments are streamed to disk (not buffered in memory). Snapshots are
/// streamed from object storage directly to disk (via `BucketStore::get_file`),
/// so peak memory usage is bounded by the chunk size, not the database size.
use bytes::Bytes;
use std::sync::Arc;
use tokio::sync::Mutex;

use crate::config::Config;
use crate::error::{Error, Result};
use crate::metrics::Metrics;
use crate::replication::manifest::{Manifest, MANIFEST_KEY};
use crate::storage::BucketStore;
use crate::wal::{WalFile, WalHeader};

pub struct RestoreEngine {
    config: Config,
    bucket: Arc<dyn BucketStore>,
    metrics: Option<Arc<dyn Metrics>>,
}

/// Path for the generation sidecar file.
/// After each restore, we write the manifest generation to this file so we
/// can detect on next open whether the local DB is newer than the bucket
/// (replacing the unreliable mtime-based comparison).
fn generation_path(db_path: &std::path::Path) -> std::path::PathBuf {
    db_path.with_extension("generation")
}

/// Write the manifest generation to the sidecar file.
pub(crate) async fn write_generation(
    db_path: &std::path::Path,
    generation: u64,
) -> crate::error::Result<()> {
    let path = generation_path(db_path);
    tokio::fs::write(&path, generation.to_string())
        .await
        .map_err(|e| crate::error::Error::Other(format!("failed to write generation file: {e}")))
}

/// Read the manifest generation from the sidecar file.
/// Returns None if the file doesn't exist (e.g. first run, or DB was created
/// outside of wal-backup).
async fn read_generation(db_path: &std::path::Path) -> Result<Option<u64>> {
    let path = generation_path(db_path);
    match tokio::fs::read_to_string(&path).await {
        Ok(content) => {
            match content.trim().parse::<u64>() {
                Ok(gen) => Ok(Some(gen)),
                Err(e) => {
                    tracing::warn!(
                        "Corrupted generation file at {} — cannot parse '{}': {}. \
                         Treating as missing generation.",
                        path.display(), content.trim(), e
                    );
                    // Treat corrupt file as missing — fall through to None below
                    // so the caller uses the default (conservative) behavior.
                    Ok(None)
                }
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            Ok(None)
        }
        Err(e) => {
            tracing::warn!(
                "Cannot read generation file at {}: {}",
                path.display(), e
            );
            Ok(None)
        }
    }
}

impl RestoreEngine {
    pub fn new(config: Config, bucket: Arc<dyn BucketStore>) -> Self {
        RestoreEngine {
            config,
            bucket,
            metrics: None,
        }
    }

    pub fn with_metrics(self, metrics: Arc<dyn Metrics>) -> Self {
        Self {
            metrics: Some(metrics),
            ..self
        }
    }

    async fn detect_local_salts(&self) -> (u32, u32, u32) {
        let db_exists = tokio::fs::try_exists(self.config.db_path())
            .await
            .unwrap_or(false);
        let wal_exists = tokio::fs::try_exists(self.config.wal_path())
            .await
            .unwrap_or(false);

        if !db_exists && !wal_exists {
            return (0, 0, 4096);
        }

        if wal_exists {
            let wal_path = self.config.wal_path().clone();
            let wal_result = tokio::task::spawn_blocking(move || WalFile::open(&wal_path))
                .await
                .ok()
                .and_then(|r| r.ok());
            if let Some(w) = wal_result {
                let ps = if db_exists {
                    read_page_size_from_db_async(self.config.db_path())
                        .await
                        .unwrap_or_else(|_| {
                            tracing::warn!("failed to read page size from DB, using WAL page size");
                            w.page_size()
                        })
                } else {
                    w.page_size()
                };
                return (w.header().salt_1, w.header().salt_2, ps);
            }
        }

        if db_exists {
            let db_page_size = read_page_size_from_db_async(self.config.db_path())
                .await
                .unwrap_or_else(|e| {
                    tracing::warn!("failed to read page size from DB: {e}");
                    0
                });
            let ps = if db_page_size > 0 { db_page_size } else { 4096 };
            tracing::warn!("WAL file not found, using zero salts with page size {ps}");
            return (0, 0, ps);
        }

        (0, 0, 4096)
    }

    pub async fn restore(&self) -> Result<Arc<Mutex<Manifest>>> {
        let start = std::time::Instant::now();
        let manifest_with_etag = self.bucket.get_with_etag(MANIFEST_KEY).await?;

        let (mut manifest, from_bucket) = match manifest_with_etag {
            Some((data, etag)) => {
                let mut m = Manifest::deserialize(&data)?;
                m.etag = Some(etag);
                (m, true)
            }
            None => {
                let (salt_1, salt_2, page_size) = self.detect_local_salts().await;
                (Manifest::new(salt_1, salt_2, page_size), false)
            }
        };

        if from_bucket {
            let local_exists = match tokio::fs::try_exists(self.config.db_path()).await {
                Ok(exists) => exists,
                Err(e) => {
                    tracing::warn!("failed to check DB existence for restore: {e}");
                    false
                }
            };
            let local_newer = local_exists && self.local_is_newer_than_manifest(&manifest).await;

            // Safety check: if the local DB exists but is empty (no user tables),
            // never consider it "newer" than a bucket with data. This prevents
            // a stale generation file (from a previous DB that was deleted)
            // from causing us to upload an empty DB and overwrite bucket data.
            let local_newer = if local_newer && (manifest.snapshot.is_some() || manifest.shipped_frames > 0) {
                match self.is_db_empty().await {
                    Ok(true) => {
                        tracing::warn!(
                            "Local DB is empty but generation file says it was synced (gen {}). \
                             Restoring from bucket instead — the generation file may be stale.",
                            manifest.generation
                        );
                        false
                    }
                    Ok(false) => true,
                    Err(e) => {
                        tracing::warn!(
                            "Failed to check if local DB is empty: {e} — assuming not empty"
                        );
                        true
                    }
                }
            } else {
                local_newer
            };

            match self.config.restore_behavior() {
                crate::config::RestoreBehavior::UploadLocalIfNewer => {
                    if local_newer {
                        self.upload_local_as_snapshot(&mut manifest).await?;
                    } else {
                        self.download_and_reconstruct(&manifest).await?;
                    }
                }
                crate::config::RestoreBehavior::AlwaysRestoreFromBucket
                | crate::config::RestoreBehavior::Recoverable => {
                    self.download_and_reconstruct(&manifest).await?;
                }
                crate::config::RestoreBehavior::ErrorIfConflict => {
                    if local_exists && local_newer {
                        return Err(Error::Restore(
                            "Local database is newer than bucket manifest. \
                             Set restore_behavior to UploadLocalIfNewer or AlwaysRestoreFromBucket \
                             to resolve."
                                .to_string(),
                        ));
                    }
                    self.download_and_reconstruct(&manifest).await?;
                }
            }
        }

        if from_bucket {
            let elapsed = start.elapsed();
            if let Some(ref metrics) = self.metrics {
                metrics.restore_completed(elapsed.as_millis() as u64);
            }
            // Write the generation sidecar so we can detect local-vs-bucket
            // staleness on next open without relying on file mtime
            write_generation(self.config.db_path(), manifest.generation).await?;
        }

        Ok(Arc::new(Mutex::new(manifest)))
    }

    pub async fn local_is_newer_than_manifest(&self, manifest: &Manifest) -> bool {
        // A fresh bucket (gen 0, no snapshot) means local is always newer
        if manifest.generation == 0 && manifest.snapshot.is_none() {
            return true;
        }

        let local_exists = match tokio::fs::try_exists(self.config.db_path()).await {
            Ok(exists) => exists,
            Err(e) => {
                tracing::warn!("failed to check DB existence for local_is_newer: {e}");
                false
            }
        };
        if !local_exists {
            return false;
        }

        // Compare generation numbers: if the local generation file exists and
        // its generation is >= the bucket's, the local DB is at least as current.
        // This is more reliable than file mtime (which can change from touch, rsync, cp, etc).
        let local_gen = read_generation(self.config.db_path()).await.unwrap_or(None);
        match local_gen {
            Some(gen) => gen > manifest.generation,
            None => {
                let has_snapshot = manifest.snapshot.is_some();
                if has_snapshot {
                    // Bucket has a snapshot but no generation file locally.
                    // This could be a stale/wrong DB pointed at this prefix.
                    // Prefer the bucket to prevent data loss.
                    tracing::warn!(
                        "No generation file found but bucket has snapshot (gen {}) — assuming bucket is authoritative. \
                         Use `--force-takeover` or delete bucket data to upload local instead.",
                        manifest.generation
                    );
                    false
                } else {
                    // No snapshot in bucket either — can't restore from bucket.
                    // Uploading local is the only option.
                    tracing::debug!(
                        "No generation file and no snapshot — assuming local DB is newer"
                    );
                    true
                }
            }
        }
    }

    /// Check if the local DB has any user-created tables.
    /// Returns Ok(true) if the DB is empty (only sqlite internal tables),
    /// Ok(false) if it has user data, or Err on query failure.
    pub async fn is_db_empty(&self) -> Result<bool> {
        let db_path = self.config.db_path().to_path_buf();
        let is_empty = tokio::task::spawn_blocking(move || {
            let conn = rusqlite::Connection::open_with_flags(
                &db_path,
                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
            )?;
            let count: i64 = conn.query_row(
                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
                [],
                |row| row.get(0),
            )?;
            Ok::<bool, crate::error::Error>(count == 0)
        })
        .await
        .map_err(|e| crate::error::Error::Other(format!("is_db_empty join: {e}")))??;
        Ok(is_empty)
    }

    async fn upload_local_as_snapshot(&self, manifest: &mut Manifest) -> Result<()> {
        let snapshot_path = format!(
            "snapshots/{}.db",
            chrono::Utc::now().format("%Y%m%d-%H%M%S%.6f")
        );

        let (local_bytes, page_size, salt_1, salt_2) = {
            let db_path = self.config.db_path().clone();
            let wal_path = self.config.wal_path().clone();
            tokio::task::spawn_blocking(move || {
                let (s1, s2) = match WalFile::open(&wal_path) {
                    Ok(w) => (w.header().salt_1, w.header().salt_2),
                    Err(_) => {
                        tracing::warn!(
                            "Cannot read WAL file for snapshot upload — using zero salts. \
                             The WAL may have been truncated by a concurrent checkpoint."
                        );
                        (0u32, 0u32)
                    }
                };
                let conn = rusqlite::Connection::open(&db_path)?;
                conn.execute_batch("PRAGMA journal_mode = WAL")?;
                conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
                drop(conn);
                let bytes = std::fs::read(&db_path)?;
                let ps = read_page_size_from_db(&bytes)?;
                Ok::<_, crate::error::Error>((bytes, ps, s1, s2))
            })
            .await??
        };

        let checksum = crate::util::compute_sha256(&local_bytes);

        self.bucket
            .put(&snapshot_path, Bytes::from(local_bytes))
            .await?;

        let db_size = tokio::fs::metadata(self.config.db_path())
            .await
            .map(|m| m.len())
            .unwrap_or(0);

        manifest.update_snapshot(snapshot_path, checksum, salt_1, salt_2, page_size, db_size);

        // Use conditional write to prevent concurrent writers from silently
        // overwriting each other's manifests.
        let manifest_bytes = manifest.serialize()?;
        match manifest.etag.clone() {
            Some(etag) => {
                self.bucket
                    .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), &etag)
                    .await?;
            }
            None => {
                // No etag means this is a new manifest — create atomically.
                // If it already exists (concurrent writer), this fails with
                // PreconditionFailed, which is correct.
                self.bucket
                    .put_if_not_exists(MANIFEST_KEY, Bytes::from(manifest_bytes))
                    .await?;
            }
        }

        // Write generation sidecar so next open knows this DB corresponds
        // to the bucket's manifest generation
        write_generation(self.config.db_path(), manifest.generation).await?;

        Ok(())
    }

    async fn download_and_reconstruct(&self, manifest: &Manifest) -> Result<()> {
        // Before starting a new restore, check for a stale marker from a previous
        // crash (i.e. the marker exists but the rename sequence was never completed).
        // Clean up any orphaned DB + WAL temp files.
        let db_path = self.config.db_path();
        let marker_path = db_path.with_extension("db.restore-in-progress");
        if tokio::fs::try_exists(&marker_path).await.unwrap_or(false) {
            tracing::warn!(
                "Found stale restore marker — previous restore may have crashed mid-rename. \
                 Cleaning up."
            );
            let wal_tmp = db_path.with_extension("wal.restore-tmp");
            let db_tmp = db_path.with_extension("db.restore-tmp");
            tokio::fs::remove_file(&wal_tmp).await.ok();
            tokio::fs::remove_file(&db_tmp).await.ok();
            tokio::fs::remove_file(&marker_path).await.ok();
        }

        if let Some(ref snapshot_key) = manifest.snapshot {
            let tmp_path = self.config.db_path().with_extension("db.restore-tmp");
            let tmp_path_for_cleanup = tmp_path.clone();

            let result = self
                .download_and_reconstruct_inner(manifest, snapshot_key, &tmp_path)
                .await;
            if result.is_err() {
                tokio::fs::remove_file(&tmp_path_for_cleanup).await.ok();
                // Also clean up any WAL temp file
                let wal_tmp = self.config.wal_path().with_extension("wal.restore-tmp");
                tokio::fs::remove_file(&wal_tmp).await.ok();
            }
            result
        } else {
            Err(Error::Restore(
                "No snapshot found in bucket. Cannot restore without a base database.".to_string(),
            ))
        }
    }

    async fn download_and_reconstruct_inner(
        &self,
        manifest: &Manifest,
        snapshot_key: &str,
        tmp_path: &std::path::Path,
    ) -> Result<()> {
        let tmp_path_owned = tmp_path.to_path_buf();

        self.bucket.get_file(snapshot_key, &tmp_path_owned).await?;

        let (snapshot_page_size, checksum) = tokio::task::spawn_blocking({
            let tmp_path = tmp_path_owned.clone();
            move || {
                let mut file = std::fs::File::open(&tmp_path)?;
                let mut header = [0u8; 20];
                std::io::Read::read_exact(&mut file, &mut header)?;
                let page_size = read_page_size_from_db(&header)?;
                drop(file);
                let checksum = crate::util::compute_sha256_file(&tmp_path)?;
                Ok::<_, crate::error::Error>((page_size, checksum))
            }
        })
        .await??;

        if let Some(ref expected_checksum) = manifest.snapshot_checksum {
            if &checksum != expected_checksum {
                let detail = format!(
                    "Snapshot checksum mismatch: expected {}, got {}",
                    expected_checksum, checksum
                );
                match self.config.restore_behavior {
                    crate::config::RestoreBehavior::Recoverable => {
                        tracing::warn!("{} — proceeding anyway (Recoverable mode)", detail);
                        if let Some(m) = self.metrics.as_ref() {
                            m.checksum_warning(&detail)
                        }
                    }
                    _ => {
                        return Err(Error::Restore(detail));
                    }
                }
            }
        }

        // Don't rename the snapshot to the final DB path yet.
        // First, download WAL segments to a temp file, then rename both atomically.
        // This ensures we never end up with a DB file but missing WAL.
        let page_size = snapshot_page_size;

        let wal_tmp_path = self.config.wal_path().with_extension("wal.restore-tmp");

        if manifest.shipped_frames > 0 {
            self.download_wal_segments_to(manifest, page_size, &wal_tmp_path)
                .await?;
        } else {
            // No WAL frames — create an empty WAL file so the rename below works
            use tokio::io::AsyncWriteExt;
            let mut f = tokio::fs::File::create(&wal_tmp_path).await?;
            f.flush().await?;
            f.sync_all().await?;
        }

        // Both snapshot and WAL are verified and in temp files.
        // Rename atomically using a marker-file protocol:
        // 1. Write a marker so we can recover from a crash between renames
        // 2. Rename DB → final path
        // 3. Rename WAL → final path
        // 4. Delete the marker (on success)
        //
        // If we crash between steps 1 and 3, the next open() will find the
        // marker and complete the rename (or clean up if WAL temp is missing).
        let db_path = self.config.db_path();
        let wal_path = self.config.wal_path();
        let marker_path = db_path.with_extension("db.restore-in-progress");
        let marker_body = format!("wal:{}", wal_tmp_path.display());

        // Step 1: write marker (contains path to WAL temp so recovery can find it)
        tokio::fs::write(&marker_path, &marker_body).await?;

        // Step 2: rename DB
        tokio::fs::rename(&tmp_path_owned, db_path).await?;

        // Step 3: rename WAL
        tokio::fs::rename(&wal_tmp_path, wal_path).await?;

        // Step 4: delete marker (success path)
        tokio::fs::remove_file(&marker_path).await?;

        Ok(())
    }

    async fn download_wal_segments_to(
        &self,
        manifest: &Manifest,
        page_size: u32,
        tmp_wal_path: &std::path::Path,
    ) -> Result<()> {
        let prefix = manifest.segment_prefix();
        let all_keys = self.bucket.list(&prefix).await?;

        // Separate L1 files and L0 segments
        let mut l1_keys: Vec<String> = all_keys
            .iter()
            .filter(|k| k.ends_with(".l1"))
            .cloned()
            .collect();
        let mut l0_keys: Vec<String> = all_keys
            .iter()
            .filter(|k| k.ends_with(".segment"))
            .cloned()
            .collect();

        l1_keys.sort();
        l0_keys.sort();

        // Determine which L0 segments are NOT covered by any L1 file
        let l1_max = manifest.l1_max_frame_value();
        let uncovered_l0_keys: Vec<String> = l0_keys
            .into_iter()
            .filter(|k| {
                // A segment is uncovered if its start_frame >= l1_max
                // (i.e., it contains frames not in any L1 file).
                // We use start_frame rather than end_frame to handle
                // segments that straddle the L1 boundary correctly.
                // Since L0 segments are non-overlapping and sorted,
                // any segment starting at or after l1_max is entirely
                // beyond L1 coverage.
                match extract_start_frame_from_key(k) {
                    Some(start) => start >= l1_max,
                    None => true, // Can't parse, include it
                }
            })
            .collect();

        if l1_keys.is_empty() && uncovered_l0_keys.is_empty() {
            // No segments found — write just the WAL header so the
            // caller can rename the temp file to the final WAL path.
            let wal_header =
                WalHeader::synthetic(page_size, manifest.current_salt_1, manifest.current_salt_2);
            let wal_header_data = serialize_header(&wal_header);
            use tokio::io::AsyncWriteExt;
            let mut file = tokio::fs::File::create(tmp_wal_path).await?;
            file.write_all(&wal_header_data).await?;
            file.flush().await?;
            file.sync_all().await?;
            return Ok(());
        }

        let wal_header_data = match self.read_wal_header_if_exists().await {
            Some(header) => serialize_header(&header),
            None => {
                let header = WalHeader::synthetic(
                    page_size,
                    manifest.current_salt_1,
                    manifest.current_salt_2,
                );
                serialize_header(&header)
            }
        };

        let mut file = tokio::fs::File::create(tmp_wal_path).await?;
        use tokio::io::AsyncWriteExt;
        file.write_all(&wal_header_data).await?;

        // Write L1 files first (compacted base)
        for key in &l1_keys {
            let data = self
                .bucket
                .get(key)
                .await?
                .ok_or_else(|| Error::Restore(format!("L1 file not found: {key}")))?;
            // Verify L1 checksum if available in manifest
            if let Some(l1) = manifest.l1_files.iter().find(|l| &l.key == key) {
                if let Some(ref expected) = l1.checksum {
                    let actual = crate::util::compute_sha256(&data);
                    if &actual != expected {
                        return Err(Error::Restore(format!(
                            "L1 file {key} checksum mismatch: expected {expected}, got {actual}"
                        )));
                    }
                }
            }
            file.write_all(&data).await?;
        }

        // Then write uncovered L0 segments (frames beyond L1 coverage)
        for key in &uncovered_l0_keys {
            let segment_data = self
                .bucket
                .get(key)
                .await?
                .ok_or_else(|| Error::Restore(format!("Segment not found: {key}")))?;
            // Verify L0 segment checksum if available in manifest
            if let Some(expected) = manifest.segment_checksums.get(key) {
                let actual = crate::util::compute_sha256(&segment_data);
                if &actual != expected {
                    return Err(Error::Restore(format!(
                        "Segment {key} checksum mismatch: expected {expected}, got {actual}"
                    )));
                }
            } else {
                tracing::debug!(
                    "No checksum in manifest for segment {key} — skipping verification"
                );
            }
            file.write_all(&segment_data).await?;
        }

        file.flush().await?;
        file.sync_all().await?; // Ensure WAL data is durable before atomic rename
        drop(file);

        Ok(())
    }

    async fn read_wal_header_if_exists(&self) -> Option<crate::wal::WalHeader> {
        let path = self.config.wal_path().clone();
        tokio::task::spawn_blocking(move || {
            if !path.exists() {
                return None;
            }
            match crate::wal::WalFile::open(&path) {
                Ok(w) => Some(w.header().clone()),
                Err(_) => None,
            }
        })
        .await
        .ok()
        .flatten()
    }
}

fn serialize_header(header: &WalHeader) -> Vec<u8> {
    let mut buf = Vec::with_capacity(32);
    buf.extend_from_slice(&header.magic.to_be_bytes());
    buf.extend_from_slice(&header.file_format.to_be_bytes());
    buf.extend_from_slice(&header.page_size.to_be_bytes());
    buf.extend_from_slice(&header.checkpoint_seq.to_be_bytes());
    buf.extend_from_slice(&header.salt_1.to_be_bytes());
    buf.extend_from_slice(&header.salt_2.to_be_bytes());
    buf.extend_from_slice(&header.checksum_1.to_be_bytes());
    buf.extend_from_slice(&header.checksum_2.to_be_bytes());
    buf
}

pub fn read_page_size_from_db(data: &[u8]) -> Result<u32> {
    if data.len() < 20 {
        return Err(Error::Restore(
            "snapshot too small to read page size".to_string(),
        ));
    }
    let page_size = u16::from_be_bytes([data[16], data[17]]);
    let page_size = if page_size == 1 {
        65536
    } else {
        page_size as u32
    };
    Ok(page_size)
}

pub async fn read_page_size_from_db_async(path: &std::path::Path) -> Result<u32> {
    let mut file = tokio::fs::File::open(path).await?;
    let mut buf = [0u8; 20];
    tokio::io::AsyncReadExt::read_exact(&mut file, &mut buf).await?;
    drop(file);
    read_page_size_from_db(&buf)
}

/// Extract start frame from a segment/L1 key like "wal/salt/00000100-00000199.segment"
/// or "wal/salt/00000100-00000199.l1"
fn extract_start_frame_from_key(key: &str) -> Option<u32> {
    let segments: Vec<&str> = key.rsplitn(2, '/').collect();
    if segments.len() < 2 {
        return None;
    }
    let filename = segments[0];
    filename.split('-').next().and_then(|s| {
        s.strip_suffix(".segment")
            .or_else(|| s.strip_suffix(".l1"))
            .unwrap_or(s)
            .parse::<u32>()
            .ok()
    })
}