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
use bytes::Bytes;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tracing::{info, warn};

use crate::config::{Config, SyncMode};
use crate::error::{Error, Result};
use crate::metrics::{noop_metrics, Metrics};
use crate::replication::manifest::{Manifest, MANIFEST_KEY};
use crate::replication::{FrameShipper, SnapshotManager};
use crate::restore::{self, RestoreEngine};
use crate::storage::BucketStore;
use crate::wal::WalFile;

const REPLICA_LOCK_KEY: &str = "lock.json";
const WRITER_KEY: &str = "writer.json";
const REPLICA_LOCK_STALE_SECS: u64 = 30;
const REPLICA_LOCK_HEARTBEAT_SECS: u64 = 10;

#[derive(Debug, Clone)]
pub struct HealthReport {
    pub healthy: bool,
    pub replicator_alive: bool,
    pub snapshot_alive: bool,
    pub watcher_alive: bool,
    pub last_sync_ago: std::time::Duration,
    pub health_timeout: std::time::Duration,
}

impl std::fmt::Display for HealthReport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "healthy={} replicator={} snapshot={} watcher={} last_sync_ago={:?} timeout={:?}",
            self.healthy,
            self.replicator_alive,
            self.snapshot_alive,
            self.watcher_alive,
            self.last_sync_ago,
            self.health_timeout,
        )
    }
}

/// The core type — manages a SQLite database with automatic S3 backup.
///
/// `DurabilityLayer` wraps a [`rusqlite::Connection`] and continuously ships
/// WAL frames to an S3-compatible bucket in the background. On startup it
/// restores the local DB from the bucket if needed.
///
/// # Lifecycle
///
/// 1. [`DurabilityLayer::open()`] — acquire locks, restore if needed, start background tasks
/// 2. `layer.with_conn()` — run SQL statements
/// 3. `layer.shutdown()` — checkpoint WAL, final sync, release locks
///
/// # Multi-writer protection
///
/// `open()` acquires three guards:
/// - **flock** on `.db.lock` — prevents two processes on the same machine
/// - **lock.json** in bucket — prevents two processes anywhere (with heartbeat)
/// - **writer.json** in bucket — permanent ownership record
///
/// If any guard fails, `open()` returns an error.
pub struct DurabilityLayer {
    conn: Arc<Mutex<rusqlite::Connection>>,
    last_sync: Arc<Mutex<Instant>>,
    replicator_handle: JoinHandle<()>,
    snapshot_handle: JoinHandle<()>,
    snapshot_trigger: Arc<Notify>,
    sync_notify: Arc<Notify>,
    wal_notify: Arc<Notify>,
    snapshot_mgr: Arc<SnapshotManager>,
    _watcher_handle: Option<JoinHandle<()>>,
    shipped_frames: Arc<AtomicU32>,
    health_timeout: std::time::Duration,
    sync_timeout: std::time::Duration,
    wal_path: std::path::PathBuf,
    db_path: std::path::PathBuf,
    /// File descriptor holding the flock. Kept alive for the lifetime of
    /// the DurabilityLayer. Released on Drop, preventing two processes
    /// from opening the same database file.
    _db_lock_file: std::fs::File,
    /// Heartbeat task for the bucket replica lock. None if replica lock is disabled.
    _replica_lock_heartbeat: Option<JoinHandle<()>>,
}

/// Acquire an exclusive file lock on a lock file adjacent to the database.
/// Uses a `.db.lock` file (not the DB itself) to avoid interfering with SQLite's
/// own file locking. The lock is released when the File is dropped (shutdown/drop).
fn acquire_db_lock(db_path: &std::path::Path) -> crate::error::Result<std::fs::File> {
    let lock_path = db_path.with_extension("db.lock");
    let file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
        .map_err(crate::error::Error::Io)?;

    use std::os::unix::io::AsRawFd;
    let fd = file.as_raw_fd();
    // LOCK_EX = 2, LOCK_NB = 4
    let result = unsafe { libc::flock(fd, 2 | 4) };
    if result == 0 {
        // Write our PID for informational purposes
        use std::io::Write;
        let mut f = std::fs::File::create(&lock_path).map_err(crate::error::Error::Io)?;
        write!(f, "{}", std::process::id()).ok();
        Ok(file)
    } else {
        let holder_pid = read_lock_pid(db_path).unwrap_or(0);
        Err(crate::error::Error::DatabaseLocked {
            path: db_path.to_path_buf(),
            holder_pid,
        })
    }
}

