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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//! WAL frame shipper — continuously reads new WAL frames and uploads them to
//! object storage as segments.
//!
//! # Sync loop
//!
//! The `run()` method loops forever:
//! 1. Open the WAL file, find new frames since last sync
//! 2. Read frame data into a segment, upload to bucket
//! 3. Update the manifest with the new shipped frame count
//! 4. Check for manifest conflicts (remote ahead) — fatal if found
//!
//! # Backoff
//!
//! On error, exponential backoff from 0.1s to 30s max.
//! `ManifestConflict` is fatal — the shipper breaks the loop and the
//! tokio task exits. The process must restart after re-restore.
//!
//! # Conflict resolution
//!
//! Last-write-wins (no consensus). Two concurrent writers can both update
//! the manifest; the later write overwrites the earlier. This is safe when
//! only one node writes at a time (the typical embedded use case).

use bytes::Bytes;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tempfile::NamedTempFile;
use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::time::sleep;
use tracing::{error, info, warn};

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

struct SegmentResult {
    start_frame: u32,
    frames_read: u32,
    data: Bytes,
    sync_duration_ms: u64,
}

struct WalOpenResult {
    salt_1: u32,
    salt_2: u32,
    wal_truncated: bool,
    segment: Option<SegmentResult>,
}

pub struct FrameShipper {
    config: Config,
    bucket: Arc<dyn BucketStore>,
    manifest: Arc<Mutex<Manifest>>,
    last_sync: Arc<Mutex<Instant>>,
    snapshot_trigger: Arc<Notify>,
    sync_notify: Arc<Notify>,
    wal_notify: Arc<Notify>,
    shipped_frames: Arc<AtomicU32>,
    snapshot_version: Arc<AtomicU64>,
    force_snapshot: Arc<AtomicBool>,
    metrics: Arc<dyn Metrics>,
}

