armdb 0.15.3

sharded bitcask key-value storage optimized for NVMe
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
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
//! Seal, maintenance and the worker thread.

use std::cmp::Reverse;
use std::collections::{BinaryHeap, VecDeque};
use std::hash::Hash;
use std::ops::Bound;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Weak};
use std::time::{Duration, Instant};

use super::core::{SegCore, View};
use super::generation::Generation;
use super::hash::{key_hash, shard_range};
use super::manifest::{self, PublishError, SegRecord};
use super::seal::{SegTimes, SegmentWriter, sdat_name, sidx_name};
use super::segment::Segment;
use super::sidecar::{OrderKind, SegHeader};
use crate::error::{DbError, DbResult};
use crate::key::Key;
use crate::map_index::Dir;
use crate::sync;

const IDLE_PAUSE: Duration = Duration::from_secs(1);
/// How long one round may keep starting skeleton builds. The worker comes
/// back at once while work remains, so seals interleave at this pace.
const SKELETON_PASS_BUDGET: Duration = Duration::from_millis(250);
const MIN_BACKOFF: Duration = Duration::from_secs(1);
const MAX_BACKOFF: Duration = Duration::from_secs(60);
const WAIT_SLICE: Duration = Duration::from_millis(20);
/// Entries a seal writes between two looks at the shutdown flag.
const SHUTDOWN_CHECK_EVERY: usize = 1024;

/// A snapshot of what the worker is doing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SealStatus {
    /// Generations that wait for a seal.
    pub frozen: usize,
    /// Generation being sealed right now.
    pub in_flight: Option<u64>,
    /// Why the last attempt failed. Cleared by a success.
    pub last_error: Option<String>,
    /// Collection-clock timestamp of the next automatic retry.
    pub retry_at_ms: Option<u64>,
    /// Collection-clock timestamp of the last successful seal.
    pub last_sealed_at_ms: Option<u64>,
    /// Why the collection refuses writes, when it does.
    pub fenced: Option<String>,
}

