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
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
mod common;

use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64};
use std::sync::Arc;
use std::time::Duration;

use common::InMemoryStore;
use tokio::sync::{Mutex as TokioMutex, Notify};
use wal_backup::config::{Config, SyncMode};
use wal_backup::error::Error;
use wal_backup::metrics::noop_metrics;
use wal_backup::replication::manifest::Manifest;
use wal_backup::replication::shipper::FrameShipper;
use wal_backup::storage::BucketStore;
use wal_backup::wal::checksum::wal_checksum_pair;

fn setup_test_db(tmp: &tempfile::TempDir, name: &str) -> std::path::PathBuf {
    let db_path = tmp.path().join(format!("{}.db", name));
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
    db_path
}

fn build_shipper(
    db_path: &std::path::Path,
    store: Arc<dyn BucketStore>,
    manifest: Arc<TokioMutex<Manifest>>,
) -> FrameShipper {
    let config = Config::new(db_path)
        .with_sync_mode(SyncMode::Immediate)
        .with_poll_interval(Duration::from_millis(50));

    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<AtomicU64> = AtomicU64::new(0).into();
    let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
    let shipped_frames: Arc<AtomicU32> = AtomicU32::new(0).into();

    FrameShipper::new(
        config,
        store,
        manifest,
        snapshot_trigger,
        sync_notify,
        wal_notify,
        snapshot_version,
        force_snapshot,
        shipped_frames,
        noop_metrics(),
    )
}

fn build_shipper_with_config(
    config: Config,
    store: Arc<dyn BucketStore>,
    manifest: Arc<TokioMutex<Manifest>>,
) -> FrameShipper {
    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<AtomicU64> = AtomicU64::new(0).into();
    let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
    let shipped_frames: Arc<AtomicU32> = AtomicU32::new(0).into();

    FrameShipper::new(
        config,
        store,
        manifest,
        snapshot_trigger,
        sync_notify,
        wal_notify,
        snapshot_version,
        force_snapshot,
        shipped_frames,
        noop_metrics(),
    )
}

fn create_valid_wal_with_frames(
    page_size: u32,
    num_frames: u32,
    salt_1: u32,
    salt_2: u32,
) -> Vec<u8> {
    let magic: u32 = 0x377f0682;
    let file_format: u32 = 3007000;
    let checkpoint_seq: u32 = 1;

    let mut header_data = [0u8; 24];
    header_data[0..4].copy_from_slice(&magic.to_be_bytes());
    header_data[4..8].copy_from_slice(&file_format.to_be_bytes());
    header_data[8..12].copy_from_slice(&page_size.to_be_bytes());
    header_data[12..16].copy_from_slice(&checkpoint_seq.to_be_bytes());
    header_data[16..20].copy_from_slice(&salt_1.to_be_bytes());
    header_data[20..24].copy_from_slice(&salt_2.to_be_bytes());

    let (ck1, ck2) = wal_checksum_pair(0, 0, &header_data, false);

    let mut buf = Vec::with_capacity(32 + (num_frames as usize) * (24 + page_size as usize));
    buf.extend_from_slice(&magic.to_be_bytes());
    buf.extend_from_slice(&file_format.to_be_bytes());
    buf.extend_from_slice(&page_size.to_be_bytes());
    buf.extend_from_slice(&checkpoint_seq.to_be_bytes());
    buf.extend_from_slice(&salt_1.to_be_bytes());
    buf.extend_from_slice(&salt_2.to_be_bytes());
    buf.extend_from_slice(&ck1.to_be_bytes());
    buf.extend_from_slice(&ck2.to_be_bytes());

    let mut prev_ck1 = ck1;
    let mut prev_ck2 = ck2;

    for i in 0..num_frames {
        let page_number: u32 = i + 1;
        let db_size_after: u32 = if i == num_frames - 1 { 1 } else { 0 };
        let frame_data = vec![0xAAu8; page_size as usize];

        let mut checksum_input = Vec::with_capacity(8 + page_size as usize);
        checksum_input.extend_from_slice(&page_number.to_be_bytes());
        checksum_input.extend_from_slice(&db_size_after.to_be_bytes());
        checksum_input.extend_from_slice(&frame_data);

        let (fc1, fc2) = wal_checksum_pair(prev_ck1, prev_ck2, &checksum_input, false);

        buf.extend_from_slice(&page_number.to_be_bytes());
        buf.extend_from_slice(&db_size_after.to_be_bytes());
        buf.extend_from_slice(&salt_1.to_be_bytes());
        buf.extend_from_slice(&salt_2.to_be_bytes());
        buf.extend_from_slice(&fc1.to_be_bytes());
        buf.extend_from_slice(&fc2.to_be_bytes());
        buf.extend_from_slice(&frame_data);

        prev_ck1 = fc1;
        prev_ck2 = fc2;
    }

    buf
}