impl FrameShipper {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        config: Config,
        bucket: Arc<dyn BucketStore>,
        manifest: Arc<Mutex<Manifest>>,
        snapshot_trigger: Arc<Notify>,
        sync_notify: Arc<Notify>,
        wal_notify: Arc<Notify>,
        snapshot_version: Arc<AtomicU64>,
        force_snapshot: Arc<AtomicBool>,
        shipped_frames: Arc<AtomicU32>,
        metrics: Arc<dyn Metrics>,
    ) -> Self {
        FrameShipper {
            config,
            bucket,
            manifest,
            last_sync: Arc::new(Mutex::new(Instant::now())),
            snapshot_trigger,
            sync_notify,
            wal_notify,
            shipped_frames,
            snapshot_version,
            force_snapshot,
            metrics,
        }
    }

    pub fn last_sync(&self) -> Arc<Mutex<Instant>> {
        self.last_sync.clone()
    }

    pub fn sync_notify(&self) -> Arc<Notify> {
        self.sync_notify.clone()
    }

    pub async fn run(&self) {
        let mut backoff = Duration::from_millis(100);
        let mut last_gc = Instant::now();
        let mut last_compaction = Instant::now();
        let gc_interval = self.config.gc_interval();
        let compaction_interval = self.config.compaction_interval();

        loop {
            // Verify writer identity on every loop iteration.
            // This catches the case where another process deleted writer.json
            // and re-created it with a different identity.
            if let Err(e) = crate::connection::verify_writer_id(
                &self.bucket,
                self.bucket.prefix(),
                self.bucket.writer_id(),
            )
            .await
            {
                if e.is_wrong_writer() {
                    error!("WRITER IDENTITY LOST: {e} — stopping shipper to prevent corruption");
                    return;
                }
                // Transient error (bucket unavailable) — log and continue
                warn!("Writer verification failed (will retry): {e}");
            }

            // Run GC if configured and interval has elapsed
            if let Some(interval) = gc_interval {
                if last_gc.elapsed() >= interval {
                    last_gc = Instant::now();
                    match self.gc().await {
                        Ok(deleted) => {
                            if deleted > 0 {
                                info!("GC run completed, deleted {} orphaned segments", deleted);
                            }
                        }
                        Err(e) => {
                            warn!("GC failed: {}", e);
                        }
                    }
                }
            }

            // Run compaction if configured and interval has elapsed
            if let Some(interval) = compaction_interval {
                if last_compaction.elapsed() >= interval {
                    last_compaction = Instant::now();
                    match self.compact().await {
                        Ok(compacted) => {
                            if compacted > 0 {
                                info!(
                                    "Compaction run completed, compacted {} L0 segments",
                                    compacted
                                );
                            }
                        }
                        Err(e) => {
                            warn!("Compaction failed: {}", e);
                        }
                    }
                }
            }

            let result = self.sync_once().await;
            match result {
                Ok(true) => {
                    backoff = Duration::from_millis(100);
                    *self.last_sync.lock().await = Instant::now();
                    self.sync_notify.notify_waiters();
                }
                Ok(false) => {
                    *self.last_sync.lock().await = Instant::now();
                    self.sync_notify.notify_waiters();
                    match self.config.sync_mode() {
                        SyncMode::Immediate => {
                            // Use wal_notify.notified() for event-driven wakeups
                            // combined with a poll interval as fallback
                            let poll_interval = self.config.poll_interval();
                            tokio::select! {
                                _ = self.wal_notify.notified() => {
                                    // WAL changed — sync immediately
                                }
                                _ = sleep(poll_interval) => {
                                    // Poll interval elapsed — check for new frames
                                }
                            }
                        }
                        SyncMode::Lazy => {
                            sleep(self.config.poll_interval()).await;
                        }
                    }
                }
                Err(e) => {
                    error!("WAL sync error, backing off {:?}: {}", backoff, e);
                    if matches!(e, Error::ManifestConflict { .. }) {
                        error!(
                            "Manifest conflict is fatal — remote manifest is ahead. \
                            Re-restore from bucket and restart to resolve."
                        );
                        self.metrics.shipper_error(&e.to_string());
                        break;
                    }
                    self.metrics.shipper_error(&e.to_string());
                    sleep(backoff).await;
                    backoff = (backoff * 2).min(Duration::from_secs(30));
                }
            }
        }
    }

    pub async fn sync_once(&self) -> Result<bool> {
        let start_frame = self.manifest.lock().await.shipped_frames;
        let max_frames = self.config.max_frames_per_segment();

        let wal_path_clone = self.config.wal_path().clone();
        let sync_result = match tokio::task::spawn_blocking(move || {
            Self::open_and_read_frames(&wal_path_clone, start_frame, max_frames)
        })
        .await
        {
            Ok(result) => result,
            Err(e) => {
                warn!("WAL open+read task failed: {}", e);
                return Ok(false);
            }
        };

        let wal_info = match sync_result {
            Ok(info) => info,
            Err(e) => {
                if matches!(e, Error::WalParse { .. } | Error::WalChecksum { .. }) {
                    error!("WAL file is corrupt: {}", e);
                    return Err(e);
                }
                warn!("Failed to open WAL file: {}", e);
                return Ok(false);
            }
        };

        let mut manifest = self.manifest.lock().await;

        if wal_info.wal_truncated {
            self.force_snapshot.store(true, Ordering::Relaxed);
            self.snapshot_trigger.notify_one();
            self.shipped_frames
                .store(manifest.shipped_frames, Ordering::Release);
            let pre_version = self.snapshot_version.load(Ordering::Acquire);
            drop(manifest);
            info!("WAL truncated (checkpoint mid-flight), waiting for snapshot to complete");
            let deadline = Instant::now() + self.config.salt_change_timeout();
            loop {
                if self.snapshot_version.load(Ordering::Acquire) != pre_version {
                    info!("Snapshot completed (version changed), resuming with updated manifest");
                    break;
                }
                if Instant::now() > deadline {
                    warn!(
                        "Timed out waiting for snapshot after WAL truncation ({:?}), retrying",
                        self.config.salt_change_timeout()
                    );
                    break;
                }
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
            return Ok(false);
        }

        let fresh_manifest = manifest.current_salt_1 == 0 && manifest.current_salt_2 == 0;
        if manifest.is_different_salt(wal_info.salt_1, wal_info.salt_2) {
            if fresh_manifest {
                manifest.current_salt_1 = wal_info.salt_1;
                manifest.current_salt_2 = wal_info.salt_2;
            } else {
                self.force_snapshot.store(true, Ordering::Relaxed);
                self.snapshot_trigger.notify_one();
                self.shipped_frames
                    .store(manifest.shipped_frames, Ordering::Release);
                let pre_version = self.snapshot_version.load(Ordering::Acquire);
                drop(manifest);
                info!(
                    "WAL salt changed, waiting for snapshot to complete before resuming shipping"
                );
                let deadline = Instant::now() + self.config.salt_change_timeout();
                loop {
                    if self.snapshot_version.load(Ordering::Acquire) != pre_version {
                        info!(
                            "Snapshot completed (version changed), resuming with updated manifest"
                        );
                        break;
                    }
                    if Instant::now() > deadline {
                        warn!(
                            "Timed out waiting for snapshot after salt change ({:?}), retrying",
                            self.config.salt_change_timeout()
                        );
                        break;
                    }
                    tokio::time::sleep(Duration::from_millis(100)).await;
                }
                return Ok(false);
            }
        }

        let segment = match wal_info.segment {
            Some(seg) => seg,
            None => return Ok(false),
        };

        let end_frame = segment.start_frame + segment.frames_read;

        let upload_key = format!(
            "wal/{}/{start:08}-{end:08}.segment",
            manifest.salt_string(),
            start = segment.start_frame,
            end = end_frame,
        );

        let segment_len = segment.data.len() as u64;

        // Check for manifest conflicts and refresh our etag from the remote read
        if let Ok(Some((remote_data, remote_etag))) = self.bucket.get_with_etag(MANIFEST_KEY).await
        {
            if let Ok(remote) = Manifest::deserialize(&remote_data) {
                let level = manifest.conflict_level(&remote);
                match level {
                    ConflictLevel::None => {
                        // Update our local etag from the remote read so our
                        // conditional write below uses the latest known etag
                        manifest.etag = Some(remote_etag);
                        // Also merge any snapshot-related fields that the
                        // snapshot manager may have updated since our last write.
                        // Without this, the shipper would overwrite the remote
                        // manifest with stale snapshot_checksum = None.
                        manifest.snapshot = remote.snapshot.clone();
                        manifest.snapshot_checksum = remote.snapshot_checksum.clone();
                        manifest.db_size = remote.db_size;
                    }
                    ConflictLevel::RemoteAhead => {
                        return Err(Error::ManifestConflict {
                            local_gen: manifest.generation,
                            remote_gen: remote.generation,
                        });
                    }
                    ConflictLevel::LocalAhead => {
                        warn!(
                            "Manifest: local gen {} ahead of remote gen {} (normal if this node \
                             is the primary). Proceeding.",
                            manifest.generation, remote.generation
                        );
                        // Still merge remote snapshot fields and update etag
                        manifest.etag = Some(remote_etag);
                        manifest.snapshot = remote.snapshot.clone();
                        manifest.snapshot_checksum = remote.snapshot_checksum.clone();
                        manifest.db_size = remote.db_size;
                    }
                }
            }
        }

        // Check for WAL size backpressure before uploading
        if self.config.max_wal_size_bytes() > 0 {
            let wal_size = match tokio::fs::metadata(self.config.wal_path()).await {
                Ok(meta) => meta.len(),
                Err(_) => 0,
            };
            if wal_size > self.config.max_wal_size_bytes() {
                warn!(
                    "WAL size {} exceeds max {} — forcing snapshot and pausing shipping",
                    wal_size,
                    self.config.max_wal_size_bytes()
                );
                self.force_snapshot.store(true, Ordering::Relaxed);
                self.snapshot_trigger.notify_one();
                // Return false to let snapshot complete before continuing
                return Ok(false);
            }
        }

        // Compute checksum before upload (data is moved by put)
        let segment_checksum = crate::util::compute_sha256(&segment.data);

        self.bucket.put(&upload_key, segment.data).await?;

        // Store segment checksum for restore verification
        manifest
            .segment_checksums
            .insert(upload_key.clone(), segment_checksum);

        self.metrics.segment_uploaded(&upload_key, segment_len);
        self.metrics.frames_shipped(segment.frames_read);

        let prev_shipped_frames = manifest.shipped_frames;
        manifest.update_shipped_frames(end_frame);

        if let Err(e) = async {
            let manifest_bytes = manifest.serialize()?;
            let etag = manifest.etag.clone();
            drop(manifest);
            if let Some(ref etag) = etag {
                self.bucket
                    .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
                    .await
            } else {
                // No etag known (fresh manifest) — use regular put
                self.bucket
                    .put(MANIFEST_KEY, Bytes::from(manifest_bytes))
                    .await
            }
        }
        .await
        {
            error!(
                "Failed to write manifest after segment upload (precondition failed or error), rolling back segment {}: {}",
                upload_key, e
            );
            if let Err(delete_err) = self.bucket.delete(&upload_key).await {
                error!(
                    "Failed to delete rolled-back segment {}: {}",
                    upload_key, delete_err
                );
            }
            // Re-acquire manifest and restore shipped_frames
            let mut manifest = self.manifest.lock().await;
            manifest.shipped_frames = prev_shipped_frames;

            // If this was a precondition failure, re-read the remote manifest
            // to sync our local state before retrying
            if matches!(e, crate::error::Error::PreconditionFailed { .. }) {
                warn!(
                    "Manifest precondition failed — another writer updated it. Re-reading remote manifest to sync state."
                );
                if let Ok(Some((remote_data, _))) = self.bucket.get_with_etag(MANIFEST_KEY).await {
                    if let Ok(remote) = Manifest::deserialize(&remote_data) {
                        // Preserve local progress — only advance, never retreat.
                        manifest.shipped_frames =
                            std::cmp::max(manifest.shipped_frames, remote.shipped_frames);
                        manifest.generation = remote.generation;
                        manifest.etag = remote.etag;
                        tracing::info!(
                            "Synced local manifest from remote: gen={}, frames={}",
                            manifest.generation,
                            manifest.shipped_frames
                        );
                    }
                }
                // Return Ok(false) so the loop continues without backing off
                return Ok(false);
            }
            return Err(e);
        }

        info!(
            "Shipped frames {}..{} to {}",
            segment.start_frame, end_frame, upload_key
        );

        self.shipped_frames.store(end_frame, Ordering::Release);

        self.metrics.sync_completed(segment.sync_duration_ms);

        Ok(true)
    }

    /// Garbage collect orphaned WAL segments.
    ///
    /// An orphaned segment is one that:
    /// - Matches the current salt prefix (`wal/{salt_1}-{salt_2}/`)
    /// - Has a start frame less than the current `shipped_frames` count
    ///   (i.e., it's been superseded by newer segments)
    ///
    /// Segments with start frame >= shipped_frames are ACTIVE and never deleted,
    /// even if they are still being written to.
    ///
    /// **Limitation:** Only segments under the *current* salt prefix are considered.
    /// After a WAL salt change, segments from the previous salt are not cleaned up.
    /// These orphaned segments are harmless (they're just stale data) but consume
    /// storage. A future enhancement could add a separate pass for old salt prefixes.
    ///
    /// Returns the number of orphaned segments deleted.
    pub async fn gc(&self) -> Result<u32> {
        let shipped_frames;
        let l1_max;
        let prefix;
        {
            let manifest = self.manifest.lock().await;
            shipped_frames = manifest.shipped_frames;
            l1_max = manifest.l1_max_frame_value();
            prefix = format!("wal/{}/", manifest.salt_string());
        }

        if shipped_frames == 0 {
            // No frames shipped yet, nothing to gc
            return Ok(0);
        }

        // List all objects with the current salt prefix
        let listed = self.bucket.list(&prefix).await?;

        let mut deleted = 0u32;
        // Collect segment keys to remove from bucket AND from segment_checksums
        let mut keys_to_prune: Vec<String> = Vec::new();
        for key in listed {
            // Delete L0 segments (.segment) that are either:
            // 1. Orphaned: start_frame < shipped_frames (superseded by newer segments)
            // 2. Compacted: end_frame <= l1_max (fully covered by an L1 file)
            if key.ends_with(".segment") {
                if let Some(seg_start) = Self::extract_start_frame(&key) {
                    if seg_start < shipped_frames {
                        self.bucket.delete(&key).await?;
                        self.metrics.orphan_deleted(&key);
                        deleted += 1;
                        keys_to_prune.push(key.clone());
                        info!("GC deleted orphaned segment: {}", key);
                        continue;
                    }
                }
                if let Some(seg_end) = Self::extract_end_frame(&key) {
                    if seg_end <= l1_max {
                        // L0 fully covered by compaction — safe to delete
                        self.bucket.delete(&key).await?;
                        self.metrics.orphan_deleted(&key);
                        deleted += 1;
                        keys_to_prune.push(key);
                    }
                }
            }
        }

        // Prune checksums for deleted segments from the manifest
        // We hold the lock for this brief update to keep segment_checksums in sync
        if !keys_to_prune.is_empty() {
            let manifest_etag;
            {
                let mut manifest = self.manifest.lock().await;
                for key in &keys_to_prune {
                    manifest.segment_checksums.remove(key);
                }
                manifest_etag = manifest.etag.clone();
                let manifest_bytes = manifest.serialize()?;
                // Release lock before persist to avoid holding it across I/O
                drop(manifest);
                if let Some(ref etag) = manifest_etag {
                    self.bucket
                        .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
                        .await?;
                } else {
                    self.bucket
                        .put(MANIFEST_KEY, Bytes::from(manifest_bytes))
                        .await?;
                }
            }
        }

        if deleted > 0 {
            info!(
                "GC completed: deleted {} orphaned/compacted segments (shipped_frames={}, l1_max={})",
                deleted, shipped_frames, l1_max
            );
        }

        Ok(deleted)
    }

    /// Check if the error is from a truncated WAL file (exists but too small
    /// to contain a valid header, e.g. after wal_checkpoint(TRUNCATE)).
    fn is_truncated_wal(e: &Error) -> bool {
        match e {
            // Direct IO error: file too short
            Error::Io(e) => e.kind() == std::io::ErrorKind::UnexpectedEof,
            // WAL parse error with "fill whole buffer" message
            Error::WalParse { detail, .. } => detail.contains("fill whole buffer"),
            _ => false,
        }
    }

    fn extract_start_frame(key: &str) -> Option<u32> {
        // Pattern: wal/salt/start-end.segment
        // Extract start from the start-end part
        let segments: Vec<&str> = key.rsplitn(2, '/').collect();
        if segments.len() < 2 {
            return None;
        }
        let filename = segments[0]; // e.g., "00000100-00000199.segment"
        filename
            .split('-')
            .next()
            .and_then(|s| s.strip_suffix(".segment").unwrap_or(s).parse::<u32>().ok())
    }

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

    /// Compact L0 segments into L1 files.
    ///
    /// Compaction merges multiple small L0 `.segment` files into fewer,
    /// larger L1 `.l1` files. This reduces the number of GET requests
    /// needed during restore and lowers storage costs.
    ///
    /// # Algorithm
    ///
    /// 1. List all L0 segments under the current salt prefix
    /// 2. Filter out segments already covered by existing L1 files
    /// 3. If fewer than `compaction_min_segments` eligible L0s, skip
    /// 4. Merge eligible L0s into a single L1 file
    /// 5. Upload the L1, update the manifest
    /// 6. GC will delete the L0s in the next cycle
    ///
    /// Returns the number of L0 segments compacted.
    pub async fn compact(&self) -> Result<u32> {
        let manifest = self.manifest.lock().await;
        let salt_string = manifest.salt_string();
        let prefix = format!("wal/{}/", salt_string);
        let l1_max = manifest.l1_max_frame_value();
        let min_segments = self.config.compaction_min_segments();
        drop(manifest);

        // List all L0 segments
        let listed = self.bucket.list(&prefix).await?;

        let mut l0_segments: Vec<String> = listed
            .into_iter()
            .filter(|k| k.ends_with(".segment"))
            .collect();
        l0_segments.sort();

        if l0_segments.is_empty() {
            return Ok(0);
        }

        // Filter out segments already covered by L1 files
        let eligible: Vec<String> = l0_segments
            .into_iter()
            .filter(|k| {
                // A segment is covered if its end_frame <= l1_max
                match Self::extract_end_frame(k) {
                    Some(end) => end > l1_max,
                    None => true, // Can't parse, skip filtering
                }
            })
            .collect();

        if (eligible.len() as u32) < min_segments {
            return Ok(0);
        }

        // Determine the frame range for the L1 file
        let start_frame = Self::extract_start_frame(&eligible[0]).ok_or_else(|| {
            Error::Compaction("could not parse start frame from segment key".into())
        })?;
        let end_frame = Self::extract_end_frame(
            eligible
                .last()
                .ok_or_else(|| Error::Compaction("no eligible segments".into()))?,
        )
        .ok_or_else(|| Error::Compaction("could not parse end frame from segment key".into()))?;

        // Download and merge all eligible L0 segments into a NamedTempFile.
        // NamedTempFile uses a random suffix so the path is unpredictable and
        // the file is automatically cleaned up if we return early on error.
        let tmp_dir = std::path::Path::new("/tmp");
        let mut tmp_file = NamedTempFile::new_in(tmp_dir)
            .map_err(|e| Error::Compaction(format!("create temp file: {e}")))?;

        for key in &eligible {
            let segment_data = self
                .bucket
                .get(key)
                .await?
                .ok_or_else(|| Error::Compaction(format!("segment not found: {key}")))?;
            use std::io::Write;
            tmp_file
                .write_all(&segment_data)
                .map_err(|e| Error::Compaction(format!("write temp file: {e}")))?;
        }
        use std::io::Seek;
        tmp_file
            .seek(std::io::SeekFrom::Start(0))
            .map_err(|e| Error::Compaction(format!("seek temp file: {e}")))?;

        // Get the temp file path BEFORE upload (NamedTempFile keeps the file
        // alive even after we drop the handle, but we need the path string).
        let tmp_path = tmp_file.path().to_path_buf();
        let l1_size = std::fs::metadata(&tmp_path).map(|m| m.len()).unwrap_or(0);

        // Upload the L1 file from the temp file (streaming, no full-blob in memory)
        let l1_key = format!("wal/{}/{:08}-{:08}.l1", salt_string, start_frame, end_frame);
        self.bucket.put_file(&l1_key, &tmp_path).await?;

        // Compute L1 checksum for restore verification
        let l1_checksum = crate::util::compute_sha256_file(&tmp_path)
            .map_err(|e| Error::Compaction(format!("L1 checksum: {e}")))?;

        // NamedTempFile auto-deletes the temp file when it goes out of scope.
        // Explicit close is not required — drop is sufficient.
        drop(tmp_file);

        let l1 = L1File {
            key: l1_key.clone(),
            start_frame,
            end_frame,
            source_count: eligible.len() as u32,
            checksum: Some(l1_checksum),
        };

        // Update manifest with the new L1 file
        let mut manifest = self.manifest.lock().await;
        manifest.add_l1_file(l1);
        manifest.generation = manifest.generation.wrapping_add(1);

        // Write manifest (with etag if available)
        if let Err(e) = async {
            let manifest_bytes = manifest.serialize()?;
            let etag = manifest.etag.clone();
            drop(manifest);
            if let Some(ref etag) = etag {
                self.bucket
                    .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
                    .await
            } else {
                self.bucket
                    .put(MANIFEST_KEY, Bytes::from(manifest_bytes))
                    .await
            }
        }
        .await
        {
            // Rollback: delete the L1 file we just uploaded
            warn!(
                "Failed to write manifest after compaction, rolling back L1 {}: {}",
                l1_key, e
            );
            if let Err(delete_err) = self.bucket.delete(&l1_key).await {
                warn!("Failed to delete rolled-back L1 {}: {}", l1_key, delete_err);
            }
            // Re-acquire manifest and remove the L1 entry
            let mut manifest = self.manifest.lock().await;
            manifest.l1_files.retain(|l| l.key != l1_key);
            manifest.l1_max_frame = manifest.l1_files.iter().map(|l| l.end_frame).max();
            return Err(e);
        }

        self.metrics
            .segment_compacted(eligible.len() as u32, &l1_key);
        info!(
            "Compacted {} L0 segments into L1 {} ({}..{}, {} bytes)",
            eligible.len(),
            l1_key,
            start_frame,
            end_frame,
            l1_size
        );

        Ok(eligible.len() as u32)
    }

    fn open_and_read_frames(
        path: &Path,
        start_frame: u32,
        max_frames: u32,
    ) -> Result<WalOpenResult> {
        let wal = match WalFile::open(path) {
            Ok(w) => w,
            Err(e) if e.is_io_not_found() => {
                return Ok(WalOpenResult {
                    salt_1: 0,
                    salt_2: 0,
                    wal_truncated: false,
                    segment: None,
                });
            }
            // WAL file exists but is empty or too small to contain a valid header.
            // This happens after wal_checkpoint(TRUNCATE) truncates the WAL to 0 bytes
            // before SQLite writes a new header. Treat as "no WAL available" — the
            // shipper will retry on the next cycle when the header appears.
            Err(e) if e.is_io_not_found() || Self::is_truncated_wal(&e) => {
                return Ok(WalOpenResult {
                    salt_1: 0,
                    salt_2: 0,
                    wal_truncated: false,
                    segment: None,
                });
            }
            Err(e) => return Err(e),
        };

        let salt_1 = wal.header().salt_1;
        let salt_2 = wal.header().salt_2;

        let wal_truncated = start_frame > 0 && wal.total_frames() < start_frame;

        let new_frames = wal.total_frames().saturating_sub(start_frame);
        if new_frames == 0 {
            return Ok(WalOpenResult {
                salt_1,
                salt_2,
                wal_truncated,
                segment: None,
            });
        }

        let total_to_ship = std::cmp::min(new_frames, max_frames);
        let page_size = wal.page_size();
        let big_endian = wal.header().magic == 0x377f0683;
        let initial_prev_cksum_1 = wal.header().checksum_1;
        let initial_prev_cksum_2 = wal.header().checksum_2;

        let sync_start = Instant::now();
        let mut file = std::fs::File::open(path)?;
        let mut data = Vec::with_capacity(
            (total_to_ship as usize) * (WalFrame::frame_size(page_size) as usize),
        );
        let mut frames_read = 0u32;
        let mut prev_cksum_1 = initial_prev_cksum_1;
        let mut prev_cksum_2 = initial_prev_cksum_2;

        if start_frame > 0 {
            if let Some(frame) = WalFrame::read(
                &mut file,
                start_frame - 1,
                page_size,
                prev_cksum_1,
                prev_cksum_2,
                big_endian,
                start_frame == 1,
            )? {
                prev_cksum_1 = frame.checksum_1;
                prev_cksum_2 = frame.checksum_2;
            }
        }

        for i in 0..total_to_ship {
            let frame_idx = start_frame + i;
            match WalFrame::read(
                &mut file,
                frame_idx,
                page_size,
                prev_cksum_1,
                prev_cksum_2,
                big_endian,
                true,
            )? {
                Some(frame) => {
                    prev_cksum_1 = frame.checksum_1;
                    prev_cksum_2 = frame.checksum_2;
                    data.extend_from_slice(&frame.page_number.to_be_bytes());
                    data.extend_from_slice(&frame.db_size_after.to_be_bytes());
                    data.extend_from_slice(&frame.salt_1.to_be_bytes());
                    data.extend_from_slice(&frame.salt_2.to_be_bytes());
                    data.extend_from_slice(&frame.checksum_1.to_be_bytes());
                    data.extend_from_slice(&frame.checksum_2.to_be_bytes());
                    data.extend_from_slice(&frame.data);
                    frames_read += 1;
                }
                None => break,
            }
        }

        if frames_read == 0 {
            return Ok(WalOpenResult {
                salt_1,
                salt_2,
                wal_truncated,
                segment: None,
            });
        }

        Ok(WalOpenResult {
            salt_1,
            salt_2,
            wal_truncated: false,
            segment: Some(SegmentResult {
                start_frame,
                frames_read,
                data: Bytes::from(data),
                sync_duration_ms: sync_start.elapsed().as_millis() as u64,
            }),
        })
    }
}