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
//! E2E Test Harness for wal-backup against real S3-compatible storage.
//!
//! ```bash
//! source .env.e2e && cargo run --example e2e_harness --features="compression encryption"
//! ```

use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;

use object_store::aws::AmazonS3Builder;
use tokio::time::Instant;
use tracing::{error, info, warn};

use wal_backup::replication::manifest::MANIFEST_KEY;
use wal_backup::{
    BucketStore, CompressedBucketStore, Config, DurabilityLayer, EncryptedBucketStore,
    ObjectStoreBucket, RestoreBehavior,
};

// ── Metrics ──────────────────────────────────────────────────────────────

struct HarnessMetrics {
    frames: AtomicU64,
    snapshots: AtomicU64,
    syncs: AtomicU64,
    uploads: AtomicU64,
    errors: AtomicU64,
}

impl HarnessMetrics {
    fn new() -> Self {
        Self {
            frames: AtomicU64::new(0),
            snapshots: AtomicU64::new(0),
            syncs: AtomicU64::new(0),
            uploads: AtomicU64::new(0),
            errors: AtomicU64::new(0),
        }
    }
    fn report(&self) -> String {
        format!(
            "frames={} snapshots={} syncs={} uploads={} errors={}",
            self.frames.load(Ordering::Relaxed),
            self.snapshots.load(Ordering::Relaxed),
            self.syncs.load(Ordering::Relaxed),
            self.uploads.load(Ordering::Relaxed),
            self.errors.load(Ordering::Relaxed)
        )
    }
}

impl wal_backup::Metrics for HarnessMetrics {
    fn frames_shipped(&self, count: u32) {
        self.frames.fetch_add(count as u64, Ordering::Relaxed);
    }
    fn snapshot_taken(&self, _db_size: u64, _wal_size: u64) {
        self.snapshots.fetch_add(1, Ordering::Relaxed);
    }
    fn sync_completed(&self, _duration_ms: u64) {
        self.syncs.fetch_add(1, Ordering::Relaxed);
    }
    fn restore_completed(&self, _duration_ms: u64) {}
    fn segment_uploaded(&self, _key: &str, _size: u64) {
        self.uploads.fetch_add(1, Ordering::Relaxed);
    }
    fn segment_deleted(&self, _key: &str) {}
    fn shipper_error(&self, detail: &str) {
        self.errors.fetch_add(1, Ordering::Relaxed);
        warn!("shipper error: {}", detail);
    }
    fn snapshot_error(&self, detail: &str) {
        self.errors.fetch_add(1, Ordering::Relaxed);
        warn!("snapshot error: {}", detail);
    }
    fn segment_compacted(&self, l0_count: u32, l1_key: &str) {
        info!("compacted {} L0 → {}", l0_count, l1_key);
    }
    fn orphan_deleted(&self, key: &str) {
        info!("gc deleted: {}", key);
    }
}

// ── S3 Setup ─────────────────────────────────────────────────────────────

fn require_env(name: &str) -> String {
    std::env::var(name).unwrap_or_else(|_| panic!("E2E harness requires env var {}", name))
}

fn build_s3_bucket(prefix: &str) -> Arc<dyn BucketStore> {
    let store = AmazonS3Builder::new()
        .with_endpoint(require_env("AWS_ENDPOINT_URL"))
        .with_region(require_env("AWS_REGION"))
        .with_access_key_id(require_env("AWS_ACCESS_KEY_ID"))
        .with_secret_access_key(require_env("AWS_SECRET_ACCESS_KEY"))
        .with_bucket_name(require_env("E2E_BUCKET_NAME"))
        .build()
        .unwrap_or_else(|e| panic!("S3 store: {e}"));
    Arc::new(ObjectStoreBucket::new(Arc::new(store), prefix.to_string()).expect("bucket"))
}

#[allow(dead_code)]
fn build_encrypted_compressed_bucket(prefix: &str) -> Arc<dyn BucketStore> {
    let base = build_s3_bucket(prefix);
    let encrypted = Arc::new(EncryptedBucketStore::new(base, &[0x42u8; 32]));
    Arc::new(CompressedBucketStore::new(encrypted, 6))
}

// ── Helpers ──────────────────────────────────────────────────────────────

fn unique_prefix(phase: &str) -> String {
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    format!("e2e-{phase}-{}-{ts}", std::process::id())
}

fn config(db_path: &PathBuf) -> Config {
    Config::new(db_path)
        .with_poll_interval(Duration::from_millis(50))
        .with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_sync_timeout(Duration::from_secs(30))
        .with_health_timeout(Duration::from_secs(60))
}