/// Try to read the PID from a sidecar lock file (best-effort, informational only).
/// The real lock is the flock, not this file.
fn read_lock_pid(db_path: &std::path::Path) -> Option<u32> {
    let lock_path = db_path.with_extension("db.lock");
    std::fs::read_to_string(lock_path)
        .ok()
        .and_then(|s| s.trim().parse::<u32>().ok())
}

/// Replica lock data stored in lock.json in the bucket.
#[derive(serde::Serialize, serde::Deserialize, Clone)]
struct ReplicaLock {
    pid: u32,
    hostname: String,
    started_at: String,
    last_heartbeat: String,
}

impl ReplicaLock {
    fn new() -> Self {
        let now = chrono::Utc::now().to_rfc3339();
        let hostname = std::env::var("HOSTNAME")
            .or_else(|_| std::env::var("HOST"))
            .unwrap_or_else(|_| "unknown".to_string());
        ReplicaLock {
            pid: std::process::id(),
            hostname,
            started_at: now.clone(),
            last_heartbeat: now,
        }
    }

    fn with_updated_heartbeat(&self) -> Self {
        ReplicaLock {
            last_heartbeat: chrono::Utc::now().to_rfc3339(),
            ..self.clone()
        }
    }

    /// Check if the lock is stale (heartbeat older than REPLICA_LOCK_STALE_SECS).
    fn is_stale(&self) -> bool {
        let Ok(heartbeat) = self.last_heartbeat.parse::<chrono::DateTime<chrono::Utc>>() else {
            // Can't parse timestamp — treat as stale to be safe
            return true;
        };
        let age = chrono::Utc::now() - heartbeat;
        age > chrono::Duration::seconds(REPLICA_LOCK_STALE_SECS as i64)
    }
}

/// Verify that this process is the authorized writer for this bucket prefix.
/// Reads `writer.json` from the bucket — if it exists, our writer_id must match.
/// If it doesn't exist, we create it atomically (we're the first writer).
///
/// This prevents the most dangerous scenario: two different servers accidentally
/// configured with the same bucket prefix, silently overwriting each other's data.
pub(crate) async fn verify_writer_id(
    bucket: &Arc<dyn BucketStore>,
    prefix: &str,
    our_writer_id: &str,
) -> crate::error::Result<()> {
    match bucket.get(WRITER_KEY).await {
        Ok(Some(existing_data)) => {
            // writer.json exists — parse it and compare
            let stored_writer_id = String::from_utf8_lossy(&existing_data).trim().to_string();
            if stored_writer_id == our_writer_id {
                tracing::trace!("Writer identity verified: {our_writer_id}");
                Ok(())
            } else {
                tracing::error!(
                    "WRITER MISMATCH: this process is '{our_writer_id}' but bucket prefix '{prefix}' is owned by '{stored_writer_id}'"
                );
                Err(Error::WrongWriter {
                    prefix: prefix.to_string(),
                    expected_writer: stored_writer_id,
                    actual_writer: our_writer_id.to_string(),
                })
            }
        }
        Ok(None) => {
            // No writer.json yet — we're the first writer. Create it atomically.
            let bytes = Bytes::from(our_writer_id.as_bytes().to_vec());
            match bucket.put_if_not_exists(WRITER_KEY, bytes).await {
                Ok(()) => {
                    tracing::info!("Registered as writer for prefix '{prefix}': {our_writer_id}");
                    Ok(())
                }
                Err(Error::PreconditionFailed { .. }) => {
                    // Race: another process created writer.json between our get and put.
                    // Re-read and verify.
                    let data = bucket
                        .get(WRITER_KEY)
                        .await?
                        .ok_or_else(|| Error::Other("writer.json disappeared".to_string()))?;
                    let stored = String::from_utf8_lossy(&data).trim().to_string();
                    if stored == our_writer_id {
                        Ok(()) // Another instance of the same writer
                    } else {
                        Err(Error::WrongWriter {
                            prefix: prefix.to_string(),
                            expected_writer: stored,
                            actual_writer: our_writer_id.to_string(),
                        })
                    }
                }
                Err(e) => {
                    // Can't write to bucket — writer verification is safety-critical,
                    // so we must fail rather than silently bypass the check.
                    tracing::error!(
                        "Cannot write writer.json to bucket: {e} — refusing to start"
                    );
                    Err(e)
                }
            }
        }
        Err(e) => {
            // Can't read from bucket — writer verification is safety-critical.
            tracing::error!(
                "Cannot read writer.json from bucket: {e} — refusing to start"
            );
            Err(e)
        }
    }
}

