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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
mod common;

use bytes::Bytes;
use object_store::local::LocalFileSystem;
use std::sync::Arc;
use std::time::Duration;
use wal_backup::replication::manifest::MANIFEST_KEY;
use wal_backup::{BucketStore, Config, DurabilityLayer, Metrics, ObjectStoreBucket, SyncMode};

fn setup_tmp_dir(test_name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().expect("create temp dir");
    let db_path = tmp.path().join(format!("{}.db", test_name));
    let bucket_dir = tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");
    (tmp, db_path)
}

async fn create_layer(
    db_path: &std::path::Path,
    bucket_prefix: &str,
    bucket_dir: &std::path::Path,
    poll_ms: u64,
) -> DurabilityLayer {
    let store = Arc::new(
        LocalFileSystem::new_with_prefix(bucket_dir).expect("create local filesystem store"),
    );
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, bucket_prefix.to_string()).expect("create bucket"));

    let config = Config::new(db_path)
        .with_poll_interval(Duration::from_millis(poll_ms))
        .with_restore_behavior(wal_backup::RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_replica_lock_enabled(false);

    DurabilityLayer::open(config, bucket)
        .await
        .expect("open durability layer")
}

async fn create_layer_with_sync_mode(
    db_path: &std::path::Path,
    bucket_prefix: &str,
    bucket_dir: &std::path::Path,
    poll_ms: u64,
    sync_mode: SyncMode,
    immediate_poll_ms: u64,
) -> DurabilityLayer {
    let store = Arc::new(
        LocalFileSystem::new_with_prefix(bucket_dir).expect("create local filesystem store"),
    );
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, bucket_prefix.to_string()).expect("create bucket"));

    let config = Config::new(db_path)
        .with_poll_interval(Duration::from_millis(poll_ms))
        .with_sync_mode(sync_mode)
        .with_immediate_poll_interval(Duration::from_millis(immediate_poll_ms))
        .with_restore_behavior(wal_backup::RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_replica_lock_enabled(false);

    DurabilityLayer::open(config, bucket)
        .await
        .expect("open durability layer")
}

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

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

#[tokio::test]
async fn test_basic_write_and_restore() {
    let (_tmp, db_path) = setup_tmp_dir("basic_write_restore");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "test1", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")
            .expect("create table");
        conn.execute(
            "INSERT INTO test (value) VALUES (?1)",
            rusqlite::params!["hello"],
        )
        .expect("insert row");
        conn.execute(
            "INSERT INTO test (value) VALUES (?1)",
            rusqlite::params!["world"],
        )
        .expect("insert row");
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    drop(layer);

    let layer2 = create_layer(&db_path, "test1", &bucket_dir, 50).await;

    {
        let conn = layer2.conn().await;
        let mut stmt = conn
            .prepare("SELECT value FROM test ORDER BY id")
            .expect("prepare select");
        let rows: Vec<String> = stmt
            .query_map([], |row| row.get(0))
            .expect("query")
            .filter_map(|r| r.ok())
            .collect();
        assert_eq!(rows, vec!["hello".to_string(), "world".to_string()]);
    }
}

#[tokio::test]
async fn test_write_then_sync_then_verify() {
    let (_tmp, db_path) = setup_tmp_dir("sync_verify");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "sync_test", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (k TEXT PRIMARY KEY, v INTEGER)")
            .expect("create table");
        for i in 0..10 {
            conn.execute(
                "INSERT INTO data (k, v) VALUES (?1, ?2)",
                rusqlite::params![format!("key_{}", i), i],
            )
            .expect("insert row");
        }
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    assert!(layer.is_healthy().await);
    assert!(layer.last_sync().await.elapsed() < Duration::from_secs(5));
}