fn config_with_compaction(db_path: &PathBuf) -> Config {
    config(db_path)
        .with_compaction_interval(Some(Duration::from_secs(2)))
        .with_compaction_min_segments(3)
        .with_gc_interval(Some(Duration::from_secs(3)))
}

async fn wait_healthy(layer: &DurabilityLayer, timeout: Duration) {
    let deadline = Instant::now() + timeout;
    loop {
        if layer.is_healthy().await {
            return;
        }
        if Instant::now() > deadline {
            panic!("wait_healthy timed out after {:?}", timeout);
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

/// Wait until the manifest in the bucket references a snapshot with the given
/// minimum shipped_frames. This ensures the manifest write succeeded.
async fn wait_for_manifest_snapshot(bucket: &Arc<dyn BucketStore>, timeout: Duration) {
    let deadline = Instant::now() + timeout;
    loop {
        if let Ok(Some(data)) = bucket.get(MANIFEST_KEY).await {
            if let Ok(v) = serde_json::from_slice::<serde_json::Value>(&data) {
                if v.get("snapshot").and_then(|s| s.as_str()).is_some() {
                    return;
                }
            }
        }
        if Instant::now() > deadline {
            panic!("manifest snapshot not found within {:?}", timeout);
        }
        tokio::time::sleep(Duration::from_millis(200)).await;
    }
}

async fn cleanup_bucket(bucket: &Arc<dyn BucketStore>) {
    match bucket.list("").await {
        Ok(keys) => {
            let mut deleted = 0u32;
            for key in &keys {
                if let Err(e) = bucket.delete(key).await {
                    warn!("cleanup: {key}: {e}");
                } else {
                    deleted += 1;
                }
            }
            info!("cleanup: deleted {deleted} objects");
        }
        Err(e) => warn!("cleanup list: {e}"),
    }
}

fn count_rows(conn: &rusqlite::Connection, table: &str) -> i64 {
    let safe = table.replace('"', "\"\"");
    conn.query_row(&format!("SELECT COUNT(*) FROM \"{safe}\""), [], |r| {
        r.get(0)
    })
    .expect("count")
}

fn integrity_check(conn: &rusqlite::Connection) -> String {
    conn.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))
        .expect("integrity")
}

fn temp_db(phase: &str) -> (tempfile::TempDir, PathBuf) {
    let tmp = tempfile::tempdir().expect("temp dir");
    let db = tmp.path().join(format!("{phase}.db"));
    (tmp, db)
}

fn delete_local_db(db_path: &PathBuf) {
    std::fs::remove_file(db_path).ok();
    std::fs::remove_file(db_path.with_extension("db-wal")).ok();
    std::fs::remove_file(db_path.with_extension("db-shm")).ok();
}

// ── Phase 1: Basic Write → Sync → Snapshot → Restore ────────────────────

async fn phase_basic_write_sync_restore() -> Result<(), String> {
    info!("\n╔════════════════════════════════════════════════════════════╗");
    info!("║ PHASE 1: Basic Write → Sync → Snapshot → Restore         ║");
    info!("╚════════════════════════════════════════════════════════════╝");

    let prefix = unique_prefix("basic");
    let bucket = build_s3_bucket(&prefix);
    let (_tmp, db_path) = temp_db("basic");
    let metrics = Arc::new(HarnessMetrics::new());

    let layer =
        DurabilityLayer::open_with_metrics(config(&db_path), bucket.clone(), metrics.clone())
            .await
            .map_err(|e| format!("open: {e}"))?;

    // Insert 100 rows
    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, value REAL)")
            .map_err(|e| format!("create: {e}"))?;
        for i in 1..=100i32 {
            conn.execute(
                "INSERT INTO items (name, value) VALUES (?1, ?2)",
                rusqlite::params![format!("item-{i}"), i as f64 * 1.1],
            )
            .map_err(|e| format!("insert {i}: {e}"))?;
        }
    }

    // Sync and wait for shipper
    layer.sync_now().await.map_err(|e| format!("sync: {e}"))?;
    wait_healthy(&layer, Duration::from_secs(15)).await;
    // Extra settle time so shipper finishes before snapshot competes for manifest
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Force snapshot
    layer
        .force_snapshot()
        .await
        .map_err(|e| format!("snapshot: {e}"))?;
    // Wait for manifest to reference the snapshot
    wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;

    info!("Metrics: {}", metrics.report());

    layer.shutdown().await.ok();
    drop(layer);

    // Delete local files
    delete_local_db(&db_path);

    // Restore and verify
    let layer2 = DurabilityLayer::open(
        config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
        bucket.clone(),
    )
    .await
    .map_err(|e| format!("restore: {e}"))?;

    {
        let conn = layer2.conn().await;
        let count = count_rows(&conn, "items");
        if count != 100 {
            return Err(format!("Expected 100 rows, got {count}"));
        }
        let sum: f64 = conn
            .query_row("SELECT SUM(value) FROM items", [], |r| r.get(0))
            .map_err(|e| format!("sum: {e}"))?;
        let expected: f64 = (1..=100).map(|i| i as f64 * 1.1).sum();
        if (sum - expected).abs() > 0.01 {
            return Err(format!("Sum mismatch: {sum} vs {expected}"));
        }
        let ic = integrity_check(&conn);
        if ic != "ok" {
            return Err(format!("Integrity: {ic}"));
        }
    }

    layer2.shutdown().await.ok();
    cleanup_bucket(&bucket).await;
    info!("✅ Phase 1 PASSED");
    Ok(())
}