fn create_valid_wal_header_only(page_size: u32, salt_1: u32, salt_2: u32) -> Vec<u8> {
    create_valid_wal_with_frames(page_size, 0, salt_1, salt_2)
}

#[test]
fn test_shipper_new_creates_shipper() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "shipper_new");

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let last_sync = shipper.last_sync();
    let _guard = last_sync.blocking_lock();
}

#[test]
fn test_shipper_sync_notify_returns_notify() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "shipper_notify");

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let sync_notify = shipper.sync_notify();
    drop(sync_notify);
}

#[test]
fn test_shipper_public_api_accessible() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "public_api");

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0x1111, 0x2222, 4096)));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let _ = shipper.last_sync();
    let _ = shipper.sync_notify();
}

#[test]
fn test_shipper_no_panic_on_drop() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "drop_test");

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));

    let shipper = build_shipper(&db_path, store, manifest.clone());
    drop(shipper);
}

#[tokio::test]
async fn test_sync_once_no_wal_returns_ok_false() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "no_wal");

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let result = shipper.sync_once().await;
    assert!(result.is_ok());
    assert!(!result.unwrap());
}

#[tokio::test]
async fn test_sync_once_empty_wal_returns_ok_false() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "empty_wal");

    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_header_only(4096, 0xAAAA, 0xBBBB);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0xAAAA, 0xBBBB, 4096)));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let result = shipper.sync_once().await;
    assert!(result.is_ok());
    assert!(!result.unwrap(), "0 frames → should return false");

    let m = manifest.lock().await;
    assert_eq!(m.shipped_frames, 0);
}

#[tokio::test]
async fn test_sync_once_corrupt_wal_returns_err() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "corrupt_wal");

    let wal_path = db_path.with_extension("db-wal");
    let mut corrupt = create_valid_wal_header_only(4096, 0xAAAA, 0xBBBB);
    corrupt[0] = 0xDE;
    corrupt[1] = 0xAD;
    std::fs::write(&wal_path, &corrupt).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0xAAAA, 0xBBBB, 4096)));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let result = shipper.sync_once().await;
    assert!(result.is_err(), "corrupt WAL (bad magic) should return Err");
}

#[tokio::test]
async fn test_sync_once_ships_frames_and_updates_manifest() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "ship_frames");

    let salt_1: u32 = 0xDEAD;
    let salt_2: u32 = 0xBEEF;
    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 3, salt_1, salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(salt_1, salt_2, 4096)));

    let shipper = build_shipper(&db_path, store.clone(), manifest.clone());

    let result = shipper.sync_once().await;
    assert!(result.is_ok());
    assert!(result.unwrap(), "3 frames should ship successfully");

    let m = manifest.lock().await;
    assert_eq!(
        m.shipped_frames, 3,
        "shipped_frames should be 3 after shipping 3 frames"
    );
    assert!(
        m.generation > 0,
        "generation should increment after shipping"
    );
}

#[tokio::test]
async fn test_sync_once_max_frames_per_segment_truncates() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "max_frames");

    let salt_1: u32 = 0x1111;
    let salt_2: u32 = 0x2222;
    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 10, salt_1, salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(salt_1, salt_2, 4096)));

    let config = Config::new(&db_path)
        .with_sync_mode(SyncMode::Immediate)
        .with_poll_interval(Duration::from_millis(50))
        .with_max_frames_per_segment(3);

    let shipper = build_shipper_with_config(config, store, manifest.clone());

    let result = shipper.sync_once().await;
    assert!(result.is_ok());
    assert!(result.unwrap(), "should ship at least some frames");

    let m = manifest.lock().await;
    assert_eq!(
        m.shipped_frames, 3,
        "max_frames_per_segment=3 should limit to 3 frames out of 10"
    );
}