/// Acquire the bucket replica lock atomically. Returns (ReplicaLock, lock_etag) on success.
/// Uses `put_if_not_exists` for the initial creation (atomic), and `put_if_match` for
/// stale lock acquisition (atomic with etag check). This ensures no two processes can
/// ever acquire the same lock simultaneously.
async fn acquire_replica_lock(
    bucket: &Arc<dyn BucketStore>,
) -> crate::error::Result<(ReplicaLock, String)> {
    let lock = ReplicaLock::new();
    let lock_bytes = serde_json::to_vec(&lock)
        .map_err(|e| Error::Other(format!("serialize replica lock: {e}")))?;

    // Step 1: Try atomic create-if-not-exists
    match bucket
        .put_if_not_exists(REPLICA_LOCK_KEY, lock_bytes.clone().into())
        .await
    {
        Ok(()) => {
            // We atomically created the lock — we own it
            tracing::debug!("Acquired replica lock (new creation)");
            if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
                Ok((lock, our_etag))
            } else {
                Ok((lock, String::new()))
            }
        }
        Err(Error::PreconditionFailed { .. }) => {
            // Lock already exists — check if it's stale
            let (existing_data, existing_etag) = bucket
                .get_with_etag(REPLICA_LOCK_KEY)
                .await?
                .ok_or_else(|| Error::Other("Lock exists but can't be read".to_string()))?;

            match serde_json::from_slice::<ReplicaLock>(&existing_data) {
                Ok(existing_lock) => {
                    if !existing_lock.is_stale() {
                        // Fresh lock from another holder — REFUSE
                        tracing::warn!(
                            "Replica lock held by PID {} on {} (heartbeat {})",
                            existing_lock.pid,
                            existing_lock.hostname,
                            existing_lock.last_heartbeat
                        );
                        return Err(Error::ReplicaLocked {
                            prefix: REPLICA_LOCK_KEY.to_string(),
                            holder_pid: existing_lock.pid,
                            holder_hostname: existing_lock.hostname,
                            last_heartbeat: existing_lock.last_heartbeat,
                        });
                    }
                    // Stale lock — force-acquire atomically via etag check
                    tracing::info!(
                        "Stale replica lock detected (holder PID {} on {}, last heartbeat {}), force-acquiring",
                        existing_lock.pid, existing_lock.hostname, existing_lock.last_heartbeat
                    );
                    bucket
                        .put_if_match(REPLICA_LOCK_KEY, lock_bytes.into(), &existing_etag)
                        .await?;
                    if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
                        Ok((lock, our_etag))
                    } else {
                        Ok((lock, String::new()))
                    }
                }
                Err(_) => {
                    // Can't parse existing lock — treat as stale, force-acquire atomically
                    tracing::warn!("Cannot parse existing replica lock, force-acquiring");
                    bucket
                        .put_if_match(REPLICA_LOCK_KEY, lock_bytes.into(), &existing_etag)
                        .await?;
                    if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
                        Ok((lock, our_etag))
                    } else {
                        Ok((lock, String::new()))
                    }
                }
            }
        }
        Err(e) => {
            // Can't write lock — bucket lock is safety-critical, refuse to start.
            tracing::error!(
                "Cannot write replica lock to bucket: {e} — refusing to start"
            );
            Err(e)
        }
    }
}