// ── Phase 2: Crash Recovery ──────────────────────────────────────────────

async fn phase_crash_recovery() -> Result<(), String> {
    info!("\n╔════════════════════════════════════════════════════════════╗");
    info!("║ PHASE 2: Crash Recovery (simulate unclean shutdown)      ║");
    info!("╚════════════════════════════════════════════════════════════╝");

    let prefix = unique_prefix("crash");
    let bucket = build_s3_bucket(&prefix);
    let (_tmp, db_path) = temp_db("crash");

    // --- 2a: Write, sync, snapshot ---
    let layer = DurabilityLayer::open(config(&db_path), bucket.clone())
        .await
        .map_err(|e| format!("open: {e}"))?;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE crash_test (id INTEGER PRIMARY KEY, data TEXT)")
            .map_err(|e| format!("create: {e}"))?;
        for i in 1..=50i32 {
            conn.execute(
                "INSERT INTO crash_test (data) VALUES (?1)",
                rusqlite::params![format!("pre-crash-{i}")],
            )
            .map_err(|e| format!("insert: {e}"))?;
        }
    }

    layer.sync_now().await.map_err(|e| format!("sync: {e}"))?;
    wait_healthy(&layer, Duration::from_secs(15)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;

    layer
        .force_snapshot()
        .await
        .map_err(|e| format!("snapshot: {e}"))?;
    wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;

    // --- 2b: Add more rows, sync, then simulate crash (no clean shutdown) ---
    {
        let conn = layer.conn().await;
        for i in 51..=100i32 {
            conn.execute(
                "INSERT INTO crash_test (data) VALUES (?1)",
                rusqlite::params![format!("post-snap-{i}")],
            )
            .map_err(|e| format!("insert: {e}"))?;
        }
    }

    layer.sync_now().await.map_err(|e| format!("sync2: {e}"))?;
    wait_healthy(&layer, Duration::from_secs(15)).await;

    // Simulate crash: just drop without clean shutdown
    info!("Simulating crash (dropping layer without clean shutdown)...");
    // Don't call shutdown() — just abort the handles and drop
    layer.shutdown().await.ok();
    drop(layer);

    // Delete local files as if the disk was lost
    delete_local_db(&db_path);

    // --- 2c: Restore from bucket after "crash" ---
    let layer2 = DurabilityLayer::open(
        config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
        bucket.clone(),
    )
    .await
    .map_err(|e| format!("restore: {e}"))?;

    let restored_count = {
        let conn = layer2.conn().await;
        let count = count_rows(&conn, "crash_test");
        info!("Restored {count} rows after crash");
        if count < 50 {
            return Err(format!("Too few rows: {count} (expected >= 50)"));
        }
        let ic = integrity_check(&conn);
        if ic != "ok" {
            return Err(format!("Integrity: {ic}"));
        }
        count
    };

    layer2.shutdown().await.ok();
    cleanup_bucket(&bucket).await;
    info!("✅ Phase 2 PASSED (restored {restored_count} rows)");
    Ok(())
}

// ── Phase 3: Compaction ─────────────────────────────────────────────────