impl<K: Key + Hash + Eq + Send + Sync + 'static> SegCore<K> {
    /// Seal the oldest frozen generation. `Ok(false)` when none is frozen.
    #[cfg(test)]
    pub(crate) fn seal_oldest(&self) -> DbResult<bool> {
        self.seal_oldest_with_retry(None)
    }

    /// Record automatic retry status before releasing attempt serialization.
    fn seal_oldest_with_retry(&self, retry_delay: Option<Duration>) -> DbResult<bool> {
        let _attempt = sync::lock(&self.seal_attempt);
        let started = Instant::now();
        let result = self.seal_oldest_inner();
        {
            let mut state = sync::lock(&self.seal);
            state.in_flight = None;
            match &result {
                Ok(true) => {
                    state.last_error = None;
                    state.retry_at_ms = None;
                    state.last_sealed_at_ms = Some(self.now_ms());
                    metrics::histogram!("armdb.seg.seal_seconds", "collection" => self.meta.name)
                        .record(started.elapsed().as_secs_f64());
                }
                Ok(false) => {}
                // A shutdown abort is not a failure: the frozen input stays
                // for the next open, and no retry will ever happen.
                Err(_) if self.shut_down.load(Ordering::Acquire) => {}
                Err(e) => {
                    state.last_error = Some(e.to_string());
                    state.failures += 1;
                    if !matches!(e, DbError::CollectionFenced { .. })
                        && let Some(delay) = retry_delay
                    {
                        // A manual success cannot clear the error before this
                        // retry is recorded: both hold the attempt mutex.
                        state.retry_at_ms =
                            Some(self.now_ms().saturating_add(
                                u64::try_from(delay.as_millis()).unwrap_or(u64::MAX),
                            ));
                    }
                    metrics::counter!("armdb.seg.seal_failures", "collection" => self.meta.name)
                        .increment(1);
                }
            }
        }
        self.seal_cv.notify_all();
        result
    }

    fn check_seal_shutdown(&self) -> DbResult<()> {
        if self.shut_down.load(Ordering::Acquire) {
            return Err(DbError::Internal("the seal was aborted by a shutdown"));
        }
        Ok(())
    }

    fn seal_oldest_inner(&self) -> DbResult<bool> {
        // Step 0 and step 2, under the manifest mutex.
        let (generation, segment_id, nothing_below) = {
            let mut manifest = sync::lock(&self.manifest);
            self.check_writable()?;
            self.check_seal_shutdown()?;
            let Some(rec) = manifest.oldest_frozen().copied() else {
                return Ok(false);
            };
            let view = self.view();
            let generation = view
                .frozen
                .last()
                .cloned()
                .filter(|g| g.id() == rec.gen_id)
                .ok_or(DbError::Internal(
                    "the view and the manifest disagree on the oldest frozen generation",
                ))?;
            let (reserved, segment_id) = manifest.reserve_segment_id()?;
            self.publish_next(&mut manifest, reserved)?;
            (generation, segment_id, manifest.segments.is_empty())
        };
        sync::lock(&self.seal).in_flight = Some(generation.id());

        // Step 1.
        generation.durable_flush()?;

        // Steps 3 and 4.
        let header = SegHeader {
            segment_id,
            version: 1,
            order: self.order,
            key_len: self.key_len(),
            seed: self.seed,
            block_size: self.config.block_size,
        };
        let record = self.write_segment(&generation, header, nothing_below)?;

        // Open the reader before the manifest names the segment, so that a
        // named segment is always a readable one.
        let segment = match &record {
            Some(rec) => match Segment::open(
                self.fs.clone(),
                &self.seg_root,
                rec,
                self.key_len(),
                self.seed,
                &self.shared,
            ) {
                Ok(segment) => Some(Arc::new(segment)),
                Err(e) => {
                    // `finish` already renamed both files into place, so the
                    // writer's `Drop` no longer covers them. A failed step
                    // removes its output (the spec's seal failure table).
                    self.discard_segment_files(rec);
                    return Err(e);
                }
            },
            None => None,
        };

        // Step 5.
        let mut manifest = sync::lock(&self.manifest);
        let discard = |segment: &Option<Arc<Segment>>| {
            if let Some(segment) = segment {
                segment.mark_doomed();
            }
        };
        if let Err(e) = self
            .check_writable()
            .and_then(|()| self.check_seal_shutdown())
        {
            discard(&segment);
            return Err(e);
        }
        // A frozen generation is empty only when a crash lost its whole
        // unflushed tail; it has nothing to mask and leaves without a segment.
        let transition = if record.is_none() && generation.keys() == 0 {
            manifest.with_empty_sealed(generation.id())
        } else {
            manifest.with_sealed(generation.id(), record)
        };
        let next = match transition {
            Ok(next) => next,
            Err(e) => {
                discard(&segment);
                return Err(e);
            }
        };
        match manifest::publish(&*self.fs, &self.dir, &next) {
            Ok(()) => {
                *manifest = next;
                super::failpoint!(SEAL_PUBLISHED);
            }
            Err(PublishError::NotPublished(e)) => {
                discard(&segment);
                return Err(e);
            }
            Err(PublishError::Indeterminate(e)) => {
                // The disk may already name the segment. It stays, and so
                // does the generation.
                return Err(self.fence(format!(
                    "the outcome of the seal of generation {:#x} is unknown: {e}",
                    generation.id()
                )));
            }
        }

        // Step 6.
        let view = self.view();
        let mut frozen = view.frozen.clone();
        frozen.pop();
        let mut sealed = Vec::with_capacity(view.sealed.len() + 1);
        sealed.extend(segment);
        sealed.extend(view.sealed.iter().cloned());
        let costs: Vec<_> = sealed.iter().map(|s| s.cost()).collect();
        let hot = super::residency::assign(&costs, self.config.resident_metadata_bytes);
        for segment in sealed.iter_mut().skip(hot) {
            if segment.is_hot() {
                *segment = Arc::new(segment.cooled());
            }
        }
        self.set_view(View {
            active: view.active.clone(),
            frozen,
            sealed,
        });
        drop(manifest);

        // Step 7: the directory goes when the last reader releases it.
        generation.doom();
        Ok(true)
    }

    /// Remove the final files of a segment no manifest names. Best effort:
    /// a leftover is garbage the next open removes, so a failure is logged,
    /// not returned.
    fn discard_segment_files(&self, rec: &SegRecord) {
        for name in [
            sdat_name(rec.segment_id, rec.version),
            sidx_name(rec.segment_id, rec.version),
        ] {
            if let Err(e) = self.fs.remove_file(&self.seg_root.join(&name)) {
                tracing::warn!(collection = self.meta.name, file = %name, error = %e, "cannot remove an unnamed segment file");
            }
        }
        if let Err(e) = self.fs.sync_dir(&self.seg_root) {
            tracing::warn!(collection = self.meta.name, error = %e, "cannot sync seg/ after removing an unnamed segment");
        }
    }

    /// Write the files of a segment. `None` when the generation left nothing
    /// worth one.
    fn write_segment(
        &self,
        generation: &Arc<Generation<K>>,
        header: SegHeader,
        nothing_below: bool,
    ) -> DbResult<Option<SegRecord>> {
        // The exact entry count of the frozen generation: its index length,
        // tombstones included, fixed because a frozen generation takes no
        // write. It bounds what is pushed below (tombstones may be skipped),
        // and the writer sizes the filter partitions and the seal scratch
        // memory from it. An underestimate puts the whole segment into one
        // oversized partition; never pass an estimate or 0.
        let mut writer = if self.order == OrderKind::ByKey {
            SegmentWriter::create_key(
                self.fs.clone(),
                &self.seg_root,
                header,
                &self.prefix_filters,
                generation.keys(),
            )?
        } else {
            SegmentWriter::create(self.fs.clone(), &self.seg_root, header, generation.keys())?
        };
        let shards = generation.shard_count();
        if self.order == OrderKind::ByKey {
            // One bounded copied batch per shard; journal IO never holds an index guard.
            const BATCH: usize = 256;
            let mut batches: Vec<VecDeque<_>> = Vec::with_capacity(shards);
            for shard in 0..shards {
                self.check_seal_shutdown()?;
                batches.push(
                    generation
                        .ordered_batch(shard, Bound::Unbounded, Bound::Unbounded, Dir::Asc, BATCH)
                        .into(),
                );
            }
            let mut heap = BinaryHeap::new();
            for (shard, batch) in batches.iter().enumerate() {
                if let Some((key, _)) = batch.front() {
                    heap.push(Reverse((key.as_bytes().to_vec(), shard)));
                }
            }
            let mut consumed = 0usize;
            while let Some(Reverse((_, shard))) = heap.pop() {
                if consumed.is_multiple_of(SHUTDOWN_CHECK_EVERY) {
                    self.check_seal_shutdown()?;
                }
                consumed += 1;
                let (key, loc) = batches[shard].pop_front().expect("heap head has an entry");
                let h = key_hash(key.as_bytes(), self.seed);
                if !(loc.tombstone && nothing_below) {
                    writer.push(h, &generation.read_entry(h, &loc.loc)?)?;
                }
                if batches[shard].is_empty() {
                    batches[shard] = generation
                        .ordered_batch(
                            shard,
                            Bound::Excluded(&key),
                            Bound::Unbounded,
                            Dir::Asc,
                            BATCH,
                        )
                        .into();
                }
                if let Some((key, _)) = batches[shard].front() {
                    heap.push(Reverse((key.as_bytes().to_vec(), shard)));
                }
            }
        } else {
            for shard in 0..shards {
                // Dropping the writer removes what it wrote.
                self.check_seal_shutdown()?;
                let (lo, hi) = shard_range(shard, shards);
                for (n, (h, _key, loc)) in generation
                    .snapshot_range(lo, hi, self.seed)
                    .into_iter()
                    .enumerate()
                {
                    // A shutdown aborts the seal promptly: one shard of a cold
                    // journal can take minutes of random reads.
                    if n % SHUTDOWN_CHECK_EVERY == SHUTDOWN_CHECK_EVERY - 1 {
                        self.check_seal_shutdown()?;
                    }
                    // A tombstone with nothing below it masks nothing.
                    if loc.tombstone && nothing_below {
                        continue;
                    }
                    let entry = generation.read_entry(h, &loc.loc)?;
                    writer.push(h, &entry)?;
                }
            }
        }
        if writer.entries() == 0 {
            return Ok(None);
        }
        // Before the fsyncs and renames that would only be thrown away.
        self.check_seal_shutdown()?;
        let times = SegTimes {
            opened_at_ms: generation.opened_at_ms(),
            frozen_at_ms: generation.frozen_at_ms(),
            // The manifest requires `opened_at <= frozen_at`, and a clock that
            // went back must not date the seal before the freeze either.
            sealed_at_ms: self.now_ms().max(generation.frozen_at_ms()),
        };
        let files = writer.finish(times, self.meta.value_version, self.meta.typ_hash)?;
        metrics::counter!("armdb.seg.seal_bytes", "collection" => self.meta.name)
            .increment(files.sdat_len + files.sidx_len);
        Ok(Some(files.into_record()))
    }

    /// Block until no generation is frozen. `Ok(false)` when some still are
    /// at the timeout, or at once after a shutdown, which stops sealing.
    pub(crate) fn wait_sealed(&self, timeout: Duration) -> DbResult<bool> {
        let deadline = Instant::now()
            .checked_add(timeout)
            .ok_or(DbError::Client("seal timeout exceeds the clock range"))?;
        loop {
            self.check_writable()?;
            let state = sync::lock(&self.seal);
            if self.view().frozen.is_empty() && state.in_flight.is_none() {
                return Ok(true);
            }
            let now = Instant::now();
            if now >= deadline || self.shut_down.load(Ordering::Acquire) {
                return Ok(false);
            }
            drop(sync::cv_wait_timeout(
                &self.seal_cv,
                &self.seal,
                state,
                WAIT_SLICE.min(deadline - now),
            ));
        }
    }

    /// Snapshot the last attempt and the current queue and fence.
    pub(crate) fn seal_status(&self) -> SealStatus {
        let state = sync::lock(&self.seal).clone();
        SealStatus {
            frozen: self.view().frozen.len(),
            in_flight: state.in_flight,
            last_error: state.last_error,
            retry_at_ms: state.retry_at_ms,
            last_sealed_at_ms: state.last_sealed_at_ms,
            fenced: self.fence_reason(),
        }
    }
}

impl<K: Key + Hash + Eq + Send + Sync + 'static> SegCore<K> {
    /// Freeze the active generation when it is full, or old and `aged` is
    /// asked for. Postponed when the seal queue has no free slot.
    fn freeze_if_due(&self, now_ms: u64, aged: bool) -> DbResult<()> {
        let view = self.view();
        let active = &view.active;
        if active.keys() == 0 {
            return Ok(());
        }
        let max_age_ms = u64::try_from(self.config.seal_max_age.as_millis()).unwrap_or(u64::MAX);
        let old = aged && now_ms.saturating_sub(active.opened_at_ms()) >= max_age_ms;
        if !active.is_full() && !old {
            return Ok(());
        }
        let mut manifest = sync::lock(&self.manifest);
        if !Arc::ptr_eq(&self.view().active, active)
            || manifest.frozen_count() >= self.config.max_frozen_generations
        {
            return Ok(());
        }
        self.freeze_locked(&mut manifest)
    }

    /// One round of maintenance; `Ok(true)` when skeleton work remains.
    #[cfg(test)]
    pub(crate) fn tick(&self) -> DbResult<bool> {
        let (result, more) = self.round();
        result.map(|()| more)
    }

    /// One round of maintenance. A full generation is frozen at once; age
    /// and retention are evaluated once per `maintenance_interval`. Also
    /// returns whether skeleton work remains, whatever the result.
    fn round(&self) -> (DbResult<()>, bool) {
        if self.shut_down.load(Ordering::Acquire) || self.fence_reason().is_some() {
            return (Ok(()), false);
        }
        let now_ms = self.now_ms();
        let interval_ms =
            u64::try_from(self.config.maintenance_interval.as_millis()).unwrap_or(u64::MAX);
        let last = self.last_tick_ms.load(Ordering::Acquire);
        // A clock that went back makes maintenance due instead of stopping
        // it until the clock catches up with the last tick.
        let due = last == 0 || now_ms < last || now_ms - last >= interval_ms;
        if due {
            self.last_tick_ms.store(now_ms.max(1), Ordering::Release);
        }
        // Each step runs whatever the others did: a freeze failing for lack
        // of space must not keep retention from freeing some.
        let flushed = self.flush_frozen();
        let frozen = self.freeze_if_due(now_ms, due);
        let retained = if due { self.maintain(now_ms) } else { Ok(()) };
        let (skeleton, more) = self.build_pending_skeletons(SKELETON_PASS_BUDGET);
        self.publish_gauges();
        (flushed.and(frozen).and(retained).and(skeleton), more)
    }

    /// Derive pending skeletons one at a time, newest first, starting builds
    /// until none is pending or `budget` has passed; the first always runs.
    /// Returns the first error and whether a pending skeleton remains.
    ///
    /// A failed build has its own retry deadline and is skipped until then,
    /// so older pending layers keep progressing. Each snapshot owns file
    /// handles but holds no view/manifest publication lock during I/O.
    pub(crate) fn build_pending_skeletons(&self, budget: Duration) -> (DbResult<()>, bool) {
        let started = Instant::now();
        let mut result = Ok(());
        let mut built = 0usize;
        loop {
            if self.shut_down.load(Ordering::Acquire) || self.fence_reason().is_some() {
                return (result, false);
            }
            let now = super::skeleton::now_ms();
            let Some(segment) = self
                .view()
                .sealed
                .iter()
                .find(|s| s.files.skeleton.is_pending(now))
                .cloned()
            else {
                return (result, false);
            };
            if built > 0 && started.elapsed() >= budget {
                return (result, true);
            }
            if let Err(e) = segment.skeleton_background()
                && result.is_ok()
            {
                result = Err(e);
            }
            built += 1;
        }
    }

    /// Make the tails of frozen generations durable. A frozen generation
    /// takes no more writes, so no sync policy of its journal ever flushes
    /// it, and its own seal may wait behind older ones for a long time.
    /// Once flushed it is clean and costs nothing on later ticks.
    fn flush_frozen(&self) -> DbResult<()> {
        let view = self.view();
        let mut first = None;
        for generation in view.frozen.iter().rev() {
            if generation.dirty_shards() == 0 {
                continue;
            }
            if let Err(e) = generation.durable_flush()
                && first.is_none()
            {
                first = Some(e);
            }
        }
        first.map_or(Ok(()), Err)
    }

    /// Drop the oldest segment when `due` says so. `Ok(false)` when there is
    /// no segment or it is not due.
    fn drop_oldest_if(&self, due: impl Fn(&SegRecord) -> bool) -> DbResult<bool> {
        let mut manifest = sync::lock(&self.manifest);
        self.check_writable()?;
        let Some(oldest) = manifest.segments.first() else {
            return Ok(false);
        };
        if !due(oldest) {
            return Ok(false);
        }
        let (segment_id, frozen_at_ms) = (oldest.segment_id, oldest.frozen_at_ms);
        let view = self.view();
        let mut sealed = view.sealed.clone();
        let dropped = sealed
            .pop()
            .filter(|s| s.id() == segment_id)
            .ok_or(DbError::Internal(
                "the view and the manifest disagree on the oldest segment",
            ))?;
        let next = manifest.without_oldest_segment()?;
        self.publish_next(&mut manifest, next)?;
        super::failpoint!(DROP_PUBLISHED);
        // The files go when the last reader releases the segment.
        dropped.mark_doomed();
        self.set_view(View {
            active: view.active.clone(),
            frozen: view.frozen.clone(),
            sealed,
        });
        drop(manifest);

        tracing::warn!(
            collection = self.meta.name,
            segment_id,
            frozen_at_ms,
            "segment dropped"
        );
        metrics::counter!("armdb.seg.retention_drops", "collection" => self.meta.name).increment(1);
        Ok(true)
    }

    /// Drop the longest prefix of oldest segments frozen before `ts_ms`.
    /// Segments go one publication at a time: on an error, those dropped
    /// before it stay dropped, and `segments()` shows what is left.
    pub(crate) fn drop_segments_before(&self, ts_ms: u64) -> DbResult<usize> {
        let mut dropped = 0;
        while self.drop_oldest_if(|rec| rec.frozen_at_ms < ts_ms)? {
            dropped += 1;
        }
        Ok(dropped)
    }

    /// Retention. At most one segment per tick: retention depends on the
    /// wall clock, and a clock that jumped forward must not take the whole
    /// window at once.
    fn maintain(&self, now_ms: u64) -> DbResult<()> {
        let Some(retention) = self.config.retention else {
            return Ok(());
        };
        let retention_ms = u64::try_from(retention.as_millis()).unwrap_or(u64::MAX);
        self.drop_oldest_if(|rec| now_ms.saturating_sub(rec.frozen_at_ms) >= retention_ms)?;
        Ok(())
    }

    /// Start the background worker, which holds the core only while working.
    pub(crate) fn start_worker(self: &Arc<Self>) -> DbResult<()> {
        #[cfg(any(test, feature = "test-faults"))]
        if super::failpoints::worker_paused() {
            return Ok(());
        }
        let mut worker = sync::lock(&self.worker);
        if worker.is_some() {
            return Ok(());
        }
        let weak = Arc::downgrade(self);
        let signal = self.signal.clone();
        let handle = std::thread::Builder::new()
            .name(format!("armdb-seg-{}", self.meta.name))
            .spawn(move || worker_loop(weak, signal))?;
        *worker = Some(handle);
        Ok(())
    }

    /// Whether a worker thread was started, is not stopped and has not
    /// ended, by a panic for instance.
    pub(crate) fn worker_running(&self) -> bool {
        sync::lock(&self.worker)
            .as_ref()
            .is_some_and(|handle| !handle.is_finished())
    }

    /// Request abort under manifest serialization, then join without locks.
    /// A running seal discards its unnamed output and keeps its frozen input.
    pub(crate) fn stop_worker(&self) {
        {
            let _manifest = sync::lock(&self.manifest);
            self.shut_down.store(true, Ordering::Release);
        }
        self.signal.stop();
        let handle = sync::lock(&self.worker).take();
        if let Some(handle) = handle
            && handle.thread().id() != std::thread::current().id()
        {
            let _ = handle.join();
        }
    }
}

/// How long the worker sleeps after a round: not at all while it is busy
/// (a seal succeeded or skeleton work remains), else `IDLE_PAUSE`; never past
/// the retry of a failed seal.
fn round_pause(busy: bool, retry_not_before: Option<Instant>, now: Instant) -> Duration {
    let pause = if busy { Duration::ZERO } else { IDLE_PAUSE };
    retry_not_before.map_or(pause, |at| pause.min(at.saturating_duration_since(now)))
}

fn worker_loop<K: Key + Hash + Eq + Send + Sync + 'static>(
    weak: Weak<SegCore<K>>,
    signal: Arc<super::core::WorkerSignal>,
) {
    let mut backoff = MIN_BACKOFF;
    // After a failed seal, not before this: a wake (every freeze, every
    // crossed threshold) ends a sleep early, but must not end the backoff.
    let mut retry_not_before: Option<Instant> = None;
    loop {
        // The collection is held only while there is work. Asleep, the
        // thread holds the signal alone, so the collection can be dropped.
        let pause = {
            let Some(core) = weak.upgrade() else { return };
            let mut sealed_one = false;
            let backing_off = retry_not_before.is_some_and(|at| Instant::now() < at);
            // A fenced collection seals nothing until it is reopened; an
            // attempt would only fail again every second.
            if !backing_off && core.fence_reason().is_none() {
                match core.seal_oldest_with_retry(Some(backoff)) {
                    Ok(sealed) => {
                        backoff = MIN_BACKOFF;
                        retry_not_before = None;
                        sealed_one = sealed;
                    }
                    Err(_) if core.shut_down.load(Ordering::Acquire) => {}
                    Err(DbError::CollectionFenced { .. }) => {}
                    Err(e) => {
                        tracing::warn!(collection = core.meta.name, error = %e, retry_in = ?backoff, "seal failed");
                        retry_not_before = Instant::now().checked_add(backoff);
                        backoff = (backoff * 2).min(MAX_BACKOFF);
                    }
                }
            }
            let (result, skeletons_remain) = core.round();
            if let Err(e) = result {
                tracing::warn!(collection = core.meta.name, error = %e, "maintenance failed");
            }
            round_pause(
                sealed_one || skeletons_remain,
                retry_not_before,
                Instant::now(),
            )
        };
        if signal.wait(pause) {
            return;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::DbError;
    use crate::seg::config::SegConfig;
    use crate::seg::fs::{FsOpKind, TraceFs};
    use crate::seg::manifest::{MANIFEST_NAME, load};
    use crate::seg::testkit::{
        TestClock, fill_core as fill, key_of, open_core, open_core_with_worker, try_open_core,
        value,
    };
    use std::time::Duration;

    #[test]
    fn the_worker_builds_pending_skeletons_newest_first() {
        let dir = tempfile::tempdir().unwrap();
        crate::seg::testkit::build_legacy_collection(dir.path(), 3);
        let mut config = roomy();
        config.resident_metadata_bytes = Some(0);
        let core = open_core(dir.path(), config);
        // The worker cannot race initial pending/order assertions: it starts
        // only after this scheduling barrier (manual tick exercises its round).
        assert_eq!(core.stats().skeletons_pending, 3);
        let view = core.view();
        // One round derives every pending skeleton back to back.
        assert!(!core.tick().unwrap(), "no skeleton work remains");
        assert_eq!(core.stats().skeletons_pending, 0);
        assert!(Arc::ptr_eq(&view, &core.view()), "no view publication");
        assert_eq!(*sync::lock(&core.shared.built), vec![3, 2, 1]);
        assert_eq!(core.stats().skeleton_builds_foreground, 0);
        assert_eq!(core.stats().hot_segments, 0);

        // Exercise the thread too. Initial pending assertions precede start,
        // which is a deterministic scheduling barrier rather than a sleep.
        let threaded_dir = tempfile::tempdir().unwrap();
        crate::seg::testkit::build_legacy_collection(threaded_dir.path(), 3);
        let mut config = roomy();
        config.resident_metadata_bytes = Some(0);
        let threaded = open_core(threaded_dir.path(), config);
        assert_eq!(threaded.stats().skeletons_pending, 3);
        threaded.start_worker().unwrap();
        let deadline = Instant::now() + Duration::from_secs(10);
        while threaded.stats().skeletons_pending != 0 && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        threaded.stop_worker();
        assert_eq!(threaded.stats().skeletons_pending, 0);
        assert_eq!(*sync::lock(&threaded.shared.built), vec![3, 2, 1]);
    }

    #[test]
    fn a_skeleton_pass_stops_at_its_budget_and_reports_remaining_work() {
        let dir = tempfile::tempdir().unwrap();
        crate::seg::testkit::build_legacy_collection(dir.path(), 3);
        let mut config = roomy();
        config.resident_metadata_bytes = Some(0);
        let core = open_core(dir.path(), config);
        // A spent budget still lets a pass build one skeleton, newest first.
        for (built, remains) in [(vec![3], true), (vec![3, 2], true), (vec![3, 2, 1], false)] {
            let (result, more) = core.build_pending_skeletons(Duration::ZERO);
            result.unwrap();
            assert_eq!(more, remains);
            assert_eq!(*sync::lock(&core.shared.built), built);
        }
        let (result, more) = core.build_pending_skeletons(Duration::ZERO);
        result.unwrap();
        assert!(!more);
        assert_eq!(core.stats().skeleton_builds_foreground, 0);
    }

    #[test]
    fn a_skeleton_pass_skips_failed_builds_and_returns_the_first_error() {
        let dir = tempfile::tempdir().unwrap();
        crate::seg::testkit::build_legacy_collection(dir.path(), 4);
        let mut config = roomy();
        config.resident_metadata_bytes = Some(0);
        let core = open_core(dir.path(), config);
        for segment in [&core.view().sealed[1], &core.view().sealed[2]] {
            std::fs::OpenOptions::new()
                .write(true)
                .open(dir.path().join("seg").join(sidx_name(
                    segment.record().segment_id,
                    segment.record().version,
                )))
                .unwrap()
                .set_len(0)
                .unwrap();
        }
        let (result, more) = core.build_pending_skeletons(Duration::from_secs(60));
        assert!(result.is_err());
        assert!(!more, "failed builds wait for their backoff");
        assert_eq!(*sync::lock(&core.shared.built), vec![4, 1]);
        assert_eq!(core.stats().skeleton_build_failures, 2);
    }

    #[test]
    fn the_worker_does_not_sleep_while_work_remains() {
        let now = Instant::now();
        assert_eq!(round_pause(true, None, now), Duration::ZERO);
        assert_eq!(round_pause(false, None, now), IDLE_PAUSE);
        let soon = now + Duration::from_millis(300);
        assert_eq!(
            round_pause(false, Some(soon), now),
            Duration::from_millis(300)
        );
        assert_eq!(round_pause(true, Some(soon), now), Duration::ZERO);
        assert_eq!(
            round_pause(false, Some(now), now + Duration::from_secs(5)),
            Duration::ZERO
        );
    }

    #[test]
    fn a_failing_skeleton_does_not_block_others() {
        let dir = tempfile::tempdir().unwrap();
        crate::seg::testkit::build_legacy_collection(dir.path(), 3);
        let mut config = roomy();
        config.resident_metadata_bytes = Some(0);
        let core = open_core(dir.path(), config);
        let middle = core.view().sealed[1].clone();
        std::fs::OpenOptions::new()
            .write(true)
            .open(dir.path().join("seg").join(sidx_name(
                middle.record().segment_id,
                middle.record().version,
            )))
            .unwrap()
            .set_len(0)
            .unwrap();
        // The pass builds past the failure; the failed one waits for its backoff.
        assert!(core.tick().is_err());
        assert_eq!(core.stats().skeletons_pending, 1, "Failed is not ready");
        assert_eq!(core.stats().skeleton_build_failures, 1);
        assert!(!core.tick().unwrap(), "backoff hides the failed build");
        assert_eq!(core.stats().skeleton_build_failures, 1);
        assert_eq!(*sync::lock(&core.shared.built), vec![3, 1]);
        for segment in [&core.view().sealed[0], &core.view().sealed[2]] {
            let id = segment.record().segment_id;
            let key = key_of(id);
            assert_eq!(
                segment
                    .lookup(key_hash(&key, crate::seg::testkit::SEED), &key, &core.cache)
                    .unwrap(),
                crate::seg::segment::Lookup::Live(crate::seg::testkit::value_of(id))
            );
        }
        assert_eq!(
            core.get(&key_of(3)).unwrap(),
            Some(crate::seg::testkit::value_of(3))
        );
        assert!(matches!(core.get(&key_of(2)), Err(DbError::Io(_))));
        assert!(
            matches!(core.get(&key_of(1)), Err(DbError::Io(_))),
            "newer failed layer is never absence"
        );
        assert_eq!(
            core.stats().skeleton_build_failures,
            1,
            "backoff avoids repeated builds"
        );
    }

    #[test]
    fn shutdown_stops_background_skeleton_work_but_readers_can_build() {
        let dir = tempfile::tempdir().unwrap();
        crate::seg::testkit::build_legacy_collection(dir.path(), 1);
        let mut config = roomy();
        config.resident_metadata_bytes = Some(0);
        let core = open_core(dir.path(), config);
        core.stop_worker();
        core.tick().unwrap();
        assert_eq!(core.stats().skeletons_pending, 1);
        assert_eq!(
            core.get(&key_of(1)).unwrap(),
            Some(crate::seg::testkit::value_of(1))
        );
        assert_eq!(core.stats().skeletons_pending, 0);
        assert_eq!(core.stats().skeleton_builds_foreground, 1);
    }

    // Stop deterministically inside output I/O, including the last shard and
    // finish, without requiring sleeps or a production-only test hook.
    struct ShutdownFs {
        inner: Arc<dyn crate::seg::fs::SegFs>,
        core: std::sync::Mutex<Option<Weak<SegCore<crate::seg::testkit::TestKey>>>>,
        point: &'static str,
        gates: Option<(Arc<std::sync::Barrier>, Arc<std::sync::Barrier>)>,
        writes: std::sync::atomic::AtomicUsize,
        /// Whether a segment data file got its final name.
        sdat_named: std::sync::atomic::AtomicBool,
    }

    impl ShutdownFs {
        fn stop_at(&self, point: &str, path: &std::path::Path) {
            if self.point == point && path.to_string_lossy().ends_with(".sdat.tmp") {
                let weak = self.core.lock().unwrap().take();
                if let Some(core) = weak.and_then(|core| core.upgrade()) {
                    if let Some((entered, release)) = &self.gates {
                        entered.wait();
                        release.wait();
                    } else {
                        core.stop_worker();
                    }
                }
            }
        }
    }

    impl crate::seg::fs::SegFs for ShutdownFs {
        fn create(&self, path: &std::path::Path) -> std::io::Result<std::fs::File> {
            self.inner.create(path)
        }
        fn create_new(&self, path: &std::path::Path) -> std::io::Result<std::fs::File> {
            self.inner.create_new(path)
        }
        fn write_all(
            &self,
            out: &mut dyn std::io::Write,
            path: &std::path::Path,
            bytes: &[u8],
        ) -> std::io::Result<()> {
            if path.to_string_lossy().ends_with(".sdat.tmp")
                && self.writes.fetch_add(1, Ordering::Relaxed) == 1
            {
                self.stop_at("last_shard", path);
            }
            self.inner.write_all(out, path, bytes)
        }
        fn sync_file(&self, file: &std::fs::File, path: &std::path::Path) -> std::io::Result<()> {
            self.stop_at("finish", path);
            self.inner.sync_file(file, path)
        }
        fn rename(&self, from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> {
            if to.to_string_lossy().ends_with(".sdat") {
                self.sdat_named.store(true, Ordering::Relaxed);
            }
            self.inner.rename(from, to)
        }
        fn sync_dir(&self, dir: &std::path::Path) -> std::io::Result<()> {
            self.inner.sync_dir(dir)
        }
        fn create_dir_all(&self, dir: &std::path::Path) -> std::io::Result<()> {
            self.inner.create_dir_all(dir)
        }
        fn remove_file(&self, path: &std::path::Path) -> std::io::Result<()> {
            self.inner.remove_file(path)
        }
        fn remove_dir_all(&self, dir: &std::path::Path) -> std::io::Result<()> {
            self.inner.remove_dir_all(dir)
        }
    }

    fn roomy() -> SegConfig {
        SegConfig {
            seal_max_keys: 1_000_000,
            max_frozen_generations: 64,
            ..SegConfig::test()
        }
    }

    #[test]
    fn by_key_seal_merges_bounded_shard_batches_and_reopens() {
        use crate::seg::testkit::{TestClock, open_raw_tree_core, raw_ordered_key};
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1000);
        let core = open_raw_tree_core(dir.path(), roomy(), clock.clone(), &[4, 8]);
        // More than one batch in every shard; insert opposite byte order.
        for n in (0..3000).rev() {
            core.put(&raw_ordered_key(n), b"tree").unwrap();
        }
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        assert!(core.verify_all().unwrap().is_clean());
        let view = core.view();
        assert_eq!(view.sealed[0].record().order, OrderKind::ByKey);
        let mut keys = Vec::new();
        for b in 0..view.sealed[0].block_count().unwrap() {
            let payload = view.sealed[0].block_payload(b, None).unwrap();
            for entry in crate::seg::block::EntryIter::new(&payload, 32) {
                keys.push(entry.unwrap().key.to_vec());
            }
        }
        assert_eq!(keys.len(), 3000);
        assert!(keys.windows(2).all(|w| w[0] < w[1]));
        drop(view);
        drop(core);
        // Changed declaration reads older prefix sections without false negatives.
        let core = open_raw_tree_core(dir.path(), roomy(), clock, &[16]);
        for n in 0..3000 {
            assert_eq!(
                core.get(&raw_ordered_key(n)).unwrap(),
                Some(b"tree".to_vec())
            );
        }
    }

    #[test]
    fn sealing_turns_a_generation_into_a_segment() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        fill(&core, 0..300);
        core.put(&key_of(5), b"newer").unwrap();
        core.seal().unwrap();
        assert!(core.seal_oldest().unwrap());
        assert!(!core.seal_oldest().unwrap(), "nothing is left to seal");

        let view = core.view();
        assert!(view.frozen.is_empty());
        assert_eq!(view.sealed.len(), 1);
        assert_eq!(view.sealed[0].record().entries, 300);
        assert_eq!(view.sealed[0].record().min_gsn, 1);
        assert_eq!(view.sealed[0].record().max_gsn, 301);
        assert_eq!(view.sealed[0].props().typ_hash, 0xcafe);
        assert_eq!(view.sealed[0].props().value_version, 3);
        drop(view);

        assert!(!dir.path().join("gen/0000000000000001").exists());
        assert_eq!(core.get(&key_of(5)).unwrap(), Some(b"newer".to_vec()));
        for i in 6..300 {
            assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)));
        }
        assert_eq!(core.len(), 300);

        let manifest = load(dir.path()).unwrap().unwrap();
        assert_eq!(manifest.generations.len(), 1);
        assert_eq!(manifest.segments.len(), 1);
        assert_eq!(manifest.segments[0].segment_id, 1);
        assert_eq!(manifest.next_segment_id, 2);
        assert_eq!(manifest.gsn_floor, 301);
    }

    #[test]
    fn tombstones_are_dropped_only_when_nothing_is_below() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        fill(&core, 0..100);
        core.delete(&key_of(1)).unwrap();
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        // The first segment has nothing below it.
        assert_eq!(core.view().sealed[0].record().tombstones, 0);
        assert_eq!(core.view().sealed[0].record().entries, 99);

        core.delete(&key_of(2)).unwrap();
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        let view = core.view();
        assert_eq!(
            view.sealed[0].record().tombstones,
            1,
            "it masks the first segment"
        );
        assert_eq!(core.get(&key_of(1)).unwrap(), None);
        assert_eq!(core.get(&key_of(2)).unwrap(), None);
        assert_eq!(core.get(&key_of(3)).unwrap(), Some(value(3)));
    }

    #[test]
    fn a_generation_that_leaves_nothing_leaves_no_segment() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        core.delete(&key_of(1)).unwrap();
        core.delete(&key_of(2)).unwrap();
        core.seal().unwrap();
        assert!(core.seal_oldest().unwrap());

        let view = core.view();
        assert!(view.frozen.is_empty() && view.sealed.is_empty());
        let manifest = load(dir.path()).unwrap().unwrap();
        assert!(manifest.segments.is_empty());
        assert_eq!(manifest.gsn_floor, 2);
        assert_eq!(
            std::fs::read_dir(dir.path().join("seg")).unwrap().count(),
            0
        );
    }

    #[test]
    fn generations_are_sealed_oldest_first() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        fill(&core, 0..10);
        core.seal().unwrap();
        fill(&core, 10..20);
        core.seal().unwrap();
        assert_eq!(core.view().frozen.len(), 2);

        core.seal_oldest().unwrap();
        let view = core.view();
        assert_eq!(view.frozen.len(), 1);
        assert_eq!(view.frozen[0].id(), 2, "generation 1 went first");
        assert_eq!(view.sealed[0].record().max_gsn, 10);
    }

    #[test]
    fn a_failing_seal_blocks_the_generations_behind_it() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        fill(&core, 0..10);
        core.seal().unwrap();
        fill(&core, 10..20);
        core.seal().unwrap();

        fs.fail_on(FsOpKind::CreateNew, ".sdat.tmp", 0);
        assert!(core.seal_oldest().is_err());
        let view = core.view();
        assert_eq!(view.frozen.len(), 2);
        assert!(view.sealed.is_empty());
        let status = core.seal_status();
        assert_eq!(status.frozen, 2);
        assert!(status.last_error.is_some());
        assert_eq!(status.in_flight, None);

        // The retry takes generation 1 again, under a fresh segment id.
        assert!(core.seal_oldest().unwrap());
        assert_eq!(core.view().frozen[0].id(), 2);
        assert_eq!(core.view().sealed[0].id(), 2);
        assert!(core.seal_status().last_error.is_none());
    }

    #[test]
    fn a_reader_keeps_its_layers_across_a_seal() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        fill(&core, 0..50);
        core.seal().unwrap();
        let held = core.view();
        let generation_dir = held.frozen[0].dir().to_path_buf();

        core.seal_oldest().unwrap();
        assert!(
            generation_dir.exists(),
            "a reader still holds the generation"
        );
        let key = key_of(7);
        let h = crate::seg::hash::key_hash(&key, core.seed);
        assert!(matches!(
            held.frozen[0].lookup(h, &key).unwrap(),
            crate::seg::generation::GenLookup::Live(_)
        ));

        drop(held);
        assert!(!generation_dir.exists());
    }

    #[test]
    fn a_seal_that_was_not_published_leaves_no_file() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        fill(&core, 0..50);
        core.seal().unwrap();

        // The first publication reserves the segment id, the second names it.
        fs.fail_on(FsOpKind::Rename, MANIFEST_NAME, 1);
        assert!(core.seal_oldest().is_err());
        assert_eq!(
            std::fs::read_dir(dir.path().join("seg")).unwrap().count(),
            0
        );
        assert_eq!(core.view().frozen.len(), 1);
        assert!(dir.path().join("gen/0000000000000001").exists());
        core.check_writable().unwrap();

        assert!(core.seal_oldest().unwrap());
        assert_eq!(core.view().sealed[0].id(), 2);
    }

    #[test]
    fn an_unknown_outcome_at_seal_fences_and_keeps_everything() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        fill(&core, 0..50);
        core.seal().unwrap();

        // Directory syncs of a seal: the reservation, `seg/`, the seal itself.
        fs.fail_on(FsOpKind::SyncDir, "", 2);
        assert!(matches!(
            core.seal_oldest(),
            Err(DbError::CollectionFenced { .. })
        ));
        assert_eq!(
            std::fs::read_dir(dir.path().join("seg")).unwrap().count(),
            2
        );
        assert!(dir.path().join("gen/0000000000000001").exists());
        assert!(core.seal_status().fenced.is_some());
        for i in 0..50 {
            assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)));
        }

        drop(core);
        let core = open_core(dir.path(), roomy());
        assert_eq!(core.view().sealed.len(), 1);
        for i in 0..50 {
            assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)));
        }
    }

    #[test]
    fn a_seal_makes_room_for_writers() {
        let dir = tempfile::tempdir().unwrap();
        let config = SegConfig {
            seal_max_keys: 5,
            max_frozen_generations: 1,
            seal_wait_timeout: Duration::from_millis(50),
            ..SegConfig::test()
        };
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), config, fs.clone(), &TestClock::new(1)).unwrap();
        fill(&core, 0..10);
        assert!(matches!(
            core.put(&key_of(10), b"v"),
            Err(DbError::SealBackpressure { .. })
        ));

        // The seal keeps failing: memory stays bounded, nothing is half done.
        for i in 10..13 {
            fs.fail_on(FsOpKind::CreateNew, ".sdat.tmp", 0);
            assert!(core.seal_oldest().is_err());
            assert!(matches!(
                core.put(&key_of(i), b"v"),
                Err(DbError::SealBackpressure { .. })
            ));
            assert_eq!(core.get(&key_of(i)).unwrap(), None);
            assert_eq!(core.view().active.keys(), 5);
            assert_eq!(core.view().frozen.len(), 1);
        }

        assert!(core.seal_oldest().unwrap());
        core.put(&key_of(10), b"v").unwrap();
        assert_eq!(core.get(&key_of(10)).unwrap(), Some(b"v".to_vec()));
    }

    #[test]
    fn the_segment_is_durable_before_the_manifest_names_it() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        fill(&core, 0..50);
        core.seal().unwrap();
        fs.clear();
        core.seal_oldest().unwrap();

        let ops = fs.ops();
        let publications: Vec<usize> = ops
            .iter()
            .enumerate()
            .filter(|(_, op)| op.kind() == FsOpKind::Rename && op.target().ends_with(MANIFEST_NAME))
            .map(|(i, _)| i)
            .collect();
        assert_eq!(publications.len(), 2);
        let first_file = fs.position(FsOpKind::CreateNew, ".sdat.tmp").unwrap();
        let seg_dir = ops
            .iter()
            .position(|op| op.kind() == FsOpKind::SyncDir && op.target().ends_with("seg"))
            .unwrap();
        assert!(publications[0] < first_file, "the id is reserved first");
        assert!(
            seg_dir < publications[1],
            "the files are durable before they are named"
        );
    }

    #[test]
    fn an_aged_generation_is_frozen_by_the_tick() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1_000_000);
        let config = SegConfig {
            seal_max_age: Duration::from_secs(3600),
            maintenance_interval: Duration::from_secs(60),
            ..roomy()
        };
        let core = try_open_core(dir.path(), config, crate::seg::fs::real(), &clock).unwrap();

        clock.advance(2 * 3600 * 1000);
        core.tick().unwrap();
        assert!(
            core.view().frozen.is_empty(),
            "an empty generation is never frozen"
        );

        core.put(&key_of(1), b"v").unwrap();
        core.tick().unwrap();
        assert!(core.view().frozen.is_empty(), "the interval has not passed");

        clock.advance(61_000);
        core.tick().unwrap();
        assert_eq!(core.view().frozen.len(), 1);
    }

    #[test]
    fn the_worker_seals_in_the_background() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core_with_worker(dir.path(), roomy());
        fill(&core, 0..500);
        core.seal().unwrap();
        assert!(core.wait_sealed(Duration::from_secs(20)).unwrap());

        let status = core.seal_status();
        assert_eq!(status.frozen, 0);
        assert!(status.last_sealed_at_ms.is_some());
        assert_eq!(core.view().sealed.len(), 1);
        for i in 0..500 {
            assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)));
        }
    }

    #[test]
    fn a_dropped_collection_can_be_opened_again_at_once() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core_with_worker(dir.path(), roomy());
        fill(&core, 0..10);
        drop(core);
        let core = open_core_with_worker(dir.path(), roomy());
        assert_eq!(core.get(&key_of(3)).unwrap(), Some(value(3)));
    }

    #[test]
    fn waiting_for_a_seal_that_never_comes_times_out() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        fill(&core, 0..10);
        core.seal().unwrap();
        assert!(!core.wait_sealed(Duration::from_millis(50)).unwrap());
    }
    /// `output_named`: whether the abort may come only after the segment
    /// files got their final names (a shutdown inside `finish`).
    fn assert_shutdown_aborts(point: &'static str, output_named: bool) {
        let dir = tempfile::tempdir().unwrap();
        let fs = Arc::new(ShutdownFs {
            inner: crate::seg::fs::real(),
            core: std::sync::Mutex::new(None),
            point,
            gates: None,
            writes: std::sync::atomic::AtomicUsize::new(0),
            sdat_named: std::sync::atomic::AtomicBool::new(false),
        });
        let config = SegConfig {
            shard_count: 1,
            ..roomy()
        };
        let core =
            try_open_core(dir.path(), config.clone(), fs.clone(), &TestClock::new(1)).unwrap();
        fill(&core, 0..3000);
        core.seal().unwrap();
        *fs.core.lock().unwrap() = Some(Arc::downgrade(&core));
        assert!(core.seal_oldest().is_err());
        assert!(fs.core.lock().unwrap().is_none(), "shutdown hook ran");
        assert!(core.shut_down.load(Ordering::Acquire));
        assert_eq!(
            fs.sdat_named.load(Ordering::Relaxed),
            output_named,
            "a shutdown before finish aborts before any fsync or rename"
        );
        assert_eq!(core.view().frozen.len(), 1);
        assert!(core.view().sealed.is_empty());
        assert!(load(dir.path()).unwrap().unwrap().segments.is_empty());
        assert_eq!(
            std::fs::read_dir(dir.path().join("seg")).unwrap().count(),
            0
        );
        assert!(dir.path().join("gen/0000000000000001").exists());
        // Writes still fit in the current active generation after shutdown.
        core.put(&key_of(4000), b"after-stop").unwrap();
        assert_eq!(
            core.get(&key_of(4000)).unwrap(),
            Some(b"after-stop".to_vec())
        );
        drop(core);
        let core = open_core(dir.path(), config);
        assert_eq!(core.get(&key_of(2999)).unwrap(), Some(value(2999)));
        assert_eq!(
            core.get(&key_of(4000)).unwrap(),
            Some(b"after-stop".to_vec())
        );
        assert!(core.seal_oldest().unwrap());
    }

    #[test]
    fn shutdown_during_the_final_shard_preserves_the_frozen_input() {
        assert_shutdown_aborts("last_shard", false);
    }

    #[test]
    fn shutdown_during_finish_discards_only_unnamed_output() {
        assert_shutdown_aborts("finish", true);
    }
    #[test]
    fn overlapping_seal_attempts_reserve_and_publish_only_once() {
        let dir = tempfile::tempdir().unwrap();
        let entered = Arc::new(std::sync::Barrier::new(2));
        let release = Arc::new(std::sync::Barrier::new(2));
        let fs = Arc::new(ShutdownFs {
            inner: crate::seg::fs::real(),
            core: std::sync::Mutex::new(None),
            point: "finish",
            gates: Some((entered.clone(), release.clone())),
            writes: std::sync::atomic::AtomicUsize::new(0),
            sdat_named: std::sync::atomic::AtomicBool::new(false),
        });
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        fill(&core, 0..50);
        core.seal().unwrap();
        *fs.core.lock().unwrap() = Some(Arc::downgrade(&core));
        let first = core.clone();
        let first = std::thread::spawn(move || first.seal_oldest());
        entered.wait();
        let attempt_held = sync::try_lock(&core.seal_attempt).is_none();
        // The manifest itself is free while segment output is being written.
        let manifest_free = sync::try_lock(&core.manifest).is_some();
        let second = core.clone();
        let second = std::thread::spawn(move || second.seal_oldest());
        release.wait();
        assert!(first.join().unwrap().unwrap());
        let second_result = second.join().unwrap();
        assert!(attempt_held, "attempt spans output I/O");
        assert!(manifest_free);
        assert!(!second_result.unwrap());
        assert_eq!(core.view().sealed.len(), 1);
        let manifest = load(dir.path()).unwrap().unwrap();
        assert_eq!(manifest.next_segment_id, 2);
        assert_eq!(manifest.segments.len(), 1);
    }

    /// Three segments, frozen at 1000, 2000 and 3000. Segment 1 holds keys
    /// 0..10; segment 2 overwrites key 1 and deletes key 2; segment 3 holds
    /// keys 20..30.
    fn three_segments(
        dir: &std::path::Path,
        clock: &TestClock,
        retention: Option<Duration>,
    ) -> std::sync::Arc<SegCore<crate::seg::testkit::TestKey>> {
        let config = SegConfig {
            retention,
            maintenance_interval: Duration::from_secs(1),
            seal_max_age: Duration::from_secs(1_000_000),
            ..roomy()
        };
        let core = try_open_core(dir, config, crate::seg::fs::real(), clock).unwrap();
        clock.set(1_000);
        fill(&core, 0..10);
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        clock.set(2_000);
        core.put(&key_of(1), b"newer").unwrap();
        core.delete(&key_of(2)).unwrap();
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        clock.set(3_000);
        fill(&core, 20..30);
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        assert_eq!(core.view().sealed.len(), 3);
        core
    }

    fn sealed_ids(core: &SegCore<crate::seg::testkit::TestKey>) -> Vec<u64> {
        core.view().sealed.iter().map(|s| s.id()).collect()
    }

    #[test]
    fn a_segment_leaves_when_its_retention_has_passed() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = three_segments(dir.path(), &clock, Some(Duration::from_secs(10)));

        clock.set(10_999);
        core.tick().unwrap();
        assert_eq!(
            sealed_ids(&core),
            [3, 2, 1],
            "10 s have not passed since 1000"
        );

        clock.set(13_000);
        core.tick().unwrap();
        assert_eq!(
            sealed_ids(&core),
            [3, 2],
            "one segment per tick, the oldest first"
        );
        assert!(!dir.path().join("seg").join(sdat_name(1, 1)).exists());
        assert!(!dir.path().join("seg").join(sidx_name(1, 1)).exists());

        clock.advance(1_000);
        core.tick().unwrap();
        assert_eq!(sealed_ids(&core), [3]);
        clock.advance(1_000);
        core.tick().unwrap();
        assert!(sealed_ids(&core).is_empty());

        let manifest = load(dir.path()).unwrap().unwrap();
        assert!(manifest.segments.is_empty());
        assert_eq!(manifest.next_segment_id, 4, "ids are never reused");
        assert_eq!(manifest.gsn_floor, 22, "the floor never goes down");
    }

    #[test]
    fn dropping_the_oldest_segment_uncovers_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = three_segments(dir.path(), &clock, None);
        assert_eq!(core.get(&key_of(1)).unwrap(), Some(b"newer".to_vec()));
        assert_eq!(core.get(&key_of(2)).unwrap(), None);
        assert_eq!(core.get(&key_of(3)).unwrap(), Some(value(3)));

        assert_eq!(core.drop_segments_before(1_001).unwrap(), 1);
        assert_eq!(core.get(&key_of(1)).unwrap(), Some(b"newer".to_vec()));
        assert_eq!(core.get(&key_of(2)).unwrap(), None);
        assert_eq!(
            core.get(&key_of(3)).unwrap(),
            None,
            "it lived in segment 1 only"
        );
        assert_eq!(core.get(&key_of(25)).unwrap(), Some(value(25)));
    }

    #[test]
    fn segments_are_dropped_as_a_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = three_segments(dir.path(), &clock, None);
        assert_eq!(core.drop_segments_before(1_000).unwrap(), 0);
        assert_eq!(core.drop_segments_before(2_500).unwrap(), 2);
        assert_eq!(sealed_ids(&core), [3]);
        assert_eq!(core.drop_segments_before(u64::MAX).unwrap(), 1);
        assert_eq!(core.drop_segments_before(u64::MAX).unwrap(), 0);
    }

    #[test]
    fn without_a_retention_nothing_is_dropped() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = three_segments(dir.path(), &clock, None);
        clock.set(u64::MAX / 2);
        core.tick().unwrap();
        assert_eq!(sealed_ids(&core), [3, 2, 1]);
    }

    #[test]
    fn generations_are_never_dropped_by_retention() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = three_segments(dir.path(), &clock, None);
        fill(&core, 40..50);
        core.seal().unwrap();
        fill(&core, 50..60);
        assert_eq!(core.drop_segments_before(u64::MAX).unwrap(), 3);
        assert_eq!(core.view().frozen.len(), 1);
        assert_eq!(core.get(&key_of(45)).unwrap(), Some(value(45)));
        assert_eq!(core.get(&key_of(55)).unwrap(), Some(value(55)));
    }

    #[test]
    fn a_reader_keeps_a_dropped_segment_until_it_is_done() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = three_segments(dir.path(), &clock, None);
        let held = core.view();
        let oldest = held.sealed.last().unwrap().clone();
        assert_eq!(oldest.id(), 1);

        core.drop_segments_before(1_001).unwrap();
        assert!(
            oldest.sdat_path().exists(),
            "a reader still holds the segment"
        );
        let key = key_of(3);
        let h = crate::seg::hash::key_hash(&key, core.seed);
        assert!(matches!(
            oldest.lookup(h, &key, &core.cache).unwrap(),
            crate::seg::segment::Lookup::Live(_)
        ));

        let path = oldest.sdat_path().to_path_buf();
        drop(oldest);
        drop(held);
        assert!(!path.exists());
    }

    #[test]
    fn a_drop_that_was_not_published_is_tried_again() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let fs = TraceFs::new();
        let config = SegConfig {
            retention: Some(Duration::from_secs(1)),
            maintenance_interval: Duration::from_secs(1),
            ..roomy()
        };
        let core = try_open_core(dir.path(), config, fs.clone(), &clock).unwrap();
        clock.set(1_000);
        fill(&core, 0..10);
        core.seal().unwrap();
        core.seal_oldest().unwrap();

        clock.set(10_000);
        fs.fail_on(FsOpKind::Rename, MANIFEST_NAME, 0);
        assert!(core.tick().is_err());
        assert_eq!(sealed_ids(&core), [1]);
        assert!(dir.path().join("seg").join(sdat_name(1, 1)).exists());
        core.check_writable().unwrap();

        clock.advance(1_000);
        core.tick().unwrap();
        assert!(sealed_ids(&core).is_empty());
    }

    #[test]
    fn a_fenced_collection_drops_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = three_segments(dir.path(), &clock, Some(Duration::from_secs(1)));
        core.fence("test".into());
        assert!(matches!(
            core.drop_segments_before(u64::MAX),
            Err(DbError::CollectionFenced { .. })
        ));
        clock.set(1_000_000);
        core.tick().unwrap();
        assert_eq!(sealed_ids(&core), [3, 2, 1]);
    }

    #[test]
    fn an_indeterminate_retention_drop_fences_and_preserves_the_old_view() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &clock).unwrap();
        clock.set(1_000);
        fill(&core, 0..10);
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        let held = core.view();
        let oldest = &held.sealed[0];
        let data = oldest.sdat_path().to_path_buf();
        let index = dir.path().join("seg").join(sidx_name(1, 1));

        fs.clear();
        // Retention publishes one manifest; fail its directory fsync after rename.
        fs.fail_on(FsOpKind::SyncDir, "", 0);
        let error = core.drop_segments_before(1_001).unwrap_err();
        assert!(matches!(error, DbError::CollectionFenced { .. }));
        assert!(error.to_string().contains("injected fault at SyncDir"));
        let ops = fs.ops();
        assert!(
            ops.iter()
                .any(|op| op.kind() == FsOpKind::Rename && op.target().ends_with(MANIFEST_NAME))
        );
        assert!(
            !ops.iter().any(|op| op.kind() == FsOpKind::SyncDir),
            "failed fsync is not recorded as successful"
        );
        assert!(
            load(dir.path()).unwrap().unwrap().segments.is_empty(),
            "rename made the new manifest visible"
        );
        assert_eq!(sealed_ids(&core), [1], "old View stays published");
        assert!(matches!(
            core.put(&key_of(99), b"fenced"),
            Err(DbError::CollectionFenced { .. })
        ));
        assert!(matches!(
            core.delete(&key_of(3)),
            Err(DbError::CollectionFenced { .. })
        ));
        let key = key_of(3);
        let h = crate::seg::hash::key_hash(&key, core.seed);
        assert!(matches!(
            oldest.lookup(h, &key, &core.cache).unwrap(),
            crate::seg::segment::Lookup::Live(_)
        ));
        assert_eq!(core.get(&key).unwrap(), Some(value(3)));
        assert!(data.exists() && index.exists());
        drop(held);
        drop(core);
        assert!(
            data.exists() && index.exists(),
            "indeterminate drop never dooms files"
        );

        let reopened = open_core(dir.path(), roomy());
        assert!(reopened.view().sealed.is_empty());
        assert_eq!(reopened.get(&key).unwrap(), None);
        assert!(
            !data.exists() && !index.exists(),
            "recovery removes unnamed segment files"
        );
        reopened.put(&key_of(99), b"after-reopen").unwrap();
        assert_eq!(
            reopened.get(&key_of(99)).unwrap(),
            Some(b"after-reopen".to_vec())
        );
    }

    #[test]
    fn a_retention_longer_than_the_clock_range_never_wraps() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let retention = Duration::from_secs((u64::MAX / 1_000) + 1);
        let core = three_segments(dir.path(), &clock, Some(retention));
        clock.set(13_000);
        core.tick().unwrap();
        assert_eq!(sealed_ids(&core), [3, 2, 1]);
        clock.set(u64::MAX);
        core.tick().unwrap();
        assert_eq!(sealed_ids(&core), [3, 2, 1]);
    }

    #[test]
    fn an_automatic_failure_records_retry_before_a_manual_success() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1_000);
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &clock).unwrap();
        fill(&core, 0..10);
        core.seal().unwrap();
        fs.fail_on(FsOpKind::CreateNew, ".sdat.tmp", 0);
        assert!(core.seal_oldest_with_retry(Some(MIN_BACKOFF)).is_err());
        let status = core.seal_status();
        assert!(status.last_error.is_some());
        assert_eq!(
            status.retry_at_ms,
            Some(2_000),
            "retry is recorded inside the attempt"
        );
        assert!(core.seal_oldest().unwrap());
        let status = core.seal_status();
        assert!(status.last_error.is_none());
        assert_eq!(
            status.retry_at_ms, None,
            "manual success clears the retry permanently"
        );
    }

    #[test]
    fn a_seal_age_longer_than_the_clock_range_never_wraps() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let config = SegConfig {
            seal_max_age: Duration::from_secs((u64::MAX / 1_000) + 1),
            maintenance_interval: Duration::from_secs(1),
            ..roomy()
        };
        let core = try_open_core(dir.path(), config, crate::seg::fs::real(), &clock).unwrap();
        fill(&core, 0..10);
        clock.set(13_000);
        core.tick().unwrap();
        assert!(core.view().frozen.is_empty());
    }

    #[test]
    fn a_maintenance_interval_longer_than_the_clock_range_never_wraps() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let config = SegConfig {
            retention: Some(Duration::from_secs(1)),
            maintenance_interval: Duration::from_secs((u64::MAX / 1_000) + 1),
            ..roomy()
        };
        let core = try_open_core(dir.path(), config, crate::seg::fs::real(), &clock).unwrap();
        fill(&core, 0..10);
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        core.tick().unwrap();
        clock.set(13_000);
        core.tick().unwrap();
        assert_eq!(sealed_ids(&core), [1]);
    }
}