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
mod common;

use object_store::local::LocalFileSystem;
use std::sync::Arc;
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
use wal_backup::restore::{read_page_size_from_db, read_page_size_from_db_async, RestoreEngine};
use wal_backup::ObjectStoreBucket;

use common::InMemoryStore;

fn make_db_with_page_size(page_size: u16) -> Vec<u8> {
    let mut data = vec![0u8; 100];
    data[16..18].copy_from_slice(&page_size.to_be_bytes());
    data
}

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

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(read_page_size_from_db_async(&db_path));
    assert!(result.is_err());
}

#[test]
fn test_read_page_size_from_db_async_ok() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(read_page_size_from_db_async(&db_path)).unwrap();
    assert_eq!(result, 4096);
}

#[test]
fn test_read_page_size_from_db_async_8192() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, make_db_with_page_size(8192)).unwrap();

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(read_page_size_from_db_async(&db_path)).unwrap();
    assert_eq!(result, 8192);
}

#[test]
fn test_read_page_size_from_db_special_1_means_65536() {
    let data = make_db_with_page_size(1);
    let result = read_page_size_from_db(&data).unwrap();
    assert_eq!(result, 65536);
}

#[test]
fn test_read_page_size_from_db_too_small() {
    let data = vec![0u8; 10];
    assert!(read_page_size_from_db(&data).is_err());
}

#[test]
fn test_local_is_newer_than_manifest_gen0_no_snapshot() {
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::Manifest;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();

    let inner = InMemoryStore::arc();
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, inner.clone());

    let manifest = Manifest::new(0x1234, 0x5678, 4096);

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));

    assert!(
        result,
        "generation=0 with no snapshot should be treated as newer (fresh start)"
    );
}

#[test]
fn test_local_is_newer_than_manifest_with_existing_snapshot() {
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::Manifest;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();

    let inner = InMemoryStore::arc();
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, inner.clone());

    let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
    manifest.generation = 5;
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        "sha256:abc".to_string(),
        0x1234,
        0x5678,
        4096,
        100,
    );
    manifest.last_updated = "2099-01-01T00:00:00Z".to_string();

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
    assert!(
        !result,
        "local DB with no generation file and bucket has snapshot should prefer bucket (anti-data-loss guard)"
    );
}

#[test]
fn test_local_is_newer_than_manifest_with_generation_and_snapshot() {
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::Manifest;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();

    let inner = InMemoryStore::arc();
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, inner.clone());

    let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
    manifest.generation = 5;
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        "sha256:abc".to_string(),
        0x1234,
        0x5678,
        4096,
        100,
    );
    manifest.last_updated = "2099-01-01T00:00:00Z".to_string();

    // Write a generation file matching the manifest — local is NOT newer
    let gen_path = db_path.with_extension("generation");
    std::fs::write(&gen_path, "5").unwrap();

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
    assert!(
        !result,
        "local DB with matching generation should NOT be newer than manifest"
    );

    // Write a generation file HIGHER than manifest — local IS newer
    std::fs::write(&gen_path, "10").unwrap();
    let result2 = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
    assert!(
        result2,
        "local DB with higher generation should be newer than manifest"
    );
}