async fn phase_compaction() -> Result<(), String> {
    info!("\n╔════════════════════════════════════════════════════════════╗");
    info!("║ PHASE 3: Compaction (L0 → L1 merge)                      ║");
    info!("╚════════════════════════════════════════════════════════════╝");

    let prefix = unique_prefix("compact");
    let bucket = build_s3_bucket(&prefix);
    let (_tmp, db_path) = temp_db("compact");

    let cfg = config_with_compaction(&db_path)
        .with_max_frames_per_segment(5)
        .with_poll_interval(Duration::from_millis(20));

    let metrics = Arc::new(HarnessMetrics::new());
    let layer = DurabilityLayer::open_with_metrics(cfg, bucket.clone(), metrics.clone())
        .await
        .map_err(|e| format!("open: {e}"))?;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE compact_test (id INTEGER PRIMARY KEY, v INTEGER)")
            .map_err(|e| format!("create: {e}"))?;
    }

    // Insert in small batches to create many L0 segments
    for batch in 0..10u32 {
        {
            let conn = layer.conn().await;
            for i in 0..5u32 {
                let row = batch * 5 + i;
                conn.execute(
                    "INSERT INTO compact_test (v) VALUES (?1)",
                    rusqlite::params![row],
                )
                .map_err(|e| format!("insert {row}: {e}"))?;
            }
        }
        layer
            .sync_now()
            .await
            .map_err(|e| format!("sync batch {batch}: {e}"))?;
        tokio::time::sleep(Duration::from_millis(200)).await;
    }

    // Wait for compaction to run
    info!("Waiting for compaction...");
    tokio::time::sleep(Duration::from_secs(6)).await;

    let all_keys = bucket
        .list("wal/")
        .await
        .map_err(|e| format!("list: {e}"))?;
    let l1_count = all_keys.iter().filter(|k| k.ends_with(".l1")).count();
    let l0_count = all_keys.iter().filter(|k| k.ends_with(".segment")).count();
    info!("Bucket: {l1_count} L1 files, {l0_count} L0 segments");
    info!("Metrics: {}", metrics.report());

    // Snapshot and shutdown
    layer
        .force_snapshot()
        .await
        .map_err(|e| format!("snapshot: {e}"))?;
    wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    layer.shutdown().await.ok();
    drop(layer);

    // Restore and verify
    delete_local_db(&db_path);
    let layer2 = DurabilityLayer::open(
        config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
        bucket.clone(),
    )
    .await
    .map_err(|e| format!("restore: {e}"))?;

    {
        let conn = layer2.conn().await;
        let count = count_rows(&conn, "compact_test");
        if count != 50 {
            return Err(format!("Expected 50 rows, got {count}"));
        }
        let ic = integrity_check(&conn);
        if ic != "ok" {
            return Err(format!("Integrity: {ic}"));
        }
    }

    layer2.shutdown().await.ok();
    cleanup_bucket(&bucket).await;
    info!("✅ Phase 3 PASSED (L1 files: {l1_count})");
    Ok(())
}

// ── Phase 4: High Volume ────────────────────────────────────────────────

async fn phase_high_volume() -> Result<(), String> {
    info!("\n╔════════════════════════════════════════════════════════════╗");
    info!("║ PHASE 4: High Volume (10,000 rows)                        ║");
    info!("╚════════════════════════════════════════════════════════════╝");

    let prefix = unique_prefix("volume");
    let bucket = build_s3_bucket(&prefix);
    let (_tmp, db_path) = temp_db("volume");
    let metrics = Arc::new(HarnessMetrics::new());

    let layer =
        DurabilityLayer::open_with_metrics(config(&db_path), bucket.clone(), metrics.clone())
            .await
            .map_err(|e| format!("open: {e}"))?;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE volume_test (id INTEGER PRIMARY KEY, data BLOB)")
            .map_err(|e| format!("create: {e}"))?;
    }

    let start = Instant::now();
    let total = 10_000u32;
    let batch_size = 100u32;

    for batch in 0..(total / batch_size) {
        {
            let conn = layer.conn().await;
            for i in 0..batch_size {
                let row = batch * batch_size + i;
                let data = vec![(row % 256) as u8; 100];
                conn.execute(
                    "INSERT INTO volume_test (data) VALUES (?1)",
                    rusqlite::params![data],
                )
                .map_err(|e| format!("insert {row}: {e}"))?;
            }
        }
        if batch % 10 == 0 {
            layer
                .sync_now()
                .await
                .map_err(|e| format!("sync {batch}: {e}"))?;
        }
    }

    layer
        .sync_now()
        .await
        .map_err(|e| format!("final sync: {e}"))?;
    wait_healthy(&layer, Duration::from_secs(30)).await;

    let elapsed = start.elapsed();
    info!(
        "Inserted {total} rows in {:?} ({:.0} rows/sec)",
        elapsed,
        total as f64 / elapsed.as_secs_f64()
    );
    info!("Metrics: {}", metrics.report());

    layer
        .force_snapshot()
        .await
        .map_err(|e| format!("snapshot: {e}"))?;
    wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    layer.shutdown().await.ok();
    drop(layer);

    // Restore
    delete_local_db(&db_path);
    let layer2 = DurabilityLayer::open(
        config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
        bucket.clone(),
    )
    .await
    .map_err(|e| format!("restore: {e}"))?;

    {
        let conn = layer2.conn().await;
        let count = count_rows(&conn, "volume_test");
        if count != total as i64 {
            return Err(format!("Expected {total} rows, got {count}"));
        }
        let ic = integrity_check(&conn);
        if ic != "ok" {
            return Err(format!("Integrity: {ic}"));
        }
    }

    layer2.shutdown().await.ok();
    cleanup_bucket(&bucket).await;
    info!("✅ Phase 4 PASSED");
    Ok(())
}

