reddb-io-server 1.45.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
//! Serverless object-storage recovery copies: WAL archive (RPO ≤ 5 s) and
//! physical generations.
//!
//! While a lease-fenced writer runs, data and WAL live on its local disk and a
//! commit is acknowledged once the local WAL is durable. The bucket only holds
//! recovery copies:
//!
//! * immutable WAL segments, uploaded at most once per archive window (4 s by
//!   default, so the recovery point stays within 5 s including the upload)
//!   and only when new WAL exists, so an idle database issues no
//!   object-store writes;
//! * immutable physical generations — a checkpoint-consistent copy of every
//!   file needed to reopen the store — published through `HEAD.json` CAS;
//! * `HEAD.json`, which names the current generation, the stream LSN it
//!   includes, and which writer claim (epoch) owns each later stream range.
//!
//! Uploads run on their own threads. They never hold the lease transition
//! lock and never block commits; the commit path only appends to the local
//! WAL. Restore downloads the generation, appends the archived frames after
//! its stream LSN to the restored WAL, and lets normal crash recovery replay
//! them. A missing, corrupted, or foreign segment fails the restore closed.

use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};

use super::*;
use crate::runtime::lease_lifecycle::LeaseLifecycle;
use crate::runtime::serverless_snapshot_publication::{
    GenerationPointer, SnapshotPublicationError, SnapshotPublicationStore,
};
use crate::storage::backend::{AtomicRemoteBackend, BackendError};
use crate::storage::unified::store::WalArchiveTap;

/// 4 s window + an upload (p90 ≈ 0.8 s measured São Paulo → R2) keeps the
/// recovery point within 5 s.
const DEFAULT_ARCHIVE_INTERVAL_MS: u64 = 4_000;
/// Slack on top of the window for the in-flight upload.
const UPLOAD_ALLOWANCE: Duration = Duration::from_secs(1);
const DEFAULT_MAX_SEGMENT_BYTES: u64 = 16 * 1024 * 1024;
const DEFAULT_PAUSE_ON_LAG_SECS: u64 = 30;
const DEFAULT_GENERATION_WAL_BYTES: u64 = 256 * 1024 * 1024;
const DEFAULT_GENERATION_INTERVAL_SECS: u64 = 6 * 60 * 60;
const SHUTDOWN_FLUSH_ATTEMPTS: u32 = 20;
/// Each boot adds a claim to `HEAD.json`; sleep publishes a generation once
/// this many accumulate so the head stays small.
const MAX_CLAIMS_WITHOUT_GENERATION: usize = 8;

/// Whether lease-fenced paged stores use the generation + WAL archive
/// protocol. Opt-in (`RED_SERVERLESS_WAL_ARCHIVE=true`): the first boot
/// rewrites `HEAD.json` to format 2, which older binaries refuse, so the
/// switch is one-way and must be chosen explicitly.
pub fn archive_enabled() -> bool {
    std::env::var("RED_SERVERLESS_WAL_ARCHIVE")
        .ok()
        .map(|value| {
            matches!(
                value.trim().to_ascii_lowercase().as_str(),
                "1" | "true" | "yes" | "on"
            )
        })
        .unwrap_or(false)
}

#[derive(Debug, Clone)]
pub struct ServerlessArchiveConfig {
    /// Batch window: captured WAL is uploaded no later than this after the
    /// oldest frame in the batch was captured (`RED_WAL_ARCHIVE_INTERVAL_MS`).
    pub interval: Duration,
    /// Seal a batch early once it reaches this size
    /// (`RED_WAL_ARCHIVE_MAX_SEGMENT_BYTES`).
    pub max_segment_bytes: u64,
    /// Refuse writes while the archive lag exceeds this many seconds
    /// (`RED_WAL_ARCHIVE_PAUSE_ON_LAG_SECS`, `0` disables).
    pub pause_on_lag_secs: u64,
    /// Publish a new generation after this many archived WAL bytes
    /// (`RED_SERVERLESS_GENERATION_WAL_BYTES`, `0` disables).
    pub generation_wal_bytes: u64,
    /// Publish a new generation after this long if any WAL was archived
    /// (`RED_SERVERLESS_GENERATION_INTERVAL_SECS`, `0` disables).
    pub generation_interval: Duration,
}

impl ServerlessArchiveConfig {
    pub fn from_env() -> Self {
        fn env_u64(name: &str, default: u64) -> u64 {
            std::env::var(name)
                .ok()
                .and_then(|value| value.trim().parse::<u64>().ok())
                .unwrap_or(default)
        }
        Self {
            interval: Duration::from_millis(
                env_u64("RED_WAL_ARCHIVE_INTERVAL_MS", DEFAULT_ARCHIVE_INTERVAL_MS).max(50),
            ),
            max_segment_bytes: env_u64(
                "RED_WAL_ARCHIVE_MAX_SEGMENT_BYTES",
                DEFAULT_MAX_SEGMENT_BYTES,
            )
            .max(64 * 1024),
            pause_on_lag_secs: env_u64(
                "RED_WAL_ARCHIVE_PAUSE_ON_LAG_SECS",
                DEFAULT_PAUSE_ON_LAG_SECS,
            ),
            generation_wal_bytes: env_u64(
                "RED_SERVERLESS_GENERATION_WAL_BYTES",
                DEFAULT_GENERATION_WAL_BYTES,
            ),
            generation_interval: Duration::from_secs(env_u64(
                "RED_SERVERLESS_GENERATION_INTERVAL_SECS",
                DEFAULT_GENERATION_INTERVAL_SECS,
            )),
        }
    }

    /// Documented recovery-point bound: one batch window plus one upload
    /// (5 s at the default window).
    pub fn lag_bound(&self) -> Duration {
        self.interval + UPLOAD_ALLOWANCE
    }
}

/// What a generation restore reconstructed in the local directory.
#[derive(Debug, Clone)]
pub struct RestoredStream {
    pub data_path: PathBuf,
    pub generation_wal_lsn: u64,
    /// Last stream LSN appended to the restored WAL.
    pub last_lsn: u64,
    /// Digest of the last fully replayed segment (the next segment's link).
    pub last_sha256: Option<[u8; 32]>,
    pub segments_replayed: u64,
    pub frames_replayed: u64,
    pub bytes_downloaded: u64,
    pub duration: Duration,
}