#[test]
fn test_stale_generation_with_empty_db_restores_from_bucket() {
    // Edge case: high generation file + empty DB (someone deleted the DB
    // but forgot the generation file, then sqlite3 created a fresh DB).
    // The library should detect the DB is empty and restore from bucket
    // instead of uploading the empty DB and destroying bucket data.
    use common::InMemoryStore;
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::Manifest;
    use wal_backup::restore::RestoreEngine;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");

    // Create a FRESH empty DB (no user tables)
    let conn = rusqlite::Connection::open(&db_path).unwrap();
    conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY)")
        .unwrap();
    conn.execute_batch("DROP TABLE data").unwrap();
    drop(conn);

    // Write a stale generation file claiming gen 1000
    let gen_path = db_path.with_extension("generation");
    std::fs::write(&gen_path, "1000").unwrap();

    // Bucket has data at gen 5
    let inner = InMemoryStore::arc();
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, inner.clone());

    let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
    manifest.generation = 5;
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        "sha256:abc".to_string(),
        0x1234,
        0x5678,
        4096,
        100,
    );

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
    // With the stale generation guard, empty DB + high gen = NOT newer
    // (is_db_empty returns true, so local_newer is overridden to false)
    // Note: local_is_newer only returns the raw comparison;
    // the guard is in the restore() method. But we can test is_db_empty separately.
    // The raw comparison still returns true (gen 1000 > gen 5),
    // but restore() will override it. This test documents the behavior.
    assert!(
        result,
        "raw local_is_newer still returns true (gen 1000 > 5) — the guard is in restore()"
    );

    // Verify is_db_empty detects the empty DB
    let is_empty = rt.block_on(engine.is_db_empty()).unwrap();
    assert!(
        is_empty,
        "empty DB (no user tables) should be detected as empty"
    );

    // Now create a DB with actual data
    let conn = rusqlite::Connection::open(&db_path).unwrap();
    conn.execute_batch("CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT)")
        .unwrap();
    conn.execute("INSERT INTO events (kind) VALUES ('test')", [])
        .unwrap();
    drop(conn);

    let is_empty = rt.block_on(engine.is_db_empty()).unwrap();
    assert!(
        !is_empty,
        "DB with user tables should NOT be detected as empty"
    );
}

#[tokio::test]
async fn test_restore_fresh_start_no_manifest_no_local_db() {
    use wal_backup::config::{Config, RestoreBehavior};

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("fresh.db");
    let bucket_dir = tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).unwrap();

    let inner = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).unwrap());
    let bucket = Arc::new(ObjectStoreBucket::new(inner, "fresh".to_string()).unwrap());

    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, bucket);

    let manifest_arc = engine.restore().await.unwrap();
    let manifest = manifest_arc.lock().await;
    assert_eq!(manifest.current_salt_1, 0);
    assert_eq!(manifest.current_salt_2, 0);
    assert_eq!(manifest.generation, 0);
}

#[tokio::test]
async fn test_restore_fresh_start_no_manifest_with_local_wal() {
    use wal_backup::config::{Config, RestoreBehavior};

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("fresh.db");
    let wal_path = tmp.path().join("fresh.db-wal");

    let page_size = 4096u32;
    let magic = 0x377f0682u32;
    let file_format = 3007000u32;
    let checkpoint_seq = 1u32;
    let salt_1 = 0xDEADBEEFu32;
    let salt_2 = 0xCAFEBABEu32;

    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_backup::wal::checksum::wal_checksum_pair(0, 0, &header_data, false);

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

    std::fs::write(&wal_path, &wal_bytes).unwrap();
    std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();

    let bucket_dir = tmp.path().join("bucket2");
    std::fs::create_dir_all(&bucket_dir).unwrap();
    let inner = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).unwrap());
    let bucket = Arc::new(ObjectStoreBucket::new(inner, "wal_salt".to_string()).unwrap());

    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, bucket);

    let manifest_arc = engine.restore().await.unwrap();
    let manifest = manifest_arc.lock().await;
    assert_eq!(manifest.current_salt_1, salt_1);
    assert_eq!(manifest.current_salt_2, salt_2);
    assert_eq!(manifest.page_size, 4096);
}

#[tokio::test]
async fn test_restore_snapshot_checksum_mismatch_recoverable() {
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::Manifest;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");

    let mut store_data = std::collections::HashMap::new();

    let snapshot_bytes = make_db_with_page_size(4096);
    let wrong_checksum = "sha256:0000000000000000000000000000000000000000000000000000000000000000";

    store_data.insert("snapshots/test.db".to_string(), snapshot_bytes);

    let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        wrong_checksum.to_string(),
        0x1111,
        0x2222,
        4096,
        100,
    );
    let manifest_bytes = manifest.serialize().unwrap();
    store_data.insert("manifest.json".to_string(), manifest_bytes);

    let store = InMemoryStore::arc_with_data(store_data);
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::Recoverable);
    let engine = RestoreEngine::new(config, store);

    let result = engine.restore().await;
    assert!(
        result.is_ok(),
        "Recoverable mode should proceed despite checksum mismatch, got: {:?}",
        result
    );
}