#[tokio::test]
async fn test_sync_once_manifest_conflict_returns_err() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "conflict");

    let salt_1: u32 = 0xAAAA;
    let salt_2: u32 = 0xBBBB;
    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 1, salt_1, salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();

    let mut remote_manifest = Manifest::new(salt_1, salt_2, 4096);
    remote_manifest.generation = 100;
    remote_manifest.update_shipped_frames(1);
    let remote_data = remote_manifest.serialize().unwrap();
    store
        .put("manifest.json", remote_data.into())
        .await
        .unwrap();

    let mut local_manifest = Manifest::new(salt_1, salt_2, 4096);
    local_manifest.generation = 1;
    let manifest = Arc::new(TokioMutex::new(local_manifest));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let result = shipper.sync_once().await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(err, Error::ManifestConflict { .. }),
        "remote ahead should cause ManifestConflict, got: {err}"
    );
}

#[tokio::test]
async fn test_sync_once_fresh_manifest_adopts_wal_salts() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "fresh_salt");

    let salt_1: u32 = 0xCCCC;
    let salt_2: u32 = 0xDDDD;
    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 1, salt_1, salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let result = shipper.sync_once().await;
    assert!(result.is_ok());

    let m = manifest.lock().await;
    assert_eq!(
        m.current_salt_1, salt_1,
        "fresh manifest should adopt WAL salt_1"
    );
    assert_eq!(
        m.current_salt_2, salt_2,
        "fresh manifest should adopt WAL salt_2"
    );
}

#[tokio::test]
async fn test_sync_once_salt_change_triggers_snapshot() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "salt_change");

    let old_salt_1: u32 = 0x1111;
    let old_salt_2: u32 = 0x2222;
    let new_salt_1: u32 = 0x3333;
    let new_salt_2: u32 = 0x4444;

    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 1, new_salt_1, new_salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();
    let mut m = Manifest::new(old_salt_1, old_salt_2, 4096);
    m.generation = 5;
    let manifest = Arc::new(TokioMutex::new(m));

    let config = Config::new(&db_path)
        .with_sync_mode(SyncMode::Immediate)
        .with_poll_interval(Duration::from_millis(50));

    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<AtomicU64> = AtomicU64::new(0).into();
    let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
    let shipped_frames: Arc<AtomicU32> = AtomicU32::new(0).into();

    let force_ref = force_snapshot.clone();
    let version_ref = snapshot_version.clone();

    let shipper = FrameShipper::new(
        config,
        store,
        manifest.clone(),
        snapshot_trigger,
        sync_notify,
        wal_notify,
        snapshot_version,
        force_snapshot,
        shipped_frames,
        noop_metrics(),
    );

    let handle = tokio::spawn(async move { shipper.sync_once().await });

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

    assert!(
        force_ref.load(std::sync::atomic::Ordering::Relaxed),
        "force_snapshot should be set to true on salt change"
    );

    version_ref.fetch_add(1, std::sync::atomic::Ordering::Release);

    let result = handle.await.unwrap();
    assert!(result.is_ok());
    assert!(
        !result.unwrap(),
        "salt change should defer shipping, returning false"
    );
}

#[tokio::test]
async fn test_run_exits_on_manifest_conflict() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "run_conflict");

    let salt_1: u32 = 0xAAAA;
    let salt_2: u32 = 0xBBBB;
    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 1, salt_1, salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();

    let mut remote_manifest = Manifest::new(salt_1, salt_2, 4096);
    remote_manifest.generation = 100;
    remote_manifest.update_shipped_frames(1);
    let remote_data = remote_manifest.serialize().unwrap();
    store
        .put("manifest.json", remote_data.into())
        .await
        .unwrap();

    let mut local_manifest = Manifest::new(salt_1, salt_2, 4096);
    local_manifest.generation = 1;
    let manifest = Arc::new(TokioMutex::new(local_manifest));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let start = tokio::time::Instant::now();
    shipper.run().await;
    let elapsed = start.elapsed();

    assert!(
        elapsed < Duration::from_secs(5),
        "run() should exit quickly on ManifestConflict, took {:?}",
        elapsed
    );
}