impl DurabilityLayer {
    /// Open a DurabilityLayer — the main entry point.
    ///
    /// This acquires the local file lock, verifies writer identity,
    /// acquires the bucket replica lock, restores from S3 if needed,
    /// validates bucket integrity, and starts background replication tasks.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DatabaseLocked`] if another process holds the local DB lock.
    /// Returns [`Error::ReplicaLocked`] if another process holds the bucket lock.
    /// Returns [`Error::WrongWriter`] if another server owns this bucket prefix.
    pub async fn open(config: Config, bucket: Arc<dyn BucketStore>) -> Result<Self> {
        Self::open_with_metrics(config, bucket, noop_metrics()).await
    }

    pub async fn open_with_metrics(
        config: Config,
        bucket: Arc<dyn BucketStore>,
        metrics: Arc<dyn Metrics>,
    ) -> Result<Self> {
        config
            .validate()
            .map_err(|e| crate::error::Error::Config(format!("invalid config: {e}")))?;

        // Acquire exclusive file lock on the database to prevent two processes
        // from opening the same DB. This is kernel-enforced and released on process death.
        let db_lock_file = acquire_db_lock(config.db_path())?;

        // Verify writer identity — make sure THIS process is the authorized
        // writer for this bucket prefix. writer.json is permanent (survives shutdown).
        verify_writer_id(&bucket, bucket.prefix(), bucket.writer_id()).await?;

        // Acquire bucket replica lock to prevent two processes anywhere from
        // replicating to the same bucket prefix.
        let _replica_lock_guard = if config.replica_lock_enabled() {
            let (replica_lock, replica_lock_etag) = acquire_replica_lock(&bucket).await?;

            // Start heartbeat task for the replica lock
            // Uses put_if_match with our etag — if another process force-acquired
            // our lock, our heartbeat fails safely instead of overwriting theirs.
            let heartbeat_bucket = bucket.clone();
            let heartbeat_lock = replica_lock.clone();
            let heartbeat_etag = replica_lock_etag.clone();
            let heartbeat_handle = tokio::spawn(async move {
                let mut current_etag = heartbeat_etag;
                loop {
                    tokio::time::sleep(std::time::Duration::from_secs(REPLICA_LOCK_HEARTBEAT_SECS))
                        .await;
                    let updated = heartbeat_lock.with_updated_heartbeat();
                    let bytes = match serde_json::to_vec(&updated) {
                        Ok(b) => b,
                        Err(e) => {
                            tracing::error!("Failed to serialize replica lock heartbeat: {e}");
                            continue;
                        }
                    };
                    match heartbeat_bucket
                        .put_if_match(REPLICA_LOCK_KEY, bytes.into(), &current_etag)
                        .await
                    {
                        Ok(()) => {
                            // Update our etag for next heartbeat
                            if let Ok(Some((_, new_etag))) =
                                heartbeat_bucket.get_with_etag(REPLICA_LOCK_KEY).await
                            {
                                current_etag = new_etag;
                            }
                        }
                        Err(e) if e.is_precondition_failed() => {
                            // Another process acquired our lock — stop heartbeating
                            tracing::error!("Replica lock was acquired by another process — stopping heartbeat. THIS SHOULD NOT HAPPEN in normal operation.");
                            return;
                        }
                        Err(e) => {
                            tracing::warn!("Failed to update replica lock heartbeat: {e}");
                        }
                    }
                }
            });
            Some(heartbeat_handle)
        } else {
            None
        };

        let restore = RestoreEngine::new(config.clone(), bucket.clone());
        let manifest = restore.with_metrics(metrics.clone()).restore().await?;

        // Validate bucket integrity after restore — check that all referenced
        // objects exist and checksums match. Log warnings for inconsistencies.
        {
            let m = manifest.lock().await;
            validate_manifest_against_bucket(&m, &bucket).await;
        }

        let conn = rusqlite::Connection::open(config.db_path())?;

        conn.execute_batch("PRAGMA journal_mode = WAL")?;
        conn.execute_batch("PRAGMA wal_autocheckpoint = 0")?;
        conn.execute_batch("PRAGMA synchronous = NORMAL")?;

        let conn = Arc::new(Mutex::new(conn));

        let snapshot_trigger = Arc::new(Notify::new());
        let sync_notify = Arc::new(Notify::new());
        let wal_notify = Arc::new(Notify::new());
        let snapshot_version = Arc::new(AtomicU64::new(0));
        let shipped_frames = Arc::new(AtomicU32::new(0));
        let force_next = Arc::new(AtomicBool::new(false));

        let wal_notify_clone = wal_notify.clone();
        let wal_path = config.wal_path().clone();
        let immediate_poll_interval = config.immediate_poll_interval();
        let watcher_handle = if config.sync_mode() == &SyncMode::Immediate {
            let handle = tokio::spawn(async move {
                let mut last_size: u64 = 0;
                loop {
                    tokio::time::sleep(immediate_poll_interval).await;
                    if let Ok(meta) = tokio::fs::metadata(&wal_path).await {
                        let new_size = meta.len();
                        if new_size != last_size {
                            last_size = new_size;
                            wal_notify_clone.notify_one();
                        }
                    }
                }
            });
            Some(handle)
        } else {
            None
        };

        let shipper = FrameShipper::new(
            config.clone(),
            bucket.clone(),
            manifest.clone(),
            snapshot_trigger.clone(),
            sync_notify.clone(),
            wal_notify.clone(),
            snapshot_version.clone(),
            force_next.clone(),
            shipped_frames.clone(),
            metrics.clone(),
        );
        let last_sync = shipper.last_sync();

        let snap_mgr = Arc::new(SnapshotManager::new(
            config.clone(),
            bucket.clone(),
            manifest.clone(),
            snapshot_trigger.clone(),
            snapshot_version.clone(),
            force_next.clone(),
            metrics.clone(),
            conn.clone(),
        ));

        let health_timeout = config.health_timeout();
        let sync_timeout = config.sync_timeout();

        let replicator_handle = tokio::spawn({
            let shipper = shipper;
            async move {
                shipper.run().await;
            }
        });

        let snapshot_handle = tokio::spawn({
            let snap_mgr = snap_mgr.clone();
            async move {
                snap_mgr.run().await;
            }
        });

        info!("DurabilityLayer initialized");
        info!("  DB path: {}", config.db_path().display());
        info!("  Poll interval: {:?}", config.poll_interval());
        info!("  Sync mode: {:?}", config.sync_mode());
        info!(
            "  Snapshot threshold: {}MB",
            config.snapshot_threshold_bytes() / 1024 / 1024
        );

        Ok(DurabilityLayer {
            conn,
            last_sync,
            replicator_handle,
            snapshot_handle,
            snapshot_trigger,
            sync_notify,
            wal_notify,
            snapshot_mgr: snap_mgr,
            _watcher_handle: watcher_handle,
            shipped_frames,
            health_timeout,
            sync_timeout,
            wal_path: config.wal_path().clone(),
            db_path: config.db_path().clone(),
            _db_lock_file: db_lock_file,
            _replica_lock_heartbeat: _replica_lock_guard,
        })
    }