/// Rebuild the local files of `head`'s generation in `target_dir` and append
/// the archived WAL frames that follow it. The directory must not already
/// contain the generation's files. Fails closed on any checksum, size, LSN,
/// chain, or ownership mismatch; the caller must not open a partial restore.
pub fn restore_generation(
    backend: &dyn AtomicRemoteBackend,
    head: &reddb_file::ServerlessSnapshotHead,
    target_dir: &Path,
) -> Result<RestoredStream, String> {
    let started = Instant::now();
    let generation = head
        .generation
        .as_ref()
        .ok_or("serverless head has no generation")?;
    let manifest_bytes = download_bytes(backend, &generation.manifest_key)?.ok_or_else(|| {
        format!(
            "generation manifest '{}' is missing",
            generation.manifest_key
        )
    })?;
    let manifest = reddb_file::decode_serverless_generation_manifest_json(&manifest_bytes)
        .map_err(|err| format!("generation manifest '{}': {err}", generation.manifest_key))?;
    if manifest.database_key != head.database_key {
        return Err(format!(
            "generation manifest belongs to '{}', head to '{}'",
            manifest.database_key, head.database_key
        ));
    }
    if manifest.wal_lsn != generation.wal_lsn {
        return Err(format!(
            "generation manifest includes stream LSN {}, head says {}",
            manifest.wal_lsn, generation.wal_lsn
        ));
    }
    std::fs::create_dir_all(target_dir).map_err(|err| err.to_string())?;
    let mut bytes_downloaded = manifest_bytes.len() as u64;
    let mut data_path = None;
    let mut wal_path = None;
    for file in &manifest.files {
        reddb_file::validate_serverless_generation_relative_path(&file.relative_path)
            .map_err(|err| err.to_string())?;
        if file.relative_path.is_empty() {
            return Err("generation file has an empty path".into());
        }
        let target = target_dir.join(&file.relative_path);
        if target.exists() {
            return Err(format!(
                "restore target {} already exists; restore needs an empty directory",
                target.display()
            ));
        }
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent).map_err(|err| err.to_string())?;
        }
        if !backend
            .download(&file.key, &target)
            .map_err(|err| format!("download {}: {err}", file.key))?
        {
            return Err(format!("generation file '{}' is missing", file.key));
        }
        let size = std::fs::metadata(&target)
            .map_err(|err| err.to_string())?
            .len();
        if size != file.size {
            return Err(format!(
                "generation file '{}' has {size} bytes, manifest says {}",
                file.key, file.size
            ));
        }
        let digest = reddb_file::sha256_file_hex(&target).map_err(|err| err.to_string())?;
        if digest != file.sha256 {
            return Err(format!("generation file '{}' checksum mismatch", file.key));
        }
        bytes_downloaded += size;
        match file.role {
            reddb_file::ServerlessGenerationFileRole::Data => data_path = Some(target),
            reddb_file::ServerlessGenerationFileRole::Wal => wal_path = Some(target),
            _ => {}
        }
    }
    let data_path = data_path.ok_or("generation has no data file")?;
    let wal_path = wal_path.ok_or("generation has no WAL file")?;
    let wal_version = {
        let mut header = [0u8; reddb_file::WAL_FILE_HEADER_BYTES];
        std::fs::File::open(&wal_path)
            .and_then(|mut file| file.read_exact(&mut header))
            .map_err(|err| format!("read restored WAL header: {err}"))?;
        reddb_file::decode_wal_file_header(&header)
            .map_err(|err| format!("restored WAL header: {err}"))?
            .version
    };

    let mut wal_out = std::fs::OpenOptions::new()
        .append(true)
        .open(&wal_path)
        .map_err(|err| err.to_string())?;
    let mut expected = generation
        .wal_lsn
        .checked_add(1)
        .ok_or("generation stream LSN overflows")?;
    let mut prev = manifest.wal_prev_sha256;
    let mut segments_replayed = 0u64;
    let mut frames_replayed = 0u64;
    for (index, claim) in generation.wal_epochs.iter().enumerate() {
        let owned_end = generation
            .wal_epochs
            .get(index + 1)
            .map(|next| next.start_lsn);
        if owned_end.is_some_and(|end| end <= expected) {
            continue;
        }
        if claim.start_lsn > expected {
            return Err(format!(
                "archived WAL gap: stream stops at LSN {} but epoch {} starts at {}",
                expected - 1,
                claim.epoch,
                claim.start_lsn
            ));
        }
        let prefix = reddb_file::serverless_wal_epoch_prefix(&head.database_key, claim.epoch);
        let mut segments: Vec<(u64, u64, String)> = backend
            .list(&prefix)
            .map_err(|err| format!("list {prefix}: {err}"))?
            .into_iter()
            .filter_map(|key| {
                let (epoch, first, last) = reddb_file::parse_serverless_wal_segment_key(&key)?;
                (epoch == claim.epoch).then_some((first, last, key))
            })
            .collect();
        segments.sort();
        for (first, last, key) in segments {
            if last < expected {
                continue;
            }
            if owned_end.is_some_and(|end| first >= end) {
                // A stale writer kept uploading after its successor claimed
                // the head. Those frames were never acknowledged as current.
                break;
            }
            if first > expected {
                return Err(format!(
                    "archived WAL gap: expected stream LSN {expected}, next segment '{key}' starts at {first}"
                ));
            }
            let bytes = download_bytes(backend, &key)?
                .ok_or_else(|| format!("archived WAL segment '{key}' vanished during restore"))?;
            bytes_downloaded += bytes.len() as u64;
            let segment = reddb_file::decode_serverless_wal_segment(&bytes)
                .map_err(|err| format!("archived WAL segment '{key}': {err}"))?;
            let header = &segment.header;
            if header.epoch != claim.epoch || header.first_lsn != first || header.last_lsn != last {
                return Err(format!(
                    "archived WAL segment '{key}' header does not match its key"
                ));
            }
            if header.wal_format_version != wal_version {
                return Err(format!(
                    "archived WAL segment '{key}' has WAL format {} but the generation has {wal_version}",
                    header.wal_format_version
                ));
            }
            if first == expected {
                if let Some(expected_prev) = prev {
                    if header.prev_sha256 != Some(expected_prev) {
                        return Err(format!(
                            "archived WAL segment '{key}' does not link to the previous segment"
                        ));
                    }
                }
            }
            let take_end = owned_end.map_or(last + 1, |end| end.min(last + 1));
            for (offset, frame) in segment.frames.iter().enumerate() {
                let lsn = first + offset as u64;
                if lsn < expected || lsn >= take_end {
                    continue;
                }
                wal_out.write_all(frame).map_err(|err| err.to_string())?;
                frames_replayed += 1;
            }
            prev = (take_end == last + 1).then_some(segment.sha256);
            expected = take_end;
            segments_replayed += 1;
        }
        if let Some(end) = owned_end {
            if expected < end {
                return Err(format!(
                    "archived WAL gap: epoch {} stops at LSN {} but its successor starts at {end}",
                    claim.epoch,
                    expected - 1
                ));
            }
        }
    }
    wal_out.sync_all().map_err(|err| err.to_string())?;
    Ok(RestoredStream {
        data_path,
        generation_wal_lsn: generation.wal_lsn,
        last_lsn: expected - 1,
        last_sha256: prev,
        segments_replayed,
        frames_replayed,
        bytes_downloaded,
        duration: started.elapsed(),
    })
}

fn download_bytes(backend: &dyn AtomicRemoteBackend, key: &str) -> Result<Option<Vec<u8>>, String> {
    let temp = reddb_file::ServerlessWriterLeaseTempFile::new("archive-download");
    if !backend
        .download(key, temp.path())
        .map_err(|err| format!("download {key}: {err}"))?
    {
        return Ok(None);
    }
    temp.read_bytes().map(Some).map_err(|err| err.to_string())
}

/// Counters and gauges exported on `/metrics`.
#[derive(Debug, Default)]
pub struct ServerlessArchiveMetrics {
    pub last_archived_lsn: AtomicU64,
    pub segments_uploaded_total: AtomicU64,
    pub bytes_uploaded_total: AtomicU64,
    /// Object-store write requests (PUT) issued by the archive and
    /// generation paths — the R2 "Class A" operations.
    pub put_requests_total: AtomicU64,
    pub upload_errors_total: AtomicU64,
    pub lag_over_bound_total: AtomicU64,
    pub generations_published_total: AtomicU64,
    pub generation_errors_total: AtomicU64,
    pub generation_wal_lsn: AtomicU64,
    pub last_generation_bytes: AtomicU64,
    pub last_generation_duration_ms: AtomicU64,
    pub bytes_since_generation: AtomicU64,
    pub restore_duration_ms: AtomicU64,
    pub restore_segments: AtomicU64,
    pub restore_frames: AtomicU64,
}

/// Point-in-time archive state.
#[derive(Debug, Clone, Copy)]
pub struct ServerlessArchiveStatus {
    pub epoch: u64,
    pub last_archived_lsn: u64,
    pub captured_lsn: u64,
    pub lag: Duration,
    pub lag_bytes: u64,
    pub lag_bound: Duration,
    pub over_bound: bool,
}