#[tokio::test]
async fn test_sync_once_local_ahead_proceeds() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "local_ahead");

    let salt_1: u32 = 0xAAAA;
    let salt_2: u32 = 0xBBBB;
    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 1, salt_1, salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();

    let mut remote_manifest = Manifest::new(salt_1, salt_2, 4096);
    remote_manifest.generation = 1;
    remote_manifest.last_updated = "2024-01-01T00:00:00Z".to_string();
    let remote_data = remote_manifest.serialize().unwrap();
    store
        .put("manifest.json", remote_data.into())
        .await
        .unwrap();

    let mut local_manifest = Manifest::new(salt_1, salt_2, 4096);
    local_manifest.generation = 10;
    let manifest = Arc::new(TokioMutex::new(local_manifest));

    let shipper = build_shipper(&db_path, store.clone(), manifest.clone());

    let result = shipper.sync_once().await;
    assert!(
        result.is_ok(),
        "LocalAhead conflict should not cause error, got: {:?}",
        result
    );
    assert!(
        result.unwrap(),
        "should still ship frames when local is ahead"
    );

    let m = manifest.lock().await;
    assert!(
        m.generation > 10,
        "generation should have incremented past 10"
    );
}

#[tokio::test]
async fn test_sync_once_no_new_frames_returns_false() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "no_new");

    let salt_1: u32 = 0xAAAA;
    let salt_2: u32 = 0xBBBB;
    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 2, salt_1, salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();
    let mut m = Manifest::new(salt_1, salt_2, 4096);
    m.shipped_frames = 2;
    let manifest = Arc::new(TokioMutex::new(m));

    let shipper = build_shipper(&db_path, store, manifest.clone());

    let result = shipper.sync_once().await;
    assert!(result.is_ok());
    assert!(!result.unwrap(), "no new frames should return false");
}

#[tokio::test]
async fn test_sync_once_checksum_error_returns_err() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "checksum_err");

    let salt_1: u32 = 0xAAAA;
    let salt_2: u32 = 0xBBBB;
    let wal_path = db_path.with_extension("db-wal");

    let magic: u32 = 0x377f0682;
    let file_format: u32 = 3007000;
    let page_size: u32 = 4096;
    let checkpoint_seq: u32 = 1;

    let mut header_data = [0u8; 24];
    header_data[0..4].copy_from_slice(&magic.to_be_bytes());
    header_data[4..8].copy_from_slice(&file_format.to_be_bytes());
    header_data[8..12].copy_from_slice(&page_size.to_be_bytes());
    header_data[12..16].copy_from_slice(&checkpoint_seq.to_be_bytes());
    header_data[16..20].copy_from_slice(&salt_1.to_be_bytes());
    header_data[20..24].copy_from_slice(&salt_2.to_be_bytes());

    let (ck1, ck2) = wal_checksum_pair(0, 0, &header_data, false);

    let mut buf = Vec::new();
    buf.extend_from_slice(&magic.to_be_bytes());
    buf.extend_from_slice(&file_format.to_be_bytes());
    buf.extend_from_slice(&page_size.to_be_bytes());
    buf.extend_from_slice(&checkpoint_seq.to_be_bytes());
    buf.extend_from_slice(&salt_1.to_be_bytes());
    buf.extend_from_slice(&salt_2.to_be_bytes());
    buf.extend_from_slice(&ck1.to_be_bytes());
    buf.extend_from_slice(&ck2.to_be_bytes());

    let page_number: u32 = 1;
    let db_size_after: u32 = 1;
    let frame_data = vec![0xAAu8; page_size as usize];
    let mut checksum_input = Vec::with_capacity(8 + page_size as usize);
    checksum_input.extend_from_slice(&page_number.to_be_bytes());
    checksum_input.extend_from_slice(&db_size_after.to_be_bytes());
    checksum_input.extend_from_slice(&frame_data);
    let (mut fc1, fc2) = wal_checksum_pair(ck1, ck2, &checksum_input, false);
    fc1 = !fc1;

    buf.extend_from_slice(&page_number.to_be_bytes());
    buf.extend_from_slice(&db_size_after.to_be_bytes());
    buf.extend_from_slice(&salt_1.to_be_bytes());
    buf.extend_from_slice(&salt_2.to_be_bytes());
    buf.extend_from_slice(&fc1.to_be_bytes());
    buf.extend_from_slice(&fc2.to_be_bytes());
    buf.extend_from_slice(&frame_data);

    std::fs::write(&wal_path, &buf).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(salt_1, salt_2, 4096)));

    let shipper = build_shipper(&db_path, store, manifest);

    let result = shipper.sync_once().await;
    assert!(result.is_err(), "WAL checksum error should return Err");
    assert!(
        matches!(result.unwrap_err(), Error::WalChecksum { .. }),
        "should be WalChecksum error"
    );
}