#[tokio::test]
async fn test_restore_checksum_mismatch_non_recoverable_returns_error() {
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::Manifest;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");

    let mut store_data = std::collections::HashMap::new();

    let snapshot_bytes = make_db_with_page_size(4096);
    let wrong_checksum = "sha256:0000000000000000000000000000000000000000000000000000000000000000";

    store_data.insert("snapshots/test.db".to_string(), snapshot_bytes);

    let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        wrong_checksum.to_string(),
        0x1111,
        0x2222,
        4096,
        100,
    );
    let manifest_bytes = manifest.serialize().unwrap();
    store_data.insert("manifest.json".to_string(), manifest_bytes);

    let store = InMemoryStore::arc_with_data(store_data);
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, store);

    let result = engine.restore().await;
    assert!(
        result.is_err(),
        "UploadLocalIfNewer (non-Recoverable) should fail on checksum mismatch, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.to_string().contains("checksum mismatch"),
        "error should mention checksum mismatch, got: {err}"
    );
}

#[tokio::test]
async fn test_restore_no_snapshot_in_manifest_returns_error() {
    use wal_backup::config::Config;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");

    let mut store_data = std::collections::HashMap::new();

    let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
    manifest.generation = 5;
    manifest.last_updated = "2024-01-01T00:00:00Z".to_string();
    let manifest_bytes = manifest.serialize().unwrap();
    store_data.insert("manifest.json".to_string(), manifest_bytes);

    let store = InMemoryStore::arc_with_data(store_data);
    let config = Config::new(&db_path)
        .with_restore_behavior(wal_backup::RestoreBehavior::AlwaysRestoreFromBucket);
    let engine = RestoreEngine::new(config, store);

    let result = engine.restore().await;
    assert!(
        result.is_err(),
        "manifest with no snapshot should error, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.to_string().contains("No snapshot found"),
        "error should say 'No snapshot found', got: {err}"
    );
}

#[tokio::test]
async fn test_restore_snapshot_not_found_in_bucket_returns_error() {
    use wal_backup::config::{Config, RestoreBehavior};

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");

    let mut store_data = std::collections::HashMap::new();

    let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
    manifest.update_snapshot(
        "snapshots/missing.db".to_string(),
        "sha256:abc123".to_string(),
        0x1111,
        0x2222,
        4096,
        100,
    );
    let manifest_bytes = manifest.serialize().unwrap();
    store_data.insert("manifest.json".to_string(), manifest_bytes);

    let store = InMemoryStore::arc_with_data(store_data);
    let config =
        Config::new(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
    let engine = RestoreEngine::new(config, store);

    let result = engine.restore().await;
    assert!(result.is_err(), "missing snapshot file should error");
    let err = result.unwrap_err();
    assert!(
        err.to_string().contains("Snapshot not found"),
        "error should say 'Snapshot not found', got: {err}"
    );
}

#[tokio::test]
async fn test_restore_no_segments_but_shipped_frames_creates_wal_with_header() {
    use wal_backup::config::{Config, RestoreBehavior};

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");

    let mut store_data = std::collections::HashMap::new();

    let snapshot_bytes = make_db_with_page_size(4096);
    store_data.insert("snapshots/test.db".to_string(), snapshot_bytes.clone());

    let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        compute_sha256(&snapshot_bytes),
        0x1111,
        0x2222,
        4096,
        100,
    );
    manifest.shipped_frames = 5;
    let manifest_bytes = manifest.serialize().unwrap();
    store_data.insert("manifest.json".to_string(), manifest_bytes);

    let store = InMemoryStore::arc_with_data(store_data);
    let config =
        Config::new(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
    let engine = RestoreEngine::new(config, store);

    let result = engine.restore().await;
    assert!(
        result.is_ok(),
        "restore with shipped_frames but no segments should succeed (no WAL file created), got: {:?}",
        result
    );

    let wal_path = db_path.with_extension("db-wal");
    assert!(
        wal_path.exists(),
        "WAL file should be created with header even when there are no segments to download"
    );
}

#[test]
fn test_local_is_newer_than_manifest_true_by_timestamp() {
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::Manifest;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("test.db");
    std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();

    let inner = InMemoryStore::arc();
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, inner.clone());

    let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
    manifest.generation = 5;
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        "sha256:abc".to_string(),
        0x1234,
        0x5678,
        4096,
        100,
    );
    manifest.last_updated = "2020-01-01T00:00:00Z".to_string();

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
    assert!(
        !result,
        "local DB with no generation file and bucket has snapshot should prefer bucket (anti-data-loss guard)"
    );
}