pub struct ServerlessWalArchive {
    backend: Arc<dyn AtomicRemoteBackend>,
    publication: Arc<SnapshotPublicationStore>,
    lease: OnceLock<Arc<LeaseLifecycle>>,
    tap: Arc<WalArchiveTap>,
    database_key: String,
    epoch: u64,
    config: ServerlessArchiveConfig,
    pub metrics: ServerlessArchiveMetrics,
    stop: AtomicBool,
    /// Serializes segment uploads between the archiver and shutdown flush.
    upload_lock: Mutex<()>,
    /// Serializes generation publications.
    generation_lock: Mutex<()>,
    generation_request: (Mutex<bool>, Condvar),
    last_generation_at: Mutex<Instant>,
    /// Writes that reach the data file outside the commit WAL (auth vault
    /// pages). While one is not yet covered by a published generation, WAL
    /// segments are held back: restoring later WAL on top of a generation
    /// without that write would mix states the writer never had.
    out_of_wal_writes: AtomicU64,
    out_of_wal_covered: AtomicU64,
    /// `(write number, first stream LSN that may depend on it)` for every
    /// out-of-WAL write not yet covered by a generation. Segments that end
    /// below the oldest entry's LSN keep uploading.
    out_of_wal_holds: Mutex<std::collections::VecDeque<(u64, u64)>>,
    over_bound: AtomicBool,
    threads: Mutex<Vec<std::thread::JoinHandle<()>>>,
    generation_thread: Mutex<Option<std::thread::JoinHandle<()>>>,
}

impl ServerlessWalArchive {
    pub(crate) fn new(
        backend: Arc<dyn AtomicRemoteBackend>,
        publication: Arc<SnapshotPublicationStore>,
        tap: Arc<WalArchiveTap>,
        epoch: u64,
        config: ServerlessArchiveConfig,
        restored: Option<&RestoredStream>,
    ) -> Self {
        let database_key = publication.database_key().to_string();
        let metrics = ServerlessArchiveMetrics::default();
        if let Some(restored) = restored {
            metrics
                .last_archived_lsn
                .store(restored.last_lsn, Ordering::Release);
            metrics
                .generation_wal_lsn
                .store(restored.generation_wal_lsn, Ordering::Release);
            metrics
                .restore_duration_ms
                .store(restored.duration.as_millis() as u64, Ordering::Release);
            metrics
                .restore_segments
                .store(restored.segments_replayed, Ordering::Release);
            metrics
                .restore_frames
                .store(restored.frames_replayed, Ordering::Release);
        }
        Self {
            backend,
            publication,
            lease: OnceLock::new(),
            tap,
            database_key,
            epoch,
            config,
            metrics,
            stop: AtomicBool::new(false),
            upload_lock: Mutex::new(()),
            generation_lock: Mutex::new(()),
            generation_request: (Mutex::new(false), Condvar::new()),
            last_generation_at: Mutex::new(Instant::now()),
            out_of_wal_writes: AtomicU64::new(0),
            out_of_wal_covered: AtomicU64::new(0),
            out_of_wal_holds: Mutex::new(std::collections::VecDeque::new()),
            over_bound: AtomicBool::new(false),
            threads: Mutex::new(Vec::new()),
            generation_thread: Mutex::new(None),
        }
    }

    pub fn epoch(&self) -> u64 {
        self.epoch
    }

    pub fn config(&self) -> &ServerlessArchiveConfig {
        &self.config
    }

    pub(crate) fn attach_lease(&self, lease: Arc<LeaseLifecycle>) {
        let _ = self.lease.set(lease);
    }

    /// Record a durable write that bypassed the commit WAL and ask for a
    /// generation that captures it.
    pub fn note_out_of_wal_write(&self) {
        // Every frame captured before this point committed before the write;
        // frames numbered from here on may depend on it.
        self.hold_from(self.tap.status().next_lsn);
        self.request_generation();
    }

    fn hold_from(&self, first_dependent_lsn: u64) {
        let mut holds = self.out_of_wal_holds.lock().expect("poisoned holds");
        let write = self.out_of_wal_writes.fetch_add(1, Ordering::AcqRel) + 1;
        holds.push_back((write, first_dependent_lsn));
    }

    /// Segments must end below this stream LSN to upload now.
    fn upload_floor(&self) -> u64 {
        self.out_of_wal_holds
            .lock()
            .expect("poisoned holds")
            .front()
            .map_or(u64::MAX, |(_, lsn)| *lsn)
    }

    fn release_holds_through(&self, covered_write: u64) {
        self.out_of_wal_covered
            .fetch_max(covered_write, Ordering::AcqRel);
        let mut holds = self.out_of_wal_holds.lock().expect("poisoned holds");
        while holds
            .front()
            .is_some_and(|(write, _)| *write <= covered_write)
        {
            holds.pop_front();
        }
    }

    fn out_of_wal_pending(&self) -> bool {
        self.out_of_wal_writes.load(Ordering::Acquire)
            > self.out_of_wal_covered.load(Ordering::Acquire)
    }

    /// Publish a generation now if an out-of-WAL write is not yet covered.
    pub fn publish_if_out_of_wal_pending(&self, runtime: &RedDBRuntime) -> RedDBResult<()> {
        if self.out_of_wal_pending() {
            self.publish_generation(runtime)?;
        }
        Ok(())
    }

    pub fn status(&self) -> ServerlessArchiveStatus {
        let tap = self.tap.status();
        let lag = tap
            .oldest_unarchived_at
            .map(|oldest| oldest.elapsed())
            .unwrap_or_default();
        let lag_bound = self.config.lag_bound();
        ServerlessArchiveStatus {
            epoch: self.epoch,
            last_archived_lsn: self.metrics.last_archived_lsn.load(Ordering::Acquire),
            captured_lsn: tap.next_lsn.saturating_sub(1),
            lag,
            lag_bytes: tap.pending_bytes + tap.sealed_bytes,
            lag_bound,
            over_bound: lag > lag_bound || self.tap.discontinuity().is_some(),
        }
    }