#[tokio::test]
async fn test_sync_once_wal_truncated_triggers_snapshot_wait() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = setup_test_db(&tmp, "wal_truncated");

    let old_salt_1: u32 = 0x1111;
    let old_salt_2: u32 = 0x2222;
    let new_salt_1: u32 = 0x3333;
    let new_salt_2: u32 = 0x4444;

    let wal_path = db_path.with_extension("db-wal");
    let wal_data = create_valid_wal_with_frames(4096, 1, new_salt_1, new_salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = InMemoryStore::arc();
    let mut m = Manifest::new(old_salt_1, old_salt_2, 4096);
    m.shipped_frames = 5;
    let manifest = Arc::new(TokioMutex::new(m));

    let config = Config::new(&db_path)
        .with_sync_mode(SyncMode::Immediate)
        .with_poll_interval(Duration::from_millis(50));

    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<AtomicU64> = AtomicU64::new(0).into();
    let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
    let shipped_frames: Arc<AtomicU32> = AtomicU32::new(5).into();

    let force_ref = force_snapshot.clone();
    let version_ref = snapshot_version.clone();

    let shipper = FrameShipper::new(
        config,
        store,
        manifest.clone(),
        snapshot_trigger,
        sync_notify,
        wal_notify,
        snapshot_version,
        force_snapshot,
        shipped_frames,
        noop_metrics(),
    );

    let handle = tokio::spawn(async move { shipper.sync_once().await });

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

    assert!(
        force_ref.load(std::sync::atomic::Ordering::Relaxed),
        "force_snapshot should be set to true on WAL truncation"
    );

    version_ref.fetch_add(1, std::sync::atomic::Ordering::Release);

    let result = handle.await.unwrap();
    assert!(result.is_ok());
    assert!(
        !result.unwrap(),
        "WAL truncation should defer shipping, returning false"
    );
}

#[tokio::test]
async fn test_shipper_rollback_manifest_on_upload_failure() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("rollback.db");
    let wal_path = db_path.with_extension("db-wal");

    let salt_1: u32 = 0xCAFE;
    let salt_2: u32 = 0xBEEF;
    let page_size: u32 = 4096;

    std::fs::write(&db_path, vec![0u8; page_size as usize]).unwrap();
    let wal_data = create_valid_wal_with_frames(page_size, 2, salt_1, salt_2);
    std::fs::write(&wal_path, &wal_data).unwrap();

    let store = common::FailOnManifestStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(salt_1, salt_2, page_size)));

    let config = Config::new(&db_path)
        .with_sync_mode(SyncMode::Immediate)
        .with_poll_interval(Duration::from_millis(50));

    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<AtomicU64> = AtomicU64::new(0).into();
    let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
    let shipped_frames: Arc<AtomicU32> = AtomicU32::new(0).into();

    let shipper = FrameShipper::new(
        config,
        store,
        manifest.clone(),
        snapshot_trigger,
        sync_notify,
        wal_notify,
        snapshot_version,
        force_snapshot,
        shipped_frames,
        noop_metrics(),
    );

    let original_shipped = manifest.lock().await.shipped_frames;
    let result = shipper.sync_once().await;
    assert!(
        result.is_err(),
        "sync_once should fail when manifest write fails, got: {:?}",
        result
    );

    let after_shipped = manifest.lock().await.shipped_frames;
    assert_eq!(
        after_shipped, original_shipped,
        "manifest.shipped_frames should be rolled back on manifest write failure, got {} (expected {})",
        after_shipped, original_shipped
    );
}