#[test]
fn test_local_is_newer_than_manifest_no_local_db_returns_false() {
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::Manifest;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("nonexistent.db");

    let inner = InMemoryStore::arc();
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, inner.clone());

    let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
    manifest.generation = 5;
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        "sha256:abc".to_string(),
        0x1234,
        0x5678,
        4096,
        100,
    );
    manifest.last_updated = "2020-01-01T00:00:00Z".to_string();

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
    assert!(
        !result,
        "no local DB file should not be newer than manifest"
    );
}

use wal_backup::util::compute_sha256;

#[tokio::test]
async fn test_restore_with_segments_synthesizes_wal_header() {
    use wal_backup::config::{Config, RestoreBehavior};

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("synth.db");

    let snapshot_bytes = make_db_with_page_size(4096);

    let salt_1: u32 = 0xDEAD;
    let salt_2: u32 = 0xBEEF;

    let mut manifest = Manifest::new(salt_1, salt_2, 4096);
    manifest.update_snapshot(
        "snapshots/synth.db".to_string(),
        compute_sha256(&snapshot_bytes),
        salt_1,
        salt_2,
        4096,
        snapshot_bytes.len() as u64,
    );
    manifest.shipped_frames = 1;

    let segment_prefix = manifest.segment_prefix();
    let segment_key = format!("{}00000000-00000001.segment", segment_prefix);

    let magic: u32 = 0x377f0682;
    let page_size: u32 = 4096;
    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_backup::wal::checksum::wal_checksum_pair(0, 0, &header_data, false);

    let page_number: u32 = 1;
    let db_size_after: u32 = 1;
    let frame_page_data = vec![0u8; 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_page_data);

    let (fc1, fc2) = wal_backup::wal::checksum::wal_checksum_pair(ck1, ck2, &checksum_input, false);

    let mut segment = Vec::new();
    segment.extend_from_slice(&page_number.to_be_bytes());
    segment.extend_from_slice(&db_size_after.to_be_bytes());
    segment.extend_from_slice(&salt_1.to_be_bytes());
    segment.extend_from_slice(&salt_2.to_be_bytes());
    segment.extend_from_slice(&fc1.to_be_bytes());
    segment.extend_from_slice(&fc2.to_be_bytes());
    segment.extend_from_slice(&frame_page_data);

    let mut store_data = std::collections::HashMap::new();
    store_data.insert("snapshots/synth.db".to_string(), snapshot_bytes);
    store_data.insert("manifest.json".to_string(), manifest.serialize().unwrap());
    store_data.insert(segment_key, segment);

    let store = InMemoryStore::arc_with_data(store_data);
    let config =
        Config::new(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
    let engine = RestoreEngine::new(config, store);

    let result = engine.restore().await;
    assert!(
        result.is_ok(),
        "restore with segments should succeed even without existing WAL: {:?}",
        result
    );

    let wal_path = db_path.with_extension("db-wal");
    assert!(
        wal_path.exists(),
        "WAL file should be created after restore"
    );
}

#[tokio::test]
async fn test_restore_checksum_mismatch_errorifconflict_returns_error() {
    use wal_backup::config::{Config, RestoreBehavior};

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("errorconflict.db");

    let mut store_data = std::collections::HashMap::new();

    let snapshot_bytes = make_db_with_page_size(4096);
    let wrong_checksum = "sha256:0000000000000000000000000000000000000000000000000000000000000000";

    store_data.insert("snapshots/test.db".to_string(), snapshot_bytes);

    let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        wrong_checksum.to_string(),
        0x1111,
        0x2222,
        4096,
        100,
    );
    let manifest_bytes = manifest.serialize().unwrap();
    store_data.insert("manifest.json".to_string(), manifest_bytes);

    let store = InMemoryStore::arc_with_data(store_data);
    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::ErrorIfConflict);
    let engine = RestoreEngine::new(config, store);

    let result = engine.restore().await;
    assert!(
        result.is_err(),
        "ErrorIfConflict should also fail on checksum mismatch (falls through to _ branch): {:?}",
        result
    );
}