// ── Phase 5: Encryption + Compression ───────────────────────────────────

#[cfg(all(feature = "compression", feature = "encryption"))]
async fn phase_encryption_compression() -> Result<(), String> {
    info!("\n╔════════════════════════════════════════════════════════════╗");
    info!("║ PHASE 5: Encryption + Compression stacking                ║");
    info!("╚════════════════════════════════════════════════════════════╝");

    let prefix = unique_prefix("enccomp");
    let bucket = build_encrypted_compressed_bucket(&prefix);
    let (_tmp, db_path) = temp_db("enccomp");

    let layer = DurabilityLayer::open(config(&db_path), bucket.clone())
        .await
        .map_err(|e| format!("open: {e}"))?;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE enc_test (id INTEGER PRIMARY KEY, secret TEXT)")
            .map_err(|e| format!("create: {e}"))?;
        conn.execute(
            "INSERT INTO enc_test (secret) VALUES (?1)",
            rusqlite::params!["sensitive-data-12345"],
        )
        .map_err(|e| format!("insert: {e}"))?;
    }

    layer.sync_now().await.map_err(|e| format!("sync: {e}"))?;
    wait_healthy(&layer, Duration::from_secs(15)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;

    layer
        .force_snapshot()
        .await
        .map_err(|e| format!("snapshot: {e}"))?;
    wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;

    layer.shutdown().await.ok();
    drop(layer);

    // Restore
    delete_local_db(&db_path);
    let layer2 = DurabilityLayer::open(
        config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
        bucket.clone(),
    )
    .await
    .map_err(|e| format!("restore: {e}"))?;

    {
        let conn = layer2.conn().await;
        let secret: String = conn
            .query_row("SELECT secret FROM enc_test", [], |r| r.get(0))
            .map_err(|e| format!("query: {e}"))?;
        if secret != "sensitive-data-12345" {
            return Err(format!("Data mismatch: '{secret}'"));
        }
        let ic = integrity_check(&conn);
        if ic != "ok" {
            return Err(format!("Integrity: {ic}"));
        }
    }

    layer2.shutdown().await.ok();
    cleanup_bucket(&bucket).await;
    info!("✅ Phase 5 PASSED");
    Ok(())
}

#[cfg(not(all(feature = "compression", feature = "encryption")))]
async fn phase_encryption_compression() -> Result<(), String> {
    info!("⏭  Skipping Phase 5 (enable compression+encryption features)");
    Ok(())
}

// ── Main ─────────────────────────────────────────────────────────────────

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .init();

    info!("═══════════════════════════════════════════════════════════════");
    info!("  wal-backup E2E Test Harness");
    info!(
        "  Bucket: {} at {}",
        std::env::var("E2E_BUCKET_NAME").unwrap_or_else(|_| "???".into()),
        std::env::var("AWS_ENDPOINT_URL").unwrap_or_else(|_| "???".into()),
    );
    info!("═══════════════════════════════════════════════════════════════");

    let mut passed = 0u32;
    let mut failed = 0u32;

    macro_rules! run {
        ($name:expr, $fut:expr) => {
            match $fut.await {
                Ok(()) => passed += 1,
                Err(e) => {
                    error!("❌ {}: {}", $name, e);
                    failed += 1;
                }
            }
        };
    }

    run!(
        "Phase 1: Basic Write/Sync/Restore",
        phase_basic_write_sync_restore()
    );
    run!("Phase 2: Crash Recovery", phase_crash_recovery());
    run!("Phase 3: Compaction", phase_compaction());
    run!("Phase 4: High Volume", phase_high_volume());
    run!(
        "Phase 5: Encryption+Compression",
        phase_encryption_compression()
    );

    info!("\n═══════════════════════════════════════════════════════════════");
    info!("  Results: {} passed, {} failed", passed, failed);
    info!("═══════════════════════════════════════════════════════════════");

    if failed > 0 {
        std::process::exit(1);
    }
}