#[tokio::test]
async fn test_shipper_sync_once_handles_missing_wal_gracefully() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("no_wal.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));

    let config = Config::new(&db_path)
        .with_sync_mode(SyncMode::Immediate)
        .with_poll_interval(Duration::from_millis(50));

    let shipper = build_shipper_with_config(config, store, manifest);

    let result = shipper.sync_once().await;
    assert!(
        result.is_ok(),
        "sync_once should not error when WAL file is missing: {:?}",
        result
    );
    assert!(
        !result.unwrap(),
        "sync_once should return false when no WAL frames to ship"
    );
}

#[tokio::test]
async fn test_gc_deletes_orphaned_segments() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 50;

    let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);

    // Put some segments - active ones and orphaned ones
    store
        .put(
            "wal/100-200/00000000-00000049.segment",
            vec![1u8; 100].into(),
        )
        .await
        .unwrap();
    store
        .put(
            "wal/100-200/00000050-00000099.segment",
            vec![2u8; 100].into(),
        )
        .await
        .unwrap();
    store
        .put(
            "wal/100-200/00000100-00000149.segment",
            vec![3u8; 100].into(),
        )
        .await
        .unwrap();

    // GC with shipped_frames=50 should delete frames 0-49 (orphaned)
    let deleted = shipper.gc().await.unwrap();
    assert_eq!(deleted, 1, "Should delete 1 orphaned segment");

    // Active segments (>=50) should still exist
    assert!(store
        .get("wal/100-200/00000050-00000099.segment")
        .await
        .unwrap()
        .is_some());
    assert!(store
        .get("wal/100-200/00000100-00000149.segment")
        .await
        .unwrap()
        .is_some());
}

#[tokio::test]
async fn test_gc_keeps_active_segments() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 100;

    let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);

    // Put segments with start >= shipped_frames
    store
        .put(
            "wal/100-200/00000100-00000199.segment",
            vec![1u8; 100].into(),
        )
        .await
        .unwrap();
    store
        .put(
            "wal/100-200/00000200-00000299.segment",
            vec![2u8; 100].into(),
        )
        .await
        .unwrap();

    let deleted = shipper.gc().await.unwrap();
    assert_eq!(deleted, 0, "Should delete 0 active segments");

    // Both should still exist
    assert!(store
        .get("wal/100-200/00000100-00000199.segment")
        .await
        .unwrap()
        .is_some());
    assert!(store
        .get("wal/100-200/00000200-00000299.segment")
        .await
        .unwrap()
        .is_some());
}

#[tokio::test]
async fn test_gc_ignores_different_salt_prefix() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 10;

    let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);

    // Put segment with different salt
    store
        .put(
            "wal/300-400/00000000-00000049.segment",
            vec![1u8; 100].into(),
        )
        .await
        .unwrap();

    let deleted = shipper.gc().await.unwrap();
    assert_eq!(deleted, 0, "Should not delete segments with different salt");

    // Should still exist
    assert!(store
        .get("wal/300-400/00000000-00000049.segment")
        .await
        .unwrap()
        .is_some());
}

#[tokio::test]
async fn test_gc_empty_when_no_shipped_frames() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 0;

    let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);

    store
        .put(
            "wal/100-200/00000000-00000049.segment",
            vec![1u8; 100].into(),
        )
        .await
        .unwrap();

    let deleted = shipper.gc().await.unwrap();
    assert_eq!(deleted, 0, "Should not delete when shipped_frames=0");

    // Should still exist
    assert!(store
        .get("wal/100-200/00000000-00000049.segment")
        .await
        .unwrap()
        .is_some());
}

#[tokio::test]
async fn test_wal_size_backpressure_pauses_shipping() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 0;

    // Config with max_wal_size_bytes set to very low value (10 bytes)
    // so any WAL will trigger backpressure
    let config = Config::new(&db_path)
        .with_sync_mode(SyncMode::Immediate)
        .with_poll_interval(Duration::from_millis(50))
        .with_max_wal_size_bytes(10);

    let shipper = build_shipper_with_config(config, store, manifest);

    // The shipper should return false (paused) due to WAL exceeding max size
    let result = shipper.sync_once().await.unwrap();
    assert!(
        !result,
        "sync_once should return false when WAL exceeds max size"
    );
}