#[tokio::test]
async fn test_restore_checksum_uses_streaming_hash() {
    let tmp = tempfile::tempdir().unwrap();
    let bucket_dir = tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).unwrap();

    let db_path = tmp.path().join("streaming_hash.db");
    let conn = rusqlite::Connection::open(&db_path).unwrap();
    conn.execute_batch("PRAGMA journal_mode = WAL").unwrap();
    conn.execute_batch("PRAGMA wal_autocheckpoint = 0").unwrap();
    conn.execute_batch("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, val TEXT NOT NULL)")
        .unwrap();
    conn.execute("INSERT INTO t (val) VALUES ('x')", [])
        .unwrap();
    drop(conn);

    let db_bytes = std::fs::read(&db_path).unwrap();
    let expected_checksum = wal_backup::util::compute_sha256(&db_bytes);
    let page_size = read_page_size_from_db(&db_bytes).unwrap();

    let mut store_data = std::collections::HashMap::new();
    store_data.insert("snapshots/test.db".to_string(), db_bytes);

    let mut manifest = Manifest::new(0x1111, 0x2222, page_size);
    manifest.update_snapshot(
        "snapshots/test.db".to_string(),
        expected_checksum.clone(),
        0x1111,
        0x2222,
        page_size,
        100,
    );
    let manifest_bytes = manifest.serialize().unwrap();
    store_data.insert("manifest.json".to_string(), manifest_bytes);

    let store = InMemoryStore::arc_with_data(store_data);

    let restore_db_path = tmp.path().join("restored.db");
    let config = Config::new(&restore_db_path)
        .with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
    let engine = RestoreEngine::new(config, store);
    let result = engine.restore().await;
    assert!(
        result.is_ok(),
        "restore should succeed with matching checksum: {:?}",
        result
    );
    assert!(restore_db_path.exists(), "restored DB should exist on disk");
}

#[tokio::test]
async fn test_upload_local_preserves_wal_salt_before_truncate() {
    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("salt_test.db");

    let conn = rusqlite::Connection::open(&db_path).unwrap();
    conn.execute_batch("PRAGMA journal_mode = WAL").unwrap();
    conn.execute_batch("PRAGMA wal_autocheckpoint = 0").unwrap();
    conn.execute_batch("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY)")
        .unwrap();
    conn.execute("INSERT INTO t DEFAULT VALUES", []).unwrap();

    let wal_path = db_path.with_extension("db-wal");
    let original_salt = {
        let wal = wal_backup::WalFile::open(&wal_path).unwrap();
        (wal.header().salt_1, wal.header().salt_2)
    };
    assert!(
        original_salt.0 != 0 || original_salt.1 != 0,
        "WAL should have non-zero salts after write"
    );

    let mut store_data = std::collections::HashMap::new();
    let manifest = Manifest::new(0, 0, 4096);
    let manifest_bytes = manifest.serialize().unwrap();
    store_data.insert("manifest.json".to_string(), manifest_bytes);
    let store = InMemoryStore::arc_with_data(store_data);

    let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
    let engine = RestoreEngine::new(config, store);
    let result = engine.restore().await;
    assert!(result.is_ok(), "restore should succeed: {:?}", result);

    let manifest_arc = result.unwrap();
    let manifest_guard = manifest_arc.lock().await;
    assert_eq!(
        (manifest_guard.current_salt_1, manifest_guard.current_salt_2),
        original_salt,
        "manifest should preserve WAL salt values from before checkpoint truncation"
    );

    drop(conn);
}

fn compute_sha256_for_restore(data: &[u8]) -> String {
    use sha2::Digest;
    let mut hasher = sha2::Sha256::new();
    hasher.update(data);
    let result = sha2::Digest::finalize(hasher);
    format!(
        "sha256:{}",
        result
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>()
    )
}