    /// Wait for all pending WAL frames to be shipped to the bucket.
    ///
    /// Returns once the shipper has caught up, or times out after `sync_timeout`
    /// (default 5s). On timeout, returns an error — the WAL frames remain locally
    /// and will be retried on the next sync.
    pub async fn sync_now(&self) -> Result<()> {
        {
            let guard = self.conn.lock().await;
            guard.execute_batch("BEGIN")?;
            guard.execute_batch("COMMIT")?;
        }

        self.wal_notify.notify_one();

        let deadline = Instant::now() + self.sync_timeout;
        let mut iteration = 0u32;
        loop {
            iteration += 1;

            if iteration == 1 || iteration % 10 == 0 {
                let current = self.shipped_frames.load(Ordering::Acquire);
                let wal_path = self.wal_path.clone();
                let has_pending =
                    tokio::task::spawn_blocking(move || match WalFile::open(&wal_path) {
                        Ok(w) => w.total_frames() > current,
                        Err(_) => false,
                    })
                    .await
                    .unwrap_or(false);

                if !has_pending {
                    *self.last_sync.lock().await = Instant::now();
                    return Ok(());
                }
            }

            if Instant::now() > deadline {
                return Err(crate::error::Error::Replication(format!(
                    "sync timeout: WAL frames not shipped within {:?}",
                    self.sync_timeout
                )));
            }
            // Wait for the shipper to signal completion, with a fallback poll.
            // sync_notify fires when the shipper completes a sync cycle.
            let remaining = deadline.saturating_duration_since(Instant::now());
            tokio::select! {
                _ = self.sync_notify.notified() => {
                    // Shipper completed a sync — check again on next iteration
                }
                _ = tokio::time::sleep(remaining.min(std::time::Duration::from_millis(50))) => {
                    // Timeout or poll interval — check shipped_frames again
                }
            }
        }
    }