    /// Stage and upload a generation under `prefix` without making it
    /// current. Uploads run without any lease or store lock.
    pub(crate) fn stage_and_upload_generation(
        &self,
        runtime: &RedDBRuntime,
        sequence: u64,
        cancellable: bool,
    ) -> RedDBResult<(GenerationPointer, u64)> {
        let staged = runtime.stage_serverless_generation()?;
        let nonce = format!(
            "{:x}{:x}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        );
        let prefix = reddb_file::serverless_generation_prefix(
            &self.database_key,
            self.epoch,
            sequence,
            &nonce,
        );
        let mut files = Vec::with_capacity(staged.files.len());
        let mut data_key = None;
        let mut total = 0u64;
        for file in &staged.files {
            // A background generation yields to shutdown between files so
            // the final WAL flush never waits for a whole store upload.
            if cancellable && self.stop.load(Ordering::Acquire) {
                return Err(RedDBError::Internal(
                    "generation upload cancelled by shutdown".into(),
                ));
            }
            let key = format!("{prefix}files/{}", file.relative_path);
            let size = std::fs::metadata(&file.path)
                .map_err(|err| RedDBError::Internal(err.to_string()))?
                .len();
            let sha256 = reddb_file::sha256_file_hex(&file.path)
                .map_err(|err| RedDBError::Internal(err.to_string()))?;
            self.put_immutable(&file.path, &key)?;
            if file.role == reddb_file::ServerlessGenerationFileRole::Data {
                data_key = Some(key.clone());
            }
            total += size;
            files.push(reddb_file::ServerlessGenerationFile {
                role: file.role,
                relative_path: file.relative_path.clone(),
                key,
                size,
                sha256,
            });
        }
        let manifest = reddb_file::ServerlessGenerationManifest {
            database_key: self.database_key.clone(),
            epoch: self.epoch,
            sequence,
            wal_lsn: staged.cut.wal_lsn,
            wal_prev_sha256: staged.cut.prev_sha256,
            created_at_ms: unix_ms_now(),
            files,
        };
        let manifest_key = reddb_file::serverless_generation_manifest_key(&prefix);
        let bytes = reddb_file::encode_serverless_generation_manifest_json(&manifest)
            .map_err(|err| RedDBError::Internal(err.to_string()))?;
        let temp = reddb_file::ServerlessWriterLeaseTempFile::new("generation-manifest");
        temp.write_bytes(&bytes)
            .map_err(|err| RedDBError::Internal(err.to_string()))?;
        self.put_immutable(temp.path(), &manifest_key)?;
        Ok((
            GenerationPointer {
                manifest_key,
                data_key: data_key
                    .ok_or_else(|| RedDBError::Internal("generation has no data file".into()))?,
                wal_lsn: staged.cut.wal_lsn,
            },
            total,
        ))
    }

    fn put_immutable(&self, path: &Path, key: &str) -> RedDBResult<()> {
        self.metrics
            .put_requests_total
            .fetch_add(1, Ordering::Relaxed);
        self.backend
            .upload_if_absent(path, key)
            .map_err(|err| RedDBError::Internal(format!("upload {key}: {err}")))
    }

    /// Capture, upload, and make a generation current. Writers keep
    /// committing while the files upload; the head CAS fences a successor.
    pub(crate) fn publish_generation(&self, runtime: &RedDBRuntime) -> RedDBResult<()> {
        self.publish_generation_inner(runtime, false)
    }

    fn publish_generation_inner(
        &self,
        runtime: &RedDBRuntime,
        cancellable: bool,
    ) -> RedDBResult<()> {
        let _serial = self
            .generation_lock
            .lock()
            .expect("poisoned generation lock");
        let lifecycle = self
            .lease
            .get()
            .ok_or_else(|| RedDBError::ReadOnly("serverless archive has no writer lease".into()))?;
        let lease = lifecycle.held_lease_for_publication()?;
        let started = Instant::now();
        let sequence = self
            .publication
            .next_publication_sequence()
            .map_err(|err| RedDBError::ReadOnly(err.to_string()))?;
        let archived_before = self.metrics.bytes_uploaded_total.load(Ordering::Acquire);
        if self.tap.discontinuity().is_some() {
            // Frames the tap missed are only recoverable through a new
            // generation; hold segments until one is published.
            runtime
                .db()
                .store()
                .restart_wal_archive_after_discontinuity()
                .map_err(|err| RedDBError::Internal(format!("restart WAL archive: {err}")))?;
            // Segments sealed before the restart end below the skipped LSN.
            self.hold_from(self.tap.status().next_lsn.saturating_sub(1));
        }
        // Out-of-WAL writes that completed before staging are in its copy.
        let out_of_wal_at_stage = self.out_of_wal_writes.load(Ordering::Acquire);
        let result = self.stage_and_upload_generation(runtime, sequence, cancellable);
        let (pointer, bytes) = match result {
            Ok(value) => value,
            Err(err) => {
                self.metrics
                    .generation_errors_total
                    .fetch_add(1, Ordering::Relaxed);
                return Err(err);
            }
        };
        if !lifecycle.is_held() {
            self.metrics
                .generation_errors_total
                .fetch_add(1, Ordering::Relaxed);
            return Err(RedDBError::ReadOnly(
                "writer lease expired while the generation uploaded".into(),
            ));
        }
        self.metrics
            .put_requests_total
            .fetch_add(1, Ordering::Relaxed);
        match self.publication.publish_generation(&lease, &pointer) {
            Ok(previous) => {
                self.release_holds_through(out_of_wal_at_stage);
                self.metrics
                    .generations_published_total
                    .fetch_add(1, Ordering::Relaxed);
                self.metrics
                    .generation_wal_lsn
                    .store(pointer.wal_lsn, Ordering::Release);
                self.metrics
                    .last_generation_bytes
                    .store(bytes, Ordering::Release);
                self.metrics
                    .last_generation_duration_ms
                    .store(started.elapsed().as_millis() as u64, Ordering::Release);
                // WAL archived while this generation uploaded is not in it.
                let archived_during = self
                    .metrics
                    .bytes_uploaded_total
                    .load(Ordering::Acquire)
                    .saturating_sub(archived_before);
                self.metrics
                    .bytes_since_generation
                    .store(archived_during, Ordering::Release);
                *self
                    .last_generation_at
                    .lock()
                    .expect("poisoned generation clock") = Instant::now();
                tracing::info!(
                    target: "reddb::serverless::archive",
                    wal_lsn = pointer.wal_lsn,
                    bytes,
                    duration_ms = started.elapsed().as_millis() as u64,
                    manifest = %pointer.manifest_key,
                    "serverless generation published"
                );
                self.collect_garbage(&previous, lifecycle);
                Ok(())
            }
            Err(SnapshotPublicationError::Fenced(message)) => {
                self.metrics
                    .generation_errors_total
                    .fetch_add(1, Ordering::Relaxed);
                lifecycle.mark_publication_fenced(&message);
                Err(RedDBError::ReadOnly(format!(
                    "generation publication fenced by a newer writer: {message}"
                )))
            }
            Err(err) => {
                self.metrics
                    .generation_errors_total
                    .fetch_add(1, Ordering::Relaxed);
                Err(RedDBError::Internal(err.to_string()))
            }
        }
    }

    /// Delete generations older than the one just superseded and the WAL
    /// segments that only those older generations needed. The superseded
    /// generation stays as a fallback. Only strictly older objects are ever
    /// deleted, and only while this writer still holds the lease: a writer
    /// that stalled past its TTL must not delete a successor's generation.
    /// Best effort.
    fn collect_garbage(
        &self,
        previous: &reddb_file::ServerlessSnapshotHead,
        lease: &LeaseLifecycle,
    ) {
        let Some(previous_generation) = &previous.generation else {
            return;
        };
        let Some(previous_id) = generation_id_of(&previous_generation.manifest_key)
            .as_deref()
            .and_then(parse_generation_id)
        else {
            return;
        };
        let root = reddb_file::serverless_generations_root(&self.database_key);
        let generations = match self.backend.list(&root) {
            Ok(keys) => generation_gc_victims(keys, previous_id),
            Err(err) => {
                tracing::debug!(error = %err, "generation GC listing failed");
                Vec::new()
            }
        };
        let wal_root = reddb_file::serverless_wal_prefix(&self.database_key);
        let segments = match self.backend.list(&wal_root) {
            Ok(keys) => segment_gc_victims(keys, previous_generation.wal_lsn),
            Err(err) => {
                tracing::debug!(error = %err, "WAL segment GC listing failed");
                Vec::new()
            }
        };
        for key in generations.into_iter().chain(segments) {
            if !lease.is_held() {
                return;
            }
            let _ = self.backend.delete(&key);
        }
    }

    fn upload_segment(
        &self,
        segment: &crate::storage::unified::store::SealedWalSegment,
    ) -> Result<(), BackendError> {
        let key = reddb_file::serverless_wal_segment_key(
            &self.database_key,
            segment.epoch,
            segment.first_lsn,
            segment.last_lsn,
        );
        self.metrics
            .put_requests_total
            .fetch_add(1, Ordering::Relaxed);
        match self.backend.upload_if_absent(segment.file.path(), &key) {
            Ok(()) => Ok(()),
            Err(BackendError::PreconditionFailed(message)) => {
                // An earlier attempt may have landed before its response was
                // lost. Accept the key only if it holds these exact bytes.
                let remote =
                    download_bytes(self.backend.as_ref(), &key).map_err(BackendError::Transport)?;
                let remote_sha = remote
                    .as_deref()
                    .and_then(|bytes| reddb_file::decode_serverless_wal_segment(bytes).ok())
                    .map(|decoded| decoded.sha256);
                if remote_sha == Some(segment.sha256) {
                    Ok(())
                } else {
                    Err(BackendError::PreconditionFailed(format!(
                        "segment key {key} holds another writer's bytes: {message}"
                    )))
                }
            }
            Err(err) => Err(err),
        }
    }

    /// One archive step: capture new durable WAL, seal a due batch, upload
    /// sealed segments in order, and update lag accounting.
    fn archive_tick(&self, runtime: &RedDBRuntime, force_seal: bool) -> Result<(), String> {
        let _uploads = self.upload_lock.lock().expect("poisoned upload lock");
        let store = runtime.db().store();
        let mut result = Ok(());
        if let Err(err) = store.capture_wal_archive_frames() {
            result = Err(format!("capture: {err}"));
            if self.tap.discontinuity().is_some() {
                tracing::error!(
                    target: "reddb::serverless::archive",
                    error = %err,
                    "WAL archive stream is discontinuous; publishing a new generation"
                );
                self.request_generation();
            }
        }
        // Seal one tick early so the oldest frame is uploaded within the
        // window rather than up to one tick after it.
        let now = Instant::now() + self.tick();
        if let Err(err) = self.tap.seal_if_due(
            now,
            self.config.interval,
            self.config.max_segment_bytes,
            force_seal,
        ) {
            result = Err(format!("seal: {err}"));
        }
        let lease_held = self.lease.get().is_some_and(|lease| lease.is_held());
        if lease_held {
            loop {
                match self
                    .tap
                    .upload_front_below(self.upload_floor(), |segment| self.upload_segment(segment))
                {
                    Ok(Some((_, last, bytes))) => {
                        self.metrics
                            .last_archived_lsn
                            .store(last, Ordering::Release);
                        self.metrics
                            .segments_uploaded_total
                            .fetch_add(1, Ordering::Relaxed);
                        self.metrics
                            .bytes_uploaded_total
                            .fetch_add(bytes, Ordering::Relaxed);
                        self.metrics
                            .bytes_since_generation
                            .fetch_add(bytes, Ordering::Relaxed);
                    }
                    Ok(None) => break,
                    Err(err) => {
                        self.metrics
                            .upload_errors_total
                            .fetch_add(1, Ordering::Relaxed);
                        result = Err(format!("upload: {err}"));
                        break;
                    }
                }
            }
        }
        result
    }

    fn tick(&self) -> Duration {
        (self.config.interval / 5).clamp(Duration::from_millis(20), Duration::from_secs(1))
    }

    fn account_lag(&self, runtime: &RedDBRuntime) {
        let status = self.status();
        let now_ms = unix_ms_now();
        let gate = runtime.write_gate();
        if self.config.pause_on_lag_secs > 0 {
            gate.record_archive_success(now_ms.saturating_sub(status.lag.as_millis() as u64));
            gate.evaluate_archive_lag(now_ms);
        }
        let was_over = self.over_bound.swap(status.over_bound, Ordering::AcqRel);
        if status.over_bound && !was_over {
            self.metrics
                .lag_over_bound_total
                .fetch_add(1, Ordering::Relaxed);
            tracing::warn!(
                target: "reddb::serverless::archive",
                lag_ms = status.lag.as_millis() as u64,
                lag_bytes = status.lag_bytes,
                bound_ms = status.lag_bound.as_millis() as u64,
                "WAL archive lag exceeds the RPO bound"
            );
        } else if !status.over_bound && was_over {
            tracing::info!(
                target: "reddb::serverless::archive",
                "WAL archive lag back within the RPO bound"
            );
        }
    }

    fn generation_due(&self) -> bool {
        let since = self.metrics.bytes_since_generation.load(Ordering::Acquire);
        if since == 0 {
            return false;
        }
        if self.config.generation_wal_bytes > 0 && since >= self.config.generation_wal_bytes {
            return true;
        }
        !self.config.generation_interval.is_zero()
            && self
                .last_generation_at
                .lock()
                .expect("poisoned generation clock")
                .elapsed()
                >= self.config.generation_interval
    }

    fn request_generation(&self) {
        let (flag, wake) = &self.generation_request;
        *flag.lock().expect("poisoned generation request") = true;
        wake.notify_all();
    }

    pub(crate) fn spawn(self: &Arc<Self>, runtime: RedDBRuntime) {
        if self.config.pause_on_lag_secs > 0 {
            runtime
                .write_gate()
                .configure_archive_lag_pause(self.config.pause_on_lag_secs, unix_ms_now());
        }
        let mut threads = self.threads.lock().expect("poisoned archive threads");
        let archive = Arc::clone(self);
        let archiver_runtime = runtime.clone();
        if let Ok(handle) = std::thread::Builder::new()
            .name("red-wal-archive".into())
            .spawn(move || archive.run_archiver(archiver_runtime))
        {
            threads.push(handle);
        }
        // Lag is evaluated on its own ticker so the pause engages even
        // while an upload hangs inside the archiver thread.
        let archive = Arc::clone(self);
        let lag_runtime = runtime.clone();
        if let Ok(handle) = std::thread::Builder::new()
            .name("red-wal-archive-lag".into())
            .spawn(move || archive.run_lag_monitor(lag_runtime))
        {
            threads.push(handle);
        }
        let archive = Arc::clone(self);
        let handle = std::thread::Builder::new()
            .name("red-generation".into())
            .spawn(move || archive.run_generations(runtime))
            .ok();
        *self
            .generation_thread
            .lock()
            .expect("poisoned generation thread") = handle;
    }

    fn run_lag_monitor(&self, runtime: RedDBRuntime) {
        let tick = self.tick();
        while !self.stop.load(Ordering::Acquire)
            && runtime.lifecycle().phase() != crate::runtime::lifecycle::Phase::Stopped
        {
            self.account_lag(&runtime);
            std::thread::sleep(tick);
        }
    }

    fn run_archiver(&self, runtime: RedDBRuntime) {
        let tick = self.tick();
        let mut last_error_log: Option<Instant> = None;
        while !self.stop.load(Ordering::Acquire) {
            if runtime.lifecycle().phase() == crate::runtime::lifecycle::Phase::Stopped {
                break;
            }
            if let Err(err) = self.archive_tick(&runtime, false) {
                if last_error_log.is_none_or(|at| at.elapsed() >= Duration::from_secs(10)) {
                    tracing::warn!(
                        target: "reddb::serverless::archive",
                        error = %err,
                        "WAL archive tick failed; retrying"
                    );
                    last_error_log = Some(Instant::now());
                }
            }
            if self.generation_due() || self.out_of_wal_pending() {
                self.request_generation();
            }
            std::thread::sleep(tick);
        }
    }

    fn run_generations(&self, runtime: RedDBRuntime) {
        let (flag, wake) = &self.generation_request;
        loop {
            {
                let mut requested = flag.lock().expect("poisoned generation request");
                while !*requested && !self.stop.load(Ordering::Acquire) {
                    requested = wake
                        .wait_timeout(requested, Duration::from_secs(1))
                        .expect("poisoned generation request")
                        .0;
                }
                if self.stop.load(Ordering::Acquire) {
                    return;
                }
                *requested = false;
            }
            if !(self.out_of_wal_pending()
                || self.generation_due()
                || self.tap.discontinuity().is_some())
            {
                continue;
            }
            if let Err(err) = self.publish_generation_inner(&runtime, true) {
                if self.stop.load(Ordering::Acquire) {
                    return;
                }
                tracing::warn!(
                    target: "reddb::serverless::archive",
                    error = %err,
                    "periodic generation publication failed; retrying"
                );
                // Back off so a persistent failure does not checkpoint and
                // copy the store in a tight loop.
                let retry_at = Instant::now() + Duration::from_secs(5);
                while Instant::now() < retry_at && !self.stop.load(Ordering::Acquire) {
                    std::thread::sleep(Duration::from_millis(100));
                }
            }
        }
    }

    /// Stop the archiver and lag threads. The generation thread is only
    /// signalled; it cancels between files and is joined after the flush.
    fn stop_archiver_threads(&self) {
        self.stop.store(true, Ordering::Release);
        self.generation_request.1.notify_all();
        let threads = std::mem::take(&mut *self.threads.lock().expect("poisoned archive threads"));
        for handle in threads {
            let _ = handle.join();
        }
    }

    fn join_generation_thread(&self) {
        let handle = self
            .generation_thread
            .lock()
            .expect("poisoned generation thread")
            .take();
        if let Some(handle) = handle {
            let _ = handle.join();
        }
    }

    /// Graceful sleep/move: stop the background loops, seal and upload every
    /// captured frame, and verify the archive reached the captured end. Only
    /// then may the caller release the lease. A final generation is needed
    /// only when the flush failed, an out-of-WAL write is still uncovered, or
    /// the head has accumulated many writer claims since the last generation.
    pub(crate) fn flush_for_shutdown(&self, runtime: &RedDBRuntime) -> ShutdownFlush {
        self.stop_archiver_threads();
        let mut last_error = None;
        if let Err(err) = self.publish_if_out_of_wal_pending(runtime) {
            last_error = Some(err.to_string());
        }
        let mut archived = None;
        for attempt in 0..SHUTDOWN_FLUSH_ATTEMPTS {
            if let Err(err) = self.archive_tick(runtime, true) {
                last_error = Some(err);
            }
            let tap = self.tap.status();
            let last = self.metrics.last_archived_lsn.load(Ordering::Acquire);
            if tap.pending_frames == 0
                && tap.sealed_segments == 0
                && last >= tap.next_lsn.saturating_sub(1)
            {
                archived = Some(last);
                break;
            }
            std::thread::sleep(Duration::from_millis(100 * u64::from(attempt.min(10) + 1)));
        }
        self.join_generation_thread();
        let claims = self
            .publication
            .observed_head()
            .and_then(|head| head.generation)
            .map_or(0, |generation| generation.wal_epochs.len());
        ShutdownFlush {
            archived_lsn: archived,
            error: archived
                .is_none()
                .then(|| last_error.unwrap_or_else(|| "unarchived frames remain".into())),
            generation_needed: archived.is_none()
                || self.out_of_wal_pending()
                || claims > MAX_CLAIMS_WITHOUT_GENERATION,
        }
    }
}

/// Outcome of the shutdown flush.
#[derive(Debug)]
pub(crate) struct ShutdownFlush {
    pub archived_lsn: Option<u64>,
    pub error: Option<String>,
    pub generation_needed: bool,
}

/// Generation ids `<epoch>/<sequence>-<nonce>` strictly older than
/// `previous`. Newer ids (a successor's) and the previous one are kept.
fn generation_gc_victims(keys: Vec<String>, previous: (u64, u64)) -> Vec<String> {
    keys.into_iter()
        .filter(|key| {
            generation_id_of(key)
                .as_deref()
                .and_then(parse_generation_id)
                .is_some_and(|id| id < previous)
        })
        .collect()
}

/// Segments that end at or below the superseded generation's stream LSN.
fn segment_gc_victims(keys: Vec<String>, previous_wal_lsn: u64) -> Vec<String> {
    keys.into_iter()
        .filter(|key| {
            reddb_file::parse_serverless_wal_segment_key(key)
                .is_some_and(|(_, _, last)| last <= previous_wal_lsn)
        })
        .collect()
}

/// `(epoch, sequence)` of a generation id.
fn parse_generation_id(id: &str) -> Option<(u64, u64)> {
    let (epoch, rest) = id.split_once('/')?;
    let (sequence, _nonce) = rest.split_once('-')?;
    Some((epoch.parse().ok()?, sequence.parse().ok()?))
}

/// `<epoch>/<sequence>-<nonce>` of a generation object key.
fn generation_id_of(key: &str) -> Option<String> {
    const MARKER: &str = ".serverless/generations/";
    let rest = &key[key.rfind(MARKER)? + MARKER.len()..];
    let mut parts = rest.splitn(3, '/');
    let epoch = parts.next().filter(|part| !part.is_empty())?;
    let sequence = parts.next().filter(|part| !part.is_empty())?;
    parts.next()?;
    Some(format!("{epoch}/{sequence}"))
}

fn unix_ms_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

/// One file of a staged generation.
pub(crate) struct StagedGenerationFile {
    pub role: reddb_file::ServerlessGenerationFileRole,
    /// Path relative to the data file's directory, `/`-separated.
    pub relative_path: String,
    pub path: PathBuf,
}

/// A checkpoint-consistent local copy of the store, removed on drop.
pub(crate) struct StagedGeneration {
    pub files: Vec<StagedGenerationFile>,
    pub cut: crate::storage::unified::store::WalArchiveCut,
    dir: PathBuf,
}

impl Drop for StagedGeneration {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

fn staging_dir() -> std::io::Result<PathBuf> {
    static NEXT: AtomicU64 = AtomicU64::new(0);
    let dir = std::env::temp_dir().join(format!(
        "reddb-generation-{}-{}-{}",
        std::process::id(),
        unix_ms_now(),
        NEXT.fetch_add(1, Ordering::Relaxed)
    ));
    std::fs::create_dir_all(&dir)?;
    Ok(dir)
}

fn relative_slash_path(path: &Path) -> Result<String, String> {
    let mut parts = Vec::new();
    for component in path.components() {
        match component {
            std::path::Component::Normal(part) => parts.push(
                part.to_str()
                    .ok_or_else(|| format!("non UTF-8 path {}", path.display()))?
                    .to_string(),
            ),
            _ => return Err(format!("unexpected path component in {}", path.display())),
        }
    }
    Ok(parts.join("/"))
}

/// Files below the support or operational directory that are not needed to
/// reopen the store: logs, caches, temporaries, and locks.
fn skip_support_entry(name: &str, is_dir: bool, depth: usize) -> bool {
    if is_dir {
        return depth == 0 && matches!(name, "logs" | "cache");
    }
    name.ends_with(".tmp")
        || name.contains(".tmp.")
        || name.ends_with(".lock")
        || name.starts_with(reddb_file::layout::LEGACY_AUDIT_LOG_FILE_NAME)
}

impl RedDBRuntime {
    /// The serverless archive, when this runtime publishes generations.
    pub fn serverless_wal_archive(&self) -> Option<&Arc<ServerlessWalArchive>> {
        self.inner.serverless_wal_archive.get()
    }