#[tokio::test]
async fn test_restore_with_l1_and_uncovered_l0_segments() {
    use wal_backup::config::{Config, RestoreBehavior};
    use wal_backup::replication::manifest::{L1File, Manifest};
    use wal_backup::wal::checksum::wal_checksum_pair;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("l1_restore.db");

    let snapshot_bytes = make_db_with_page_size(4096);
    let snapshot_checksum = compute_sha256_for_restore(&snapshot_bytes);

    let salt_1: u32 = 0xAAAA;
    let salt_2: u32 = 0xBBBB;

    let mut manifest = Manifest::new(salt_1, salt_2, 4096);
    manifest.update_snapshot(
        "snapshots/l1_restore.db".to_string(),
        snapshot_checksum.clone(),
        salt_1,
        salt_2,
        4096,
        snapshot_bytes.len() as u64,
    );
    manifest.shipped_frames = 2;
    manifest.l1_files.push(L1File {
        key: format!("wal/{}-{}/{:08}-{:08}.l1", salt_1, salt_2, 0, 0),
        start_frame: 0,
        end_frame: 0,
        source_count: 1,
        checksum: None,
    });
    manifest.l1_max_frame = Some(0);

    let magic: u32 = 0x377f0682;
    let page_size: u32 = 4096;
    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 page_number: u32 = 1;
    let db_size_after: u32 = 1;
    let frame_page_data = vec![0u8; 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_page_data);
    let (fc1, fc2) = wal_checksum_pair(ck1, ck2, &checksum_input, false);

    let mut frame0_data = Vec::new();
    frame0_data.extend_from_slice(&page_number.to_be_bytes());
    frame0_data.extend_from_slice(&db_size_after.to_be_bytes());
    frame0_data.extend_from_slice(&salt_1.to_be_bytes());
    frame0_data.extend_from_slice(&salt_2.to_be_bytes());
    frame0_data.extend_from_slice(&fc1.to_be_bytes());
    frame0_data.extend_from_slice(&fc2.to_be_bytes());
    frame0_data.extend_from_slice(&frame_page_data);

    let page_number_1: u32 = 2;
    let mut checksum_input2 = Vec::with_capacity(8 + page_size as usize);
    checksum_input2.extend_from_slice(&page_number_1.to_be_bytes());
    checksum_input2.extend_from_slice(&db_size_after.to_be_bytes());
    checksum_input2.extend_from_slice(&frame_page_data);
    let (fc1b, fc2b) = wal_checksum_pair(fc1, fc2, &checksum_input2, false);

    let mut frame1_data = Vec::new();
    frame1_data.extend_from_slice(&page_number_1.to_be_bytes());
    frame1_data.extend_from_slice(&db_size_after.to_be_bytes());
    frame1_data.extend_from_slice(&salt_1.to_be_bytes());
    frame1_data.extend_from_slice(&salt_2.to_be_bytes());
    frame1_data.extend_from_slice(&fc1b.to_be_bytes());
    frame1_data.extend_from_slice(&fc2b.to_be_bytes());
    frame1_data.extend_from_slice(&frame_page_data);

    let l1_key = format!("wal/{}-{}/{:08}-{:08}.l1", salt_1, salt_2, 0, 0);
    let l0_key = format!("wal/{}-{}/{:08}-{:08}.segment", salt_1, salt_2, 1, 2);

    let mut store_data = std::collections::HashMap::new();
    store_data.insert("snapshots/l1_restore.db".to_string(), snapshot_bytes);
    store_data.insert("manifest.json".to_string(), manifest.serialize().unwrap());
    store_data.insert(l1_key, frame0_data);
    store_data.insert(l0_key, frame1_data);

    let store = InMemoryStore::arc_with_data(store_data);
    let config =
        Config::new(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
    let engine = RestoreEngine::new(config, store);

    let result = engine.restore().await;
    assert!(
        result.is_ok(),
        "restore with L1 + L0 should succeed: {:?}",
        result
    );

    let wal_path = db_path.with_extension("db-wal");
    assert!(wal_path.exists(), "WAL file should exist after restore");

    let wal_data = std::fs::read(&wal_path).unwrap();
    let wal_frame_size = (24 + page_size) as usize;
    let wal_data_size = wal_data.len() - 32;
    assert_eq!(
        wal_data_size / wal_frame_size,
        2,
        "WAL should have 2 frames (1 from L1, 1 from L0)"
    );
}