    pub async fn last_sync(&self) -> Instant {
        *self.last_sync.lock().await
    }

    pub async fn is_healthy(&self) -> bool {
        self.health_report().await.healthy
    }

    pub async fn health_report(&self) -> HealthReport {
        let replicator_alive = !self.replicator_handle.is_finished();
        let snapshot_alive = !self.snapshot_handle.is_finished();
        let watcher_alive = match &self._watcher_handle {
            Some(h) => !h.is_finished(),
            None => true,
        };
        let last_sync_ago = self.last_sync.lock().await.elapsed();
        let healthy = replicator_alive
            && snapshot_alive
            && watcher_alive
            && last_sync_ago < self.health_timeout;
        HealthReport {
            healthy,
            replicator_alive,
            snapshot_alive,
            watcher_alive,
            last_sync_ago,
            health_timeout: self.health_timeout,
        }
    }

    pub async fn conn(&self) -> tokio::sync::MutexGuard<'_, rusqlite::Connection> {
        self.conn.lock().await
    }

    /// Run a closure with exclusive access to the [`rusqlite::Connection`].
    ///
    /// This is the preferred way to execute SQL. The connection is held under
    /// a Tokio mutex, so the closure should be short-lived.
    ///
    /// # Example
    ///
    /// ```ignore
    /// layer.with_conn(|conn| {
    ///     conn.execute("INSERT INTO users (name) VALUES (?)", ["Alice"])
    /// })?;
    /// ```
    pub async fn with_conn<F, T>(&self, f: F) -> Result<T>
    where
        F: FnOnce(&rusqlite::Connection) -> rusqlite::Result<T>,
    {
        let guard = self.conn.lock().await;
        f(&guard).map_err(crate::error::Error::from)
    }

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

    /// Force an immediate snapshot upload to the bucket.
    ///
    /// Triggers `VACUUM INTO` and uploads the resulting DB file.
    /// Normally snapshots happen automatically based on WAL size and time
    /// intervals, but this is useful for ensuring data is durably in S3
    /// before shutdown or during testing.
    pub async fn force_snapshot(&self) -> Result<()> {
        // Take the snapshot directly. We clear force_next afterward so the
        // snapshot manager's run() loop doesn't also take a duplicate snapshot
        // when it wakes up from the trigger notification.
        let result = self.snapshot_mgr.take_snapshot().await;
        self.snapshot_mgr
            .force_next()
            .store(false, Ordering::Relaxed);
        self.snapshot_trigger.notify_one();
        result
    }

    /// Graceful shutdown — checkpoint WAL, final sync, release locks.
    ///
    /// This should always be called before dropping the DurabilityLayer.
    /// If the layer is dropped without calling `shutdown()`, a warning is
    /// logged and the WAL may not be checkpointed.
    pub async fn shutdown(&self) -> Result<()> {
        info!("DurabilityLayer shutting down");

        // Ship all pending WAL frames before shutting down.
        // This ensures the bucket is up-to-date before we checkpoint.
        // Ignore timeout errors — best effort, the checkpoint will still happen.
        if let Err(e) = self.sync_now().await {
            warn!("Final sync on shutdown failed (data still in local WAL): {e}");
        }

        // Signal the snapshot manager to stop its loop
        self.snapshot_mgr.shutdown_notify().notify_one();

        // Now abort background tasks — the shipper has already shipped everything
        self.replicator_handle.abort();
        self.snapshot_handle.abort();
        if let Some(h) = self._replica_lock_heartbeat.as_ref() {
            h.abort();
        }
        if let Some(handle) = &self._watcher_handle {
            handle.abort();
        }

        // Release the bucket replica lock
        if let Err(e) = self.snapshot_mgr.bucket().delete(REPLICA_LOCK_KEY).await {
            tracing::warn!("Failed to delete replica lock on shutdown: {e}");
        } else {
            tracing::info!("Replica lock released on shutdown");
        }

        // Write the current manifest generation to the sidecar file.
        // This ensures the next open knows this DB was synced up to this
        // generation, preventing unnecessary re-download from the bucket.
        if let Ok(Some(data)) = self.snapshot_mgr.bucket().get(MANIFEST_KEY).await {
            if let Ok(manifest) = Manifest::deserialize(&data) {
                if let Err(e) = restore::write_generation(&self.db_path, manifest.generation).await
                {
                    tracing::warn!("Failed to write generation file on shutdown: {e}");
                }
            }
        }

        let guard = self.conn.lock().await;
        guard.execute_batch("PRAGMA wal_checkpoint(FULL)")?;
        drop(guard);

        Ok(())
    }
}