    pub(crate) fn set_serverless_wal_archive(&self, archive: Arc<ServerlessWalArchive>) {
        let _ = self.inner.serverless_wal_archive.set(archive);
    }

    /// Stage a checkpoint-consistent copy of every file needed to reopen the
    /// store. Writers are excluded only while the files are copied locally.
    pub(crate) fn stage_serverless_generation(&self) -> RedDBResult<StagedGeneration> {
        let data_path = self
            .inner
            .db
            .path()
            .ok_or_else(|| {
                RedDBError::InvalidOperation("serverless generations need a local data path".into())
            })?
            .to_path_buf();
        let data_dir = data_path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."))
            .to_path_buf();
        let store = self.inner.db.store();
        let wal_path = store.commit_wal_path().ok_or_else(|| {
            RedDBError::InvalidOperation("serverless generations need the commit WAL".into())
        })?;
        let wal_relative = wal_path
            .strip_prefix(&data_dir)
            .map_err(|_| {
                RedDBError::InvalidOperation(format!(
                    "commit WAL {} is outside the data directory",
                    wal_path.display()
                ))
            })
            .and_then(|path| relative_slash_path(path).map_err(RedDBError::Internal))?;
        let data_relative = reddb_file::data_file_name(&data_path);
        let dir = staging_dir().map_err(|err| RedDBError::Internal(err.to_string()))?;
        let mut staged = StagedGeneration {
            files: Vec::new(),
            cut: crate::storage::unified::store::WalArchiveCut {
                wal_lsn: 0,
                prev_sha256: None,
            },
            dir: dir.clone(),
        };
        // A first checkpoint outside the publication lock lets writers commit
        // between its staged batches; the second one under the lock is short.
        self.checkpoint_local()?;
        let io = |err: std::io::Error| RedDBError::Internal(err.to_string());
        {
            let _publication = store.vault_publication_lock.lock();
            self.checkpoint_local()?;
            let data_target = dir.join(&data_relative);
            self.copy_main_data_file(&data_path, &data_target)?;
            staged.files.push(StagedGenerationFile {
                role: reddb_file::ServerlessGenerationFileRole::Data,
                relative_path: data_relative.clone(),
                path: data_target,
            });
            let support = reddb_file::support_dir_for(&data_path);
            let operational = data_dir.join(format!("{data_relative}.ops"));
            for (root, role) in [
                (support, reddb_file::ServerlessGenerationFileRole::Support),
                (
                    operational,
                    reddb_file::ServerlessGenerationFileRole::Operational,
                ),
            ] {
                if root.is_dir() {
                    copy_tree(
                        &root,
                        &data_dir,
                        &dir,
                        &wal_path,
                        role,
                        0,
                        &mut staged.files,
                    )
                    .map_err(RedDBError::Internal)?;
                }
            }
            for (path, role) in [
                (
                    reddb_file::physical_metadata_json_path(&data_path),
                    reddb_file::ServerlessGenerationFileRole::MetadataJson,
                ),
                (
                    reddb_file::physical_metadata_binary_path(&data_path),
                    reddb_file::ServerlessGenerationFileRole::MetadataBinary,
                ),
            ] {
                if path.is_file() {
                    let relative = path
                        .strip_prefix(&data_dir)
                        .map_err(|err| RedDBError::Internal(err.to_string()))
                        .and_then(|p| relative_slash_path(p).map_err(RedDBError::Internal))?;
                    let target = dir.join(&relative);
                    std::fs::copy(&path, &target).map_err(io)?;
                    staged.files.push(StagedGenerationFile {
                        role,
                        relative_path: relative,
                        path: target,
                    });
                }
            }
            let wal_target = dir.join(&wal_relative);
            if let Some(parent) = wal_target.parent() {
                std::fs::create_dir_all(parent).map_err(io)?;
            }
            staged.cut = store
                .cut_wal_archive_generation(&wal_target)
                .map_err(|err| RedDBError::Internal(format!("cut generation WAL: {err}")))?;
            staged.files.push(StagedGenerationFile {
                role: reddb_file::ServerlessGenerationFileRole::Wal,
                relative_path: wal_relative,
                path: wal_target,
            });
        }
        Ok(staged)
    }