#[tokio::test]
async fn test_wal_size_zero_disables_backpressure() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 0;

    // Config with max_wal_size_bytes = 0 (disabled)
    let config = Config::new(&db_path)
        .with_sync_mode(SyncMode::Immediate)
        .with_poll_interval(Duration::from_millis(50))
        .with_max_wal_size_bytes(0);

    let shipper = build_shipper_with_config(config, store, manifest);

    // With 0 max, backpressure should not trigger
    let result = shipper.sync_once().await.unwrap();
    // Returns false because there's no WAL (no frames to ship)
    assert!(
        !result,
        "sync_once should return false when no frames to ship (not due to backpressure)"
    );
}

// ============================================================
// Compaction tests
// ============================================================

#[tokio::test]
async fn test_compact_merges_l0_segments_into_l1() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 200;

    let config = Config::new(&db_path).with_compaction_min_segments(3);

    let shipper = build_shipper_with_config(config, store.clone(), manifest.clone());

    // Put 5 L0 segments
    store
        .put(
            "wal/100-200/00000000-00000099.segment",
            vec![1u8; 100].into(),
        )
        .await
        .unwrap();
    store
        .put(
            "wal/100-200/00000100-00000149.segment",
            vec![2u8; 100].into(),
        )
        .await
        .unwrap();
    store
        .put(
            "wal/100-200/00000150-00000199.segment",
            vec![3u8; 100].into(),
        )
        .await
        .unwrap();
    store
        .put(
            "wal/100-200/00000200-00000249.segment",
            vec![4u8; 100].into(),
        )
        .await
        .unwrap();
    store
        .put(
            "wal/100-200/00000250-00000299.segment",
            vec![5u8; 100].into(),
        )
        .await
        .unwrap();

    let compacted = shipper.compact().await.unwrap();
    assert_eq!(compacted, 5, "Should compact all 5 L0 segments");

    // L1 file should exist
    assert!(
        store
            .get("wal/100-200/00000000-00000299.l1")
            .await
            .unwrap()
            .is_some(),
        "L1 file should be uploaded"
    );

    // Manifest should have l1_files and l1_max_frame
    let m = manifest.lock().await;
    assert_eq!(m.l1_files.len(), 1, "Manifest should have 1 L1 file");
    assert_eq!(m.l1_files[0].start_frame, 0);
    assert_eq!(m.l1_files[0].end_frame, 299);
    assert_eq!(m.l1_files[0].source_count, 5);
    assert_eq!(m.l1_max_frame, Some(299));
}

#[tokio::test]
async fn test_compact_skips_when_fewer_than_min_segments() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 100;

    let config = Config::new(&db_path).with_compaction_min_segments(10); // Require 10 but only put 2

    let shipper = build_shipper_with_config(config, store.clone(), manifest);

    // Put only 2 L0 segments
    store
        .put(
            "wal/100-200/00000000-00000049.segment",
            vec![1u8; 100].into(),
        )
        .await
        .unwrap();
    store
        .put(
            "wal/100-200/00000050-00000099.segment",
            vec![2u8; 100].into(),
        )
        .await
        .unwrap();

    let compacted = shipper.compact().await.unwrap();
    assert_eq!(
        compacted, 0,
        "Should not compact when fewer than min_segments"
    );

    // No L1 file should exist
    let keys = store.list("wal/100-200/").await.unwrap();
    assert!(
        keys.iter().all(|k| !k.ends_with(".l1")),
        "No L1 files should exist"
    );
}