impl Drop for DurabilityLayer {
    /// Logs a warning if shutdown() wasn't called.
    /// Calling `shutdown()` explicitly is the recommended cleanup path — it
    /// safely checkpoints the WAL on the Tokio runtime thread.
    fn drop(&mut self) {
        self.replicator_handle.abort();
        self.snapshot_handle.abort();
        if let Some(handle) = &self._watcher_handle {
            handle.abort();
        }
        if let Some(handle) = &self._replica_lock_heartbeat {
            handle.abort();
        }
        tracing::warn!(concat!(
            "DurabilityLayer dropped without calling shutdown() — ",
            "WAL may not be checkpointed. Call shutdown() explicitly for clean shutdown."
        ));
    }
}

/// Validate manifest against bucket contents after restore.
/// Checks that all referenced objects exist and checksums are consistent.
/// Logs warnings for inconsistencies but does NOT fail — the restore already succeeded
/// and the DB is usable. Warnings indicate potential data integrity concerns.
pub(crate) async fn validate_manifest_against_bucket(
    manifest: &crate::replication::Manifest,
    bucket: &Arc<dyn BucketStore>,
) {
    let mut warnings = 0u32;
    let mut errors = 0u32;

    // 1. Snapshot must exist if referenced
    if let Some(ref snap_key) = manifest.snapshot {
        match bucket.exists(snap_key).await {
            Ok(true) => {
                tracing::debug!("Bucket validation: snapshot '{snap_key}' exists");
            }
            Ok(false) => {
                tracing::error!(
                    "Bucket validation: snapshot '{snap_key}' referenced in manifest but MISSING from bucket!"
                );
                errors += 1;
            }
            Err(e) => {
                tracing::warn!("Bucket validation: cannot verify snapshot '{snap_key}': {e}");
                warnings += 1;
            }
        }
    } else if manifest.generation > 0 {
        // A non-fresh manifest should have a snapshot
        tracing::warn!(
            "Bucket validation: manifest generation {} has no snapshot",
            manifest.generation
        );
        warnings += 1;
    }

    // 2. L1 segments must exist
    for seg in &manifest.l1_files {
        match bucket.exists(&seg.key).await {
            Ok(true) => {
                tracing::debug!("Bucket validation: L1 segment '{}' exists", seg.key);
            }
            Ok(false) => {
                tracing::error!(
                    "Bucket validation: L1 segment '{}' referenced in manifest but MISSING from bucket!",
                    seg.key
                );
                errors += 1;
            }
            Err(e) => {
                tracing::warn!(
                    "Bucket validation: cannot verify L1 segment '{}': {e}",
                    seg.key
                );
                warnings += 1;
            }
        }
    }

    // 3. L0 segments with checksums — verify they exist
    for key in manifest.segment_checksums.keys() {
        match bucket.exists(key).await {
            Ok(true) => {
                tracing::debug!("Bucket validation: L0 segment '{key}' exists");
            }
            Ok(false) => {
                tracing::error!(
                    "Bucket validation: L0 segment '{key}' referenced in manifest but MISSING from bucket!"
                );
                errors += 1;
            }
            Err(e) => {
                tracing::warn!("Bucket validation: cannot verify L0 segment '{key}': {e}");
                warnings += 1;
            }
        }
    }

    // Summary
    if errors > 0 || warnings > 0 {
        tracing::warn!(
            "Bucket validation complete: {errors} errors, {warnings} warnings. \
             The restored DB is usable but may have missing segments.",
        );
    } else {
        tracing::debug!("Bucket validation: all referenced objects present");
    }
}