    /// Copy the paged main file through the pager's own handle (Windows
    /// excludes reads through a second handle while the writer holds it).
    fn copy_main_data_file(&self, source: &Path, target: &Path) -> RedDBResult<()> {
        use reddb_file::VfsFile;
        let store = self.inner.db.store();
        if let Some(pager) = store.pager() {
            pager
                .with_file(|file| -> std::io::Result<()> {
                    let mut output = std::fs::File::create(target)?;
                    file.seek(std::io::SeekFrom::Start(0))?;
                    let mut buffer = vec![0u8; 1 << 20];
                    loop {
                        let count = file.read(&mut buffer)?;
                        if count == 0 {
                            break;
                        }
                        output.write_all(&buffer[..count])?;
                    }
                    output.sync_all()
                })
                .map_err(|err| RedDBError::Internal(err.to_string()))?
                .map_err(|err| RedDBError::Internal(err.to_string()))
        } else {
            std::fs::copy(source, target)
                .map(|_| ())
                .map_err(|err| RedDBError::Internal(err.to_string()))
        }
    }
}

fn copy_tree(
    source: &Path,
    data_dir: &Path,
    staging: &Path,
    wal_path: &Path,
    role: reddb_file::ServerlessGenerationFileRole,
    depth: usize,
    files: &mut Vec<StagedGenerationFile>,
) -> Result<(), String> {
    if depth >= 32 {
        return Err("support directory nesting exceeds limit".into());
    }
    for entry in std::fs::read_dir(source).map_err(|err| err.to_string())? {
        let entry = entry.map_err(|err| err.to_string())?;
        let kind = entry.file_type().map_err(|err| err.to_string())?;
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().to_string();
        if kind.is_symlink() {
            return Err(format!(
                "support directory entry {} is a symlink",
                path.display()
            ));
        }
        if skip_support_entry(&name, kind.is_dir(), depth) || path == wal_path {
            continue;
        }
        if kind.is_dir() {
            copy_tree(&path, data_dir, staging, wal_path, role, depth + 1, files)?;
            continue;
        }
        if !kind.is_file() {
            continue;
        }
        let relative = path
            .strip_prefix(data_dir)
            .map_err(|err| err.to_string())
            .and_then(relative_slash_path)?;
        let target = staging.join(&relative);
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent).map_err(|err| err.to_string())?;
        }
        std::fs::copy(&path, &target).map_err(|err| format!("copy {}: {err}", path.display()))?;
        files.push(StagedGenerationFile {
            role,
            relative_path: relative,
            path: target,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::backend::LocalBackend;

    struct Fixture {
        _root: tempfile::TempDir,
        database_key: String,
        head: reddb_file::ServerlessSnapshotHead,
        wal_header: Vec<u8>,
    }

    fn write(path: &str, bytes: &[u8]) {
        let path = Path::new(path);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, bytes).unwrap();
    }

    /// A generation whose WAL holds one frame (`gen`) and includes stream
    /// LSNs through `wal_lsn`, owned by `epochs`.
    fn fixture(wal_lsn: u64, epochs: &[(u64, u64)]) -> Fixture {
        let root = tempfile::tempdir().unwrap();
        let database_key = root
            .path()
            .join("remote/main.rdb")
            .to_string_lossy()
            .to_string();
        let prefix = reddb_file::serverless_generation_prefix(&database_key, 1, 1, "t");
        let wal_header = reddb_file::encode_wal_file_header().to_vec();
        let wal_name = reddb_file::unified_wal_path(Path::new("data.rdb"))
            .to_string_lossy()
            .to_string();
        let mut wal = wal_header.clone();
        wal.extend_from_slice(b"gen");
        let files = [
            (
                reddb_file::ServerlessGenerationFileRole::Data,
                "data.rdb",
                b"pages".to_vec(),
            ),
            (
                reddb_file::ServerlessGenerationFileRole::Wal,
                wal_name.as_str(),
                wal,
            ),
            (
                reddb_file::ServerlessGenerationFileRole::Support,
                "data.rdb.red/snapshots/v.tv",
                b"tv".to_vec(),
            ),
        ]
        .into_iter()
        .map(|(role, relative, bytes)| {
            let key = format!("{prefix}files/{relative}");
            write(&key, &bytes);
            reddb_file::ServerlessGenerationFile {
                role,
                relative_path: relative.to_string(),
                key,
                size: bytes.len() as u64,
                sha256: reddb_file::sha256_bytes_hex(&bytes),
            }
        })
        .collect();
        let manifest = reddb_file::ServerlessGenerationManifest {
            database_key: database_key.clone(),
            epoch: 1,
            sequence: 1,
            wal_lsn,
            wal_prev_sha256: None,
            created_at_ms: 1,
            files,
        };
        let manifest_key = reddb_file::serverless_generation_manifest_key(&prefix);
        write(
            &manifest_key,
            &reddb_file::encode_serverless_generation_manifest_json(&manifest).unwrap(),
        );
        let head = reddb_file::ServerlessSnapshotHead {
            database_key: database_key.clone(),
            holder_id: "w".into(),
            term: 1,
            lease_generation: 1,
            publication_sequence: 3,
            snapshot_key: String::new(),
            generation: Some(reddb_file::ServerlessGenerationRef {
                manifest_key,
                wal_lsn,
                wal_epochs: epochs
                    .iter()
                    .map(|(epoch, start_lsn)| reddb_file::ServerlessWalEpoch {
                        epoch: *epoch,
                        start_lsn: *start_lsn,
                    })
                    .collect(),
            }),
        };
        Fixture {
            _root: root,
            database_key,
            head,
            wal_header,
        }
    }

    /// Upload a segment whose frames are `f<lsn>`; returns its digest.
    fn segment(
        fixture: &Fixture,
        epoch: u64,
        first: u64,
        last: u64,
        prev: Option<[u8; 32]>,
    ) -> [u8; 32] {
        let mut payload = Vec::new();
        for lsn in first..=last {
            reddb_file::push_serverless_wal_segment_frame(
                &mut payload,
                format!("f{lsn}").as_bytes(),
            );
        }
        let (bytes, sha) = reddb_file::encode_serverless_wal_segment(
            &reddb_file::ServerlessWalSegmentHeader {
                wal_format_version: reddb_file::encode_wal_file_header()[4],
                epoch,
                first_lsn: first,
                last_lsn: last,
                prev_sha256: prev,
            },
            last - first + 1,
            &payload,
        )
        .unwrap();
        write(
            &reddb_file::serverless_wal_segment_key(&fixture.database_key, epoch, first, last),
            &bytes,
        );
        sha
    }

    fn restored_wal(fixture: &Fixture, stream: &RestoredStream) -> String {
        let bytes = std::fs::read(reddb_file::unified_wal_path(&stream.data_path)).unwrap();
        assert!(bytes.starts_with(&fixture.wal_header));
        String::from_utf8(bytes[fixture.wal_header.len()..].to_vec()).unwrap()
    }

    #[test]
    fn garbage_collection_never_deletes_newer_generations() {
        let key = |epoch: u64, sequence: u64, file: &str| {
            format!(
                "db/main.rdb.serverless/generations/{epoch:020}/{sequence:020}-n{sequence}/{file}"
            )
        };
        let keys = vec![
            key(1, 2, "MANIFEST.json"),
            key(1, 2, "files/data.rdb"),
            key(1, 5, "MANIFEST.json"),  // previous: kept
            key(1, 7, "MANIFEST.json"),  // this writer's current: kept
            key(9, 10, "MANIFEST.json"), // a successor's current: kept
            key(9, 10, "files/data.rdb"),
            "db/main.rdb.serverless/generations/garbage".to_string(),
        ];
        let victims = generation_gc_victims(keys, (1, 5));
        assert_eq!(
            victims,
            vec![key(1, 2, "MANIFEST.json"), key(1, 2, "files/data.rdb")]
        );

        let segment = |first: u64, last: u64| {
            reddb_file::serverless_wal_segment_key("db/main.rdb", 1, first, last)
        };
        let victims = segment_gc_victims(vec![segment(1, 4), segment(5, 9), segment(10, 12)], 9);
        assert_eq!(victims, vec![segment(1, 4), segment(5, 9)]);
        assert_eq!(
            parse_generation_id("00000000000000000003/00000000000000000011-ab"),
            Some((3, 11))
        );
    }

    #[test]
    fn generation_ids_match_relative_and_absolute_keys() {
        let relative = "db/main.rdb.serverless/generations/00000000000000000001/00000000000000000002-ab/MANIFEST.json";
        let absolute = "/var/root/db/main.rdb.serverless/generations/00000000000000000001/00000000000000000002-ab/files/data.rdb";
        assert_eq!(generation_id_of(relative), generation_id_of(absolute));
        assert!(generation_id_of(relative).is_some());
        assert_eq!(
            generation_id_of("db/main.rdb.serverless/generations/x"),
            None
        );
    }

    #[test]
    fn restore_replays_only_frames_after_the_generation_across_epochs() {
        let fixture = fixture(3, &[(1, 1), (4, 7)]);
        let s1 = segment(&fixture, 1, 1, 2, None);
        // Straddles the generation LSN: f3 is inside the generation already.
        let s2 = segment(&fixture, 1, 3, 4, Some(s1));
        let s3 = segment(&fixture, 1, 5, 6, Some(s2));
        // A stale writer kept uploading after epoch 4 claimed LSN 7.
        segment(&fixture, 1, 7, 9, Some(s3));
        let s5 = segment(&fixture, 4, 7, 8, Some(s3));
        let target = tempfile::tempdir().unwrap();
        let stream = restore_generation(&LocalBackend, &fixture.head, target.path()).unwrap();
        assert_eq!(restored_wal(&fixture, &stream), "genf4f5f6f7f8");
        assert_eq!(stream.last_lsn, 8);
        assert_eq!(stream.last_sha256, Some(s5));
        assert_eq!(
            std::fs::read(target.path().join("data.rdb.red/snapshots/v.tv")).unwrap(),
            b"tv"
        );
        // Same head into a populated directory refuses instead of doubling.
        assert!(restore_generation(&LocalBackend, &fixture.head, target.path()).is_err());
        // A fresh directory reproduces the exact bytes.
        let again = tempfile::tempdir().unwrap();
        let second = restore_generation(&LocalBackend, &fixture.head, again.path()).unwrap();
        assert_eq!(restored_wal(&fixture, &second), "genf4f5f6f7f8");
    }

    #[test]
    fn restore_fails_closed_on_gaps_corruption_and_broken_links() {
        let fx = fixture(0, &[(1, 1)]);
        let s1 = segment(&fx, 1, 1, 2, None);
        segment(&fx, 1, 5, 6, Some(s1));
        let err = restore_generation(&LocalBackend, &fx.head, tempfile::tempdir().unwrap().path())
            .expect_err("gap between 2 and 5");
        assert!(err.contains("gap"), "{err}");

        let fx = fixture(0, &[(1, 1)]);
        segment(&fx, 1, 1, 2, None);
        segment(&fx, 1, 3, 4, Some([9u8; 32]));
        let err = restore_generation(&LocalBackend, &fx.head, tempfile::tempdir().unwrap().path())
            .expect_err("chain mismatch");
        assert!(err.contains("link"), "{err}");

        let fx = fixture(0, &[(1, 1)]);
        segment(&fx, 1, 1, 2, None);
        let key = reddb_file::serverless_wal_segment_key(&fx.database_key, 1, 1, 2);
        let mut bytes = std::fs::read(&key).unwrap();
        let middle = bytes.len() / 2;
        bytes[middle] ^= 1;
        std::fs::write(&key, bytes).unwrap();
        let err = restore_generation(&LocalBackend, &fx.head, tempfile::tempdir().unwrap().path())
            .expect_err("corruption");
        assert!(err.contains("checksum"), "{err}");

        // An old epoch that stops before its successor's start is a gap too.
        let fx = fixture(0, &[(1, 1), (2, 5)]);
        let s1 = segment(&fx, 1, 1, 2, None);
        segment(&fx, 2, 5, 6, Some(s1));
        let err = restore_generation(&LocalBackend, &fx.head, tempfile::tempdir().unwrap().path())
            .expect_err("epoch 1 ends at 2, epoch 2 starts at 5");
        assert!(err.contains("gap"), "{err}");

        // A tampered generation file is refused.
        let fx = fixture(0, &[(1, 1)]);
        let generation = fx.head.generation.as_ref().unwrap();
        let data_key = generation
            .manifest_key
            .replace("MANIFEST.json", "files/data.rdb");
        std::fs::write(&data_key, b"PAGES").unwrap();
        let err = restore_generation(&LocalBackend, &fx.head, tempfile::tempdir().unwrap().path())
            .expect_err("data file checksum");
        assert!(err.contains("checksum"), "{err}");
    }
}