#[tokio::test]
async fn test_compact_skips_already_covered_segments() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 300;
    manifest.lock().await.l1_max_frame = Some(199); // L1 already covers frames 0-199
    manifest
        .lock()
        .await
        .l1_files
        .push(wal_backup::replication::manifest::L1File {
            key: "wal/100-200/00000000-00000199.l1".to_string(),
            start_frame: 0,
            end_frame: 199,
            source_count: 4,
            checksum: None,
        });

    let config = Config::new(&db_path).with_compaction_min_segments(2);

    let shipper = build_shipper_with_config(config, store.clone(), manifest.clone());

    // Put L0 segments — some covered by L1, some not
    store
        .put(
            "wal/100-200/00000000-00000099.segment",
            vec![1u8; 100].into(),
        )
        .await
        .unwrap(); // covered
    store
        .put(
            "wal/100-200/00000100-00000199.segment",
            vec![2u8; 100].into(),
        )
        .await
        .unwrap(); // covered
    store
        .put(
            "wal/100-200/00000200-00000249.segment",
            vec![3u8; 100].into(),
        )
        .await
        .unwrap(); // uncovered
    store
        .put(
            "wal/100-200/00000250-00000299.segment",
            vec![4u8; 100].into(),
        )
        .await
        .unwrap(); // uncovered

    let compacted = shipper.compact().await.unwrap();
    // Only the 2 uncovered segments should be compacted
    assert_eq!(compacted, 2, "Should compact only uncovered segments");

    // New L1 should cover frames 200-299
    let m = manifest.lock().await;
    assert_eq!(m.l1_files.len(), 2, "Should have 2 L1 files (old + new)");
    assert_eq!(m.l1_max_frame, Some(299));
}

#[tokio::test]
async fn test_compact_no_segments_returns_zero() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));

    let config = Config::new(&db_path);
    let shipper = build_shipper_with_config(config, store, manifest);

    let compacted = shipper.compact().await.unwrap();
    assert_eq!(compacted, 0, "Should return 0 when no segments exist");
}

#[tokio::test]
async fn test_gc_deletes_compacted_l0_segments() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, vec![0u8; 4096]).unwrap();

    let store = InMemoryStore::arc();
    let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
    manifest.lock().await.shipped_frames = 200; // Only frames 0-199 have been shipped
                                                // Set l1_max_frame to indicate frames 0-199 are covered by L1
    manifest.lock().await.l1_max_frame = Some(199);

    let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);

    // Put segments: some covered by L1, one active
    store
        .put(
            "wal/100-200/00000000-00000099.segment",
            vec![1u8; 100].into(),
        )
        .await
        .unwrap(); // covered by L1
    store
        .put(
            "wal/100-200/00000100-00000199.segment",
            vec![2u8; 100].into(),
        )
        .await
        .unwrap(); // covered by L1
    store
        .put(
            "wal/100-200/00000200-00000299.segment",
            vec![3u8; 100].into(),
        )
        .await
        .unwrap(); // active (start >= shipped_frames)

    let deleted = shipper.gc().await.unwrap();
    assert_eq!(deleted, 2, "Should delete 2 compacted L0 segments");

    // Active segment should still exist
    assert!(store
        .get("wal/100-200/00000200-00000299.segment")
        .await
        .unwrap()
        .is_some());
    // Compacted segments should be gone
    assert!(store
        .get("wal/100-200/00000000-00000099.segment")
        .await
        .unwrap()
        .is_none());
    assert!(store
        .get("wal/100-200/00000100-00000199.segment")
        .await
        .unwrap()
        .is_none());
}

#[tokio::test]
async fn test_snapshot_clears_l1_files() {
    let mut manifest = Manifest::new(100, 200, 4096);
    manifest.shipped_frames = 100;
    manifest
        .l1_files
        .push(wal_backup::replication::manifest::L1File {
            key: "wal/100-200/00000000-00000099.l1".to_string(),
            start_frame: 0,
            end_frame: 99,
            source_count: 3,
            checksum: None,
        });
    manifest.l1_max_frame = Some(99);

    // Simulate a snapshot — should clear L1 files
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        "checksum".to_string(),
        100,
        200,
        4096,
        4096,
    );

    assert!(
        manifest.l1_files.is_empty(),
        "L1 files should be cleared after snapshot"
    );
    assert_eq!(
        manifest.l1_max_frame, None,
        "l1_max_frame should be None after snapshot"
    );
    assert_eq!(
        manifest.shipped_frames, 0,
        "shipped_frames should be 0 after snapshot"
    );
}