#[tokio::test]
async fn test_crash_recovery_snapshot_and_segments() {
    let (_tmp, db_path) = setup_tmp_dir("crash_snap_seg");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "crash1", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE items (id INTEGER PRIMARY KEY, val TEXT)")
            .expect("create table");
        for i in 0..100 {
            conn.execute(
                "INSERT INTO items (val) VALUES (?1)",
                rusqlite::params![format!("pre_snap_{}", i)],
            )
            .expect("insert");
        }
    }
    {
        let conn = layer.conn().await;
        assert_eq!(count_rows(&conn, "items"), 100);
    }

    layer.force_snapshot().await.expect("force snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    {
        let conn = layer.conn().await;
        for i in 0..50 {
            conn.execute(
                "INSERT INTO items (val) VALUES (?1)",
                rusqlite::params![format!("post_snap_{}", i)],
            )
            .expect("insert");
        }
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    layer.shutdown().await.expect("shutdown");

    {
        let conn = layer.conn().await;
        assert_eq!(count_rows(&conn, "items"), 150);
    }

    layer.shutdown().await.expect("shutdown");
    drop(layer);

    let layer2 = create_layer(&db_path, "crash1", &bucket_dir, 50).await;

    {
        let conn = layer2.conn().await;
        assert_eq!(count_rows(&conn, "items"), 150);
    }
    {
        let conn = layer2.conn().await;
        let mut stmt = conn
            .prepare("SELECT val FROM items WHERE val LIKE 'post_snap_%' ORDER BY val")
            .expect("prepare");
        let rows: Vec<String> = stmt
            .query_map([], |row| row.get(0))
            .expect("query")
            .filter_map(|r| r.ok())
            .collect();
        assert_eq!(rows.len(), 50, "post-snapshot data must survive crash");
    }
}

#[tokio::test]
async fn test_crash_recovery_no_data_loss() {
    let (_tmp, db_path) = setup_tmp_dir("crash_noloss");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "crash2", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE sensor (ts INTEGER PRIMARY KEY, reading REAL)")
            .expect("create table");
        for ts in 0..1000 {
            conn.execute(
                "INSERT INTO sensor (ts, reading) VALUES (?1, ?2)",
                rusqlite::params![ts, (ts as f64) * 0.5],
            )
            .expect("insert");
        }
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    layer.force_snapshot().await.expect("force snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    layer.shutdown().await.expect("shutdown");
    drop(layer);

    let layer2 = create_layer(&db_path, "crash2", &bucket_dir, 50).await;

    {
        let conn = layer2.conn().await;
        assert_eq!(count_rows(&conn, "sensor"), 1000);
    }

    drop(layer2);

    let layer3 = create_layer(&db_path, "crash2", &bucket_dir, 50).await;

    {
        let conn = layer3.conn().await;
        assert_eq!(count_rows(&conn, "sensor"), 1000);
    }
}

#[tokio::test]
async fn test_immediate_sync_mode_ships_frames() {
    let (_tmp, db_path) = setup_tmp_dir("immediate_sync");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer_with_sync_mode(
        &db_path,
        "immediate_test",
        &bucket_dir,
        1000,
        SyncMode::Immediate,
        20,
    )
    .await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params!["data"])
            .expect("insert");
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    assert!(layer.is_healthy().await);
    assert!(layer.last_sync().await.elapsed() < Duration::from_secs(5));

    drop(layer);

    let layer2 = create_layer(&db_path, "immediate_test", &bucket_dir, 1000).await;
    let conn = layer2.conn().await;
    let mut stmt = conn.prepare("SELECT v FROM t").expect("prepare select");
    let rows: Vec<String> = stmt
        .query_map([], |row| row.get(0))
        .expect("query")
        .filter_map(|r| r.ok())
        .collect();
    assert_eq!(rows, vec!["data"]);
}

#[tokio::test]
async fn test_lazy_sync_mode_batches_uploads() {
    let (_tmp, db_path) = setup_tmp_dir("lazy_sync");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer =
        create_layer_with_sync_mode(&db_path, "lazy_test", &bucket_dir, 200, SyncMode::Lazy, 20)
            .await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        for i in 0..100 {
            conn.execute(
                "INSERT INTO t (v) VALUES (?1)",
                rusqlite::params![format!("row_{}", i)],
            )
            .expect("insert");
        }
    }

    tokio::time::sleep(Duration::from_millis(50)).await;

    let last_sync_before = layer.last_sync().await;
    tokio::time::sleep(Duration::from_millis(450)).await;
    let last_sync_after = layer.last_sync().await;

    drop(layer);

    assert!(
        last_sync_after > last_sync_before,
        "Lazy sync should update last_sync after poll_interval elapsed"
    );
}

#[tokio::test]
async fn test_is_healthy_checks_watcher_in_immediate_mode() {
    let (_tmp, db_path) = setup_tmp_dir("health_check");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer_with_sync_mode(
        &db_path,
        "health_test",
        &bucket_dir,
        1000,
        SyncMode::Immediate,
        20,
    )
    .await;

    assert!(layer.is_healthy().await, "Fresh layer should be healthy");

    drop(layer);
}

#[tokio::test]
async fn test_bucket_restore_after_local_delete() {
    let (_tmp, db_path) = setup_tmp_dir("bucket_restore");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let store = Arc::new(
        object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"),
    );
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, "bucket_restore_test".to_string()).expect("bucket"));

    let layer = create_layer(&db_path, "bucket_restore_test", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (k TEXT PRIMARY KEY, v INTEGER)")
            .expect("create table");
        for i in 0..100 {
            conn.execute(
                "INSERT INTO data (k, v) VALUES (?1, ?2)",
                rusqlite::params![format!("key_{}", i), i],
            )
            .expect("insert row");
        }
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    layer.force_snapshot().await.expect("force snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    layer.shutdown().await.expect("shutdown");
    drop(layer);

    let manifest_data = bucket
        .get(MANIFEST_KEY)
        .await
        .expect("get manifest")
        .expect("manifest must exist after snapshot");
    let manifest: serde_json::Value =
        serde_json::from_slice(&manifest_data).expect("valid manifest json");
    assert!(
        manifest.get("snapshot").and_then(|v| v.as_str()).is_some(),
        "manifest must have a snapshot after force_snapshot: {:?}",
        manifest
    );

    std::fs::remove_file(&db_path).expect("delete local DB");
    let wal_path = db_path.with_extension("db-wal");
    std::fs::remove_file(&wal_path).ok();
    let wal_shm_path = db_path.with_extension("db-wal-shm");
    std::fs::remove_file(&wal_shm_path).ok();

    let layer2 = create_layer(&db_path, "bucket_restore_test", &bucket_dir, 50).await;

    {
        let conn = layer2.conn().await;
        assert_eq!(
            count_rows(&conn, "data"),
            100,
            "Data must be restored from bucket after local delete"
        );
    }
}

#[tokio::test]
async fn test_concurrent_writes_multiple_connections() {
    let (_tmp, db_path) = setup_tmp_dir("concurrent_writes");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "concurrent_test", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS concurrent_test (id INTEGER PRIMARY KEY, value TEXT)",
        )
        .expect("create table");
    }

    let layer = Arc::new(layer);

    let handles: Vec<_> = (0..4)
        .map(|thread_id| {
            let layer = layer.clone();
            tokio::spawn(async move {
                let conn = layer.conn().await;
                for i in 0..25 {
                    conn.execute(
                        "INSERT INTO concurrent_test (value) VALUES (?1)",
                        rusqlite::params![format!("thread_{}_row_{}", thread_id, i)],
                    )
                    .expect("insert");
                }
            })
        })
        .collect();

    for handle in handles {
        handle.await.expect("thread panic");
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    {
        let conn = layer.conn().await;
        let count = count_rows(&conn, "concurrent_test");
        assert_eq!(count, 100, "All 100 rows from 4 threads should be present");
    }
}

#[tokio::test]
async fn test_salt_change_triggers_snapshot_and_cleans_old_segments() {
    let (_tmp, db_path) = setup_tmp_dir("salt_change_cleanup");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "salt_test", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        for i in 0..50 {
            conn.execute(
                "INSERT INTO data (v) VALUES (?1)",
                rusqlite::params![format!("row_{}", i)],
            )
            .expect("insert");
        }
    }

    layer.sync_now().await.expect("sync first batch");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    layer.force_snapshot().await.expect("force snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    let segments_before: Vec<String> = {
        let store = Arc::new(
            object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"),
        );
        let bucket = Arc::new(
            ObjectStoreBucket::new(store, "salt_test".to_string()).expect("create bucket"),
        );
        bucket
            .list("wal/")
            .await
            .expect("list wal")
            .into_iter()
            .filter(|k| k.ends_with(".segment"))
            .collect()
    };
    let _old_prefix_count = segments_before.len();

    {
        let conn = layer.conn().await;
        conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")
            .expect("checkpoint to force salt change");
        for i in 50..100 {
            conn.execute(
                "INSERT INTO data (v) VALUES (?1)",
                rusqlite::params![format!("row_{}", i)],
            )
            .expect("insert");
        }
    }

    layer.sync_now().await.expect("sync after salt change");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    layer
        .force_snapshot()
        .await
        .expect("force snapshot after salt change");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    layer.sync_now().await.expect("sync after snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    drop(layer);

    let layer2 = create_layer(&db_path, "salt_test", &bucket_dir, 50).await;
    {
        let conn = layer2.conn().await;
        assert_eq!(
            count_rows(&conn, "data"),
            100,
            "all rows survive salt change"
        );
    }
}

#[tokio::test]
async fn test_recoverable_behavior_proceeds_on_checksum_mismatch() {
    use wal_backup::RestoreBehavior;
    let (_tmp, db_path) = setup_tmp_dir("recoverable_test");

    let bucket_dir = _tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");

    let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("create store"));
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, "recoverable".to_string()).expect("create bucket"));

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer = DurabilityLayer::open(config, bucket.clone())
        .await
        .expect("open layer");

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        for i in 0..10 {
            conn.execute(
                "INSERT INTO data (v) VALUES (?1)",
                rusqlite::params![format!("row_{}", i)],
            )
            .expect("insert");
        }
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    layer.force_snapshot().await.expect("force snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    tokio::time::sleep(Duration::from_millis(200)).await;

    layer.shutdown().await.expect("shutdown");
    drop(layer);

    let manifest_bytes = bucket
        .get(MANIFEST_KEY)
        .await
        .expect("get manifest")
        .expect("manifest must exist after snapshot");

    let mut manifest_json: serde_json::Value =
        serde_json::from_slice(&manifest_bytes).expect("valid json");

    let corrupted_checksum = manifest_json
        .get("snapshot_checksum")
        .and_then(|c| c.as_str())
        .map(|checksum| {
            let hash_part = checksum
                .strip_prefix("sha256:")
                .expect("checksum should have sha256: prefix");
            let mut bytes = hex::decode(hash_part).expect("valid hex after prefix");
            bytes[0] ^= 0xFF;
            format!("sha256:{}", hex::encode(bytes))
        })
        .expect("snapshot_checksum must exist");

    if let Some(obj) = manifest_json.as_object_mut() {
        obj.insert(
            "snapshot_checksum".to_string(),
            serde_json::Value::String(corrupted_checksum),
        );
    }

    bucket
        .put(
            MANIFEST_KEY,
            Bytes::from(serde_json::to_vec(&manifest_json).expect("serialize")),
        )
        .await
        .expect("write corrupted manifest");

    std::fs::remove_file(&db_path).expect("remove local db to force restore from bucket");

    let config2 = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::Recoverable)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer2 = DurabilityLayer::open(config2, bucket.clone())
        .await
        .expect("open layer with Recoverable");

    {
        let conn = layer2.conn().await;
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM data", [], |r| r.get(0))
            .expect("count rows");
        assert_eq!(
            count, 10,
            "data should be recovered despite corrupted manifest checksum"
        );
    }
}

#[tokio::test]
async fn test_shutdown_completes_cleanly() {
    let (_tmp, db_path) = setup_tmp_dir("shutdown_test");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "shutdown", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        conn.execute("INSERT INTO data (v) VALUES ('test')", [])
            .expect("insert");
    }

    layer.sync_now().await.expect("sync before shutdown");
    layer.shutdown().await.expect("shutdown");
}

#[tokio::test]
async fn test_is_healthy_after_sync() {
    let (_tmp, db_path) = setup_tmp_dir("health_test");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "health", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY)")
            .expect("create table");
    }

    layer.sync_now().await.expect("sync");
    assert!(
        layer.is_healthy().await,
        "layer should be healthy after sync"
    );
}

#[tokio::test]
async fn test_immediate_sync_mode_ships_wal() {
    let (_tmp, db_path) = setup_tmp_dir("immediate_sync");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer_with_sync_mode(
        &db_path,
        "immediate",
        &bucket_dir,
        50,
        SyncMode::Immediate,
        50,
    )
    .await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        for i in 0..5 {
            conn.execute(
                "INSERT INTO data (v) VALUES (?1)",
                rusqlite::params![format!("row_{}", i)],
            )
            .expect("insert");
        }
    }

    layer.sync_now().await.expect("sync in immediate mode");

    let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("create store"));
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, "immediate".to_string()).expect("create bucket"));

    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    let segments = loop {
        let segs: Vec<String> = bucket
            .list("wal/")
            .await
            .expect("list")
            .into_iter()
            .filter(|k| k.ends_with(".segment"))
            .collect();
        if !segs.is_empty() {
            break segs;
        }
        if std::time::Instant::now() > deadline {
            break segs;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    };
    assert!(
        !segments.is_empty(),
        "immediate mode should ship WAL segments"
    );
}

#[cfg(all(feature = "compression", feature = "encryption"))]
#[tokio::test]
async fn test_compression_encryption_stacking() {
    use common::InMemoryStore;
    use wal_backup::storage::compressed::CompressedBucketStore;
    use wal_backup::storage::encrypted::EncryptedBucketStore;

    let base = InMemoryStore::arc();
    let encrypted = Arc::new(EncryptedBucketStore::new(base.clone(), &[0x42u8; 32]));
    let compressed_encrypted = CompressedBucketStore::new(encrypted, 6);

    let plaintext = b"compressible data for stacking test: AAAAAAABBBBBBB".repeat(100);
    compressed_encrypted
        .put("stacked", Bytes::copy_from_slice(&plaintext))
        .await
        .unwrap();

    let raw = base.get_raw("stacked").unwrap();
    assert!(
        raw.starts_with(b"ENCR"),
        "outermost layer should be encrypted"
    );
    assert!(
        raw.len() < plaintext.len(),
        "compressed+encrypted should be smaller than original ({} >= {})",
        raw.len(),
        plaintext.len()
    );

    let decrypted = compressed_encrypted.get("stacked").await.unwrap().unwrap();
    assert_eq!(decrypted.as_ref(), plaintext.as_slice());
}

#[tokio::test]
async fn test_error_if_conflict_rejects_newer_local() {
    use wal_backup::RestoreBehavior;
    let (_tmp, db_path) = setup_tmp_dir("error_if_conflict");
    let bucket_dir = _tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");

    let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, "error_conflict".to_string()).expect("bucket"));

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer = DurabilityLayer::open(config, bucket.clone())
        .await
        .expect("open layer");

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        for i in 0..10 {
            conn.execute(
                "INSERT INTO data (v) VALUES (?1)",
                rusqlite::params![format!("row_{}", i)],
            )
            .expect("insert");
        }
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    layer.force_snapshot().await.expect("force snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    layer.shutdown().await.expect("shutdown");
    drop(layer);

    std::fs::remove_file(&db_path).expect("remove db");
    let wal_path = db_path.with_extension("db-wal");
    let _ = std::fs::remove_file(&wal_path);

    let config2 = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer2 = DurabilityLayer::open(config2, bucket.clone())
        .await
        .expect("restore from bucket");

    {
        let conn = layer2.conn().await;
        conn.execute("INSERT INTO data (v) VALUES ('new_row')", [])
            .expect("insert");
    }

    layer2.sync_now().await.expect("sync2");
    wait_for_sync(&layer2, Duration::from_secs(5)).await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    layer2.shutdown().await.expect("shutdown2");
    drop(layer2);

    // Now modify the local DB outside of wal-backup (e.g. via a raw SQLite connection)
    // and update the generation sidecar to trick wal-backup into thinking the local
    // DB is newer. This simulates the scenario where a DB was restored from a
    // different backup tool.
    {
        let conn = rusqlite::Connection::open(&db_path).expect("open raw");
        conn.execute("INSERT INTO data (v) VALUES ('external_modification')", [])
            .expect("external insert");
    }
    // Write a generation number that's higher than the bucket's
    let gen_path = db_path.with_extension("generation");
    std::fs::write(&gen_path, "99999").expect("write fake generation");

    let config3 = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::ErrorIfConflict)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let result = DurabilityLayer::open(config3, bucket).await;
    assert!(
        result.is_err(),
        "ErrorIfConflict should reject when local generation is higher than bucket"
    );
}

#[tokio::test]
async fn test_always_restore_from_bucket_overwrites_local() {
    use wal_backup::RestoreBehavior;
    let (_tmp, db_path) = setup_tmp_dir("always_restore");
    let bucket_dir = _tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");

    let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, "always_restore".to_string()).expect("bucket"));

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer = DurabilityLayer::open(config, bucket.clone())
        .await
        .expect("open layer");

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        for i in 0..20 {
            conn.execute(
                "INSERT INTO data (v) VALUES (?1)",
                rusqlite::params![format!("bucket_row_{}", i)],
            )
            .expect("insert");
        }
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    layer.force_snapshot().await.expect("force snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    layer.shutdown().await.expect("shutdown");
    drop(layer);

    {
        let conn = rusqlite::Connection::open(&db_path).expect("open db directly");
        conn.execute("INSERT INTO data (v) VALUES ('local_only_row')", [])
            .expect("insert extra row");
        drop(conn);
    }

    let config2 = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer2 = DurabilityLayer::open(config2, bucket.clone())
        .await
        .expect("open with AlwaysRestoreFromBucket");

    {
        let conn = layer2.conn().await;
        let count = count_rows(&conn, "data");
        assert_eq!(
            count, 20,
            "AlwaysRestoreFromBucket should restore bucket data (not 21 with local-only row)"
        );
    }
}

#[tokio::test]
async fn test_empty_database_restore() {
    let (_tmp, db_path) = setup_tmp_dir("empty_db_restore");
    let bucket_dir = _tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");

    let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, "empty_restore".to_string()).expect("bucket"));

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer = DurabilityLayer::open(config, bucket.clone())
        .await
        .expect("open layer");

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE empty_test (id INTEGER PRIMARY KEY)")
            .expect("create table");
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    layer.force_snapshot().await.expect("force snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    layer.shutdown().await.expect("shutdown");
    drop(layer);

    std::fs::remove_file(&db_path).expect("remove local DB");
    let wal_path = db_path.with_extension("db-wal");
    let _ = std::fs::remove_file(&wal_path);

    let config2 = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer2 = DurabilityLayer::open(config2, bucket)
        .await
        .expect("restore from bucket");

    {
        let conn = layer2.conn().await;
        let count = count_rows(&conn, "empty_test");
        assert_eq!(count, 0, "empty table should have 0 rows after restore");
    }
}

struct CountingMetrics {
    snapshots: std::sync::atomic::AtomicU32,
}

impl CountingMetrics {
    fn new() -> Self {
        Self {
            snapshots: std::sync::atomic::AtomicU32::new(0),
        }
    }
}

impl Metrics for CountingMetrics {
    fn frames_shipped(&self, _count: u32) {}
    fn snapshot_taken(&self, _db_size: u64, _wal_size: u64) {
        self.snapshots
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }
    fn sync_completed(&self, _duration_ms: u64) {}
    fn restore_completed(&self, _duration_ms: u64) {}
    fn segment_uploaded(&self, _key: &str, _size: u64) {}
    fn segment_deleted(&self, _key: &str) {}
    fn shipper_error(&self, _detail: &str) {}
}

#[tokio::test]
async fn test_open_with_metrics() {
    let (_tmp, db_path) = setup_tmp_dir("metrics_test");
    let bucket_dir = _tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");

    let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
    let bucket =
        Arc::new(ObjectStoreBucket::new(store, "metrics_test".to_string()).expect("bucket"));

    let metrics = Arc::new(CountingMetrics::new());

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer = DurabilityLayer::open_with_metrics(config, bucket, metrics.clone())
        .await
        .expect("open with metrics");

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
            .expect("create table");
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    layer.force_snapshot().await.expect("snapshot");
    wait_for_sync(&layer, Duration::from_secs(5)).await;
    tokio::time::sleep(Duration::from_millis(200)).await;

    let snap_count = metrics.snapshots.load(std::sync::atomic::Ordering::Relaxed);
    assert!(
        snap_count >= 1,
        "metrics should record snapshot (got {snap_count})"
    );

    layer.shutdown().await.expect("shutdown");
}

#[tokio::test]
async fn test_auto_snapshot_trigger_on_size_threshold() {
    let (_tmp, db_path) = setup_tmp_dir("auto_snapshot");
    let bucket_dir = _tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");

    let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
    let bucket = Arc::new(ObjectStoreBucket::new(store, "auto_snap".to_string()).expect("bucket"));

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(50))
        .with_snapshot_threshold(1)
        .with_snapshot_interval(Duration::from_secs(86400));

    let layer = DurabilityLayer::open(config, bucket.clone())
        .await
        .expect("open layer");

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        conn.execute("INSERT INTO data (v) VALUES ('x')", [])
            .expect("insert");
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(5)).await;

    let deadline = std::time::Instant::now() + Duration::from_secs(10);
    loop {
        let manifest_data = bucket.get(MANIFEST_KEY).await.expect("get manifest");
        if let Some(data) = manifest_data {
            let v: serde_json::Value = serde_json::from_slice(&data).expect("json");
            if v.get("snapshot").and_then(|v| v.as_str()).is_some() {
                break;
            }
        }
        if std::time::Instant::now() > deadline {
            panic!("auto snapshot not triggered within timeout");
        }
        tokio::time::sleep(Duration::from_millis(200)).await;
    }

    drop(layer);
}

#[tokio::test]
async fn test_health_report_returns_diagnostics() {
    let (_tmp, db_path) = setup_tmp_dir("health_report");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "health_rpt", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
            .expect("create table");
    }

    layer.sync_now().await.expect("sync");

    let report = layer.health_report().await;
    assert!(report.healthy);
    assert!(report.replicator_alive);
    assert!(report.snapshot_alive);
    assert!(report.last_sync_ago < Duration::from_secs(5));
}

#[tokio::test]
async fn test_with_conn_scoped_closure() {
    let (_tmp, db_path) = setup_tmp_dir("with_conn_test");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "with_conn", &bucket_dir, 50).await;

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
    }

    layer
        .with_conn(|c| c.execute("INSERT INTO t (v) VALUES ('via_with_conn')", []))
        .await
        .expect("with_conn insert");

    let count: i64 = layer
        .with_conn(|c| c.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0)))
        .await
        .expect("with_conn query");
    assert_eq!(count, 1, "with_conn should execute queries through closure");
}

#[tokio::test]
async fn test_shutdown_ships_pending_frames() {
    // Verify that shutdown() ships all pending WAL frames before checkpoint.
    // This is a regression test for the bug where shutdown() aborted the
    // shipper before it could ship the last batch of frames.
    let (_tmp, db_path) = setup_tmp_dir("shutdown_ships_test");
    let bucket_dir = db_path.parent().unwrap().join("bucket");

    let layer = create_layer(&db_path, "shutdown_ships", &bucket_dir, 50).await;

    // Insert rows WITHOUT calling sync_now() — leave frames unshipped
    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
            .expect("create table");
        for i in 0..100 {
            conn.execute("INSERT INTO data (v) VALUES (?1)", [&format!("row-{i}")])
                .expect("insert");
        }
    }

    // Don't call sync_now() — shutdown should do it for us
    layer.shutdown().await.expect("shutdown");

    // Now verify the bucket has the shipped frames by reading the manifest
    let store = Arc::new(
        LocalFileSystem::new_with_prefix(&bucket_dir).expect("create local filesystem store"),
    );
    let bucket = Arc::new(
        ObjectStoreBucket::new(store, "shutdown_ships".to_string()).expect("create bucket"),
    );

    let manifest_data = bucket
        .get(MANIFEST_KEY)
        .await
        .expect("get manifest")
        .expect("manifest exists");
    let manifest: wal_backup::replication::manifest::Manifest =
        wal_backup::replication::manifest::Manifest::deserialize(&manifest_data)
            .expect("parse manifest");

    // After shutdown, the shipper should have shipped all frames.
    // shipped_frames > 0 means the frames made it to the bucket.
    assert!(
        manifest.shipped_frames > 0,
        "shipped_frames should be > 0 after shutdown (frames were shipped), got {}",
        manifest.shipped_frames
    );

    // The DB should have the data — open a plain connection and verify
    let conn = rusqlite::Connection::open(&db_path).expect("open db");
    let count: i64 = conn
        .query_row("SELECT COUNT(*) FROM data", [], |r| r.get(0))
        .expect("count");
    assert_eq!(count, 100, "all rows should be in the DB after shutdown");
}