armdb 0.15.1

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
//! The switch from one generation to the next, and admission of writes.

use std::hash::Hash;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};

use super::block::BLOCK_HEADER_LEN;
use super::config::SegConfig;
use super::core::{SegCore, View};
use super::generation::{Append, Generation, InsertStep};
use super::hash::key_hash;
use super::manifest::{self, GenRecord, GenState, Manifest, PublishError};
use crate::entry::entry_size;
use crate::error::{DbError, DbResult};
use crate::key::Key;
use crate::sync;

/// How long a waiter sleeps between two looks at the seal queue.
const WAIT_SLICE: Duration = Duration::from_millis(20);

/// How long a write that finds the seal queue full may wait for a slot.
/// Either way, a write that gives up was not applied.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Admission {
    /// Until this instant, then `SealBackpressure`. The contract of every
    /// public write.
    Deadline(Instant),
    /// While the seal pipeline works: until a seal attempt fails after the
    /// wait began, or the collection is fenced or shut down. A migration
    /// waits so: it writes as fast as it reads, outruns any seal, and a
    /// timeout would fail the same open on every retry. With no worker
    /// running nothing else frees a slot, and `fallback` applies.
    UntilSealFails { fallback: Instant },
}

impl Admission {
    /// The admission of a public write.
    pub(crate) fn deadline(config: &SegConfig) -> DbResult<Self> {
        Ok(Self::Deadline(config.seal_deadline()?))
    }

    /// The admission of a migration write.
    pub(crate) fn until_seal_fails(config: &SegConfig) -> DbResult<Self> {
        Ok(Self::UntilSealFails {
            fallback: config.seal_deadline()?,
        })
    }
}

/// Refuse an entry that no segment block can hold, before anything is
/// appended. The block index stores a block's length, header included, as a
/// `u32`; a larger entry could enter a generation but never be sealed, and
/// the generation would then stay frozen with every later write ending in
/// `SealBackpressure`.
pub(crate) fn check_entry_size(key_len: usize, value_len: usize) -> DbResult<()> {
    let fits = u32::try_from(value_len).is_ok_and(|value_len| {
        BLOCK_HEADER_LEN as u64 + entry_size(key_len, value_len) <= u64::from(u32::MAX)
    });
    if fits {
        Ok(())
    } else {
        Err(DbError::Client(
            "the entry is too large for a segment block",
        ))
    }
}

impl<K: Key + Hash + Eq + Send + Sync + 'static> SegCore<K> {
    /// Append a value, applying admission before the journal write.
    pub(crate) fn put(&self, key: &K, value: &[u8]) -> DbResult<()> {
        self.put_with(key, value, Admission::deadline(&self.config)?)
    }

    /// [`Self::put`] with an explicit admission.
    pub(crate) fn put_with(&self, key: &K, value: &[u8], admission: Admission) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "put", "tree" => "seg_map").increment(1);
        self.write(key, Some(value), admission)
    }

    /// Write `value` only when no layer holds a live version of `key`.
    pub(crate) fn insert(&self, key: &K, value: &[u8]) -> DbResult<()> {
        self.insert_since(key, value, None)
    }

    /// Insert with the caller's trusted lower-layer pruning hint.
    pub(crate) fn insert_since(
        &self,
        key: &K,
        value: &[u8],
        since_ms: Option<u64>,
    ) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "insert", "tree" => "seg_map").increment(1);
        check_entry_size(size_of::<K>(), value.len())?;
        let h = key_hash(key.as_bytes(), self.seed);
        let admission = Admission::deadline(&self.config)?;
        let limits = self.config.limits();
        loop {
            self.check_writable()?;
            let view = self.view();
            let active = &view.active;

            // Steps 1 and 2: the active layer decides when it knows the key.
            let mut step = active.insert(h, key, value, None, limits)?;
            if step == InsertStep::NeedLower {
                // Step 3, with no lock held.
                let lower = self.exists_in(&view, h, key, false, since_ms);
                // Steps 4 to 6. The active layer is resolved again: it may
                // have learned the key while the lower layers were read.
                step = active.insert(h, key, value, lower.as_ref().ok().copied(), limits)?;
                if step == InsertStep::NeedLower {
                    // The lower layers could not be read, and the active one
                    // still does not know the key: the result depends on them.
                    return Err(lower.expect_err("an answer from below never leaves NeedLower"));
                }
            }
            match step {
                InsertStep::Done { crossed } => {
                    if crossed {
                        self.signal.wake();
                    }
                    return Ok(());
                }
                InsertStep::Exists => return Err(DbError::KeyExists),
                InsertStep::Frozen => {}
                InsertStep::Full => self.make_room(active, admission)?,
                InsertStep::NeedLower => {
                    return Err(DbError::Internal("insert left NeedLower unresolved"));
                }
            }
        }
    }

    /// Append a tombstone, masking values in every older layer.
    pub(crate) fn delete(&self, key: &K) -> DbResult<()> {
        self.delete_with(key, Admission::deadline(&self.config)?)
    }

    /// [`Self::delete`] with an explicit admission.
    pub(crate) fn delete_with(&self, key: &K, admission: Admission) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "delete", "tree" => "seg_map").increment(1);
        self.write(key, None, admission)
    }

    fn write(&self, key: &K, value: Option<&[u8]>, admission: Admission) -> DbResult<()> {
        // A tombstone carries no value and always fits.
        if let Some(value) = value {
            check_entry_size(size_of::<K>(), value.len())?;
        }
        let h = key_hash(key.as_bytes(), self.seed);
        loop {
            // Inside the loop: a fence set by a concurrent freeze leaves the
            // generation marked frozen, and this is what ends the retries.
            self.check_writable()?;
            let view = self.view();
            match view.active.append(h, key, value, self.config.limits())? {
                Append::Done { crossed } => {
                    if crossed {
                        self.signal.wake();
                    }
                    return Ok(());
                }
                Append::Frozen => {}
                Append::Full => self.make_room(&view.active, admission)?,
            }
        }
    }

    /// Report admission failure for an operation that was not applied.
    /// A shutdown refuses without counting a timeout: none happened.
    pub(crate) fn backpressure(&self) -> DbError {
        if !self.shut_down.load(Ordering::Acquire) {
            metrics::counter!("armdb.seg.backpressure_timeouts", "collection" => self.meta.name)
                .increment(1);
        }
        DbError::SealBackpressure {
            collection: self.meta.name,
        }
    }

    /// Wait until a seal attempt ends or the slice passes, or give up as
    /// `admission` says. `failures` is the count of failed seal attempts when
    /// the wait began. Holds no lock of the write path.
    fn wait_for_seal(&self, admission: Admission, failures: u64) -> DbResult<()> {
        if self.shut_down.load(Ordering::Acquire) {
            return Err(self.backpressure());
        }
        let deadline = match admission {
            Admission::UntilSealFails { .. } if self.worker_running() => None,
            Admission::Deadline(at) | Admission::UntilSealFails { fallback: at } => Some(at),
        };
        let now = Instant::now();
        // Read under the lock the worker records a failure under, so that
        // its notification cannot fall between the check and the wait.
        let state = sync::lock(&self.seal);
        let slice = match deadline {
            Some(at) if now >= at => return Err(self.backpressure()),
            Some(at) => WAIT_SLICE.min(at - now),
            // The worker now backs off, and nothing says when a slot frees.
            None if state.failures != failures => return Err(self.backpressure()),
            None => WAIT_SLICE,
        };
        metrics::counter!("armdb.seg.backpressure_waits", "collection" => self.meta.name)
            .increment(1);
        drop(sync::cv_wait_timeout(
            &self.seal_cv,
            &self.seal,
            state,
            slice,
        ));
        Ok(())
    }

    /// Get a generation that takes writes, or fail without having written.
    pub(crate) fn make_room(
        &self,
        full: &Arc<Generation<K>>,
        admission: Admission,
    ) -> DbResult<()> {
        // An attempt that failed before the wait began is not the one this
        // write waits for: the worker retries it.
        let failures = sync::lock(&self.seal).failures;
        loop {
            self.check_writable()?;
            if !Arc::ptr_eq(&self.view().active, full) {
                return Ok(());
            }
            {
                let mut manifest = sync::lock(&self.manifest);
                if !Arc::ptr_eq(&self.view().active, full) {
                    return Ok(());
                }
                if !self.shut_down.load(Ordering::Acquire)
                    && manifest.frozen_count() < self.config.max_frozen_generations
                {
                    return self.freeze_locked(&mut manifest);
                }
            }
            self.wait_for_seal(admission, failures)?;
        }
    }

    /// Transaction admission, taken before the commit holds any lock: wait
    /// within `seal_wait_timeout` until the active generation has room.
    /// Commit admission under the locks repeats the check without waiting.
    pub(crate) fn admit_tx(&self) -> DbResult<()> {
        self.check_writable()?;
        let active = self.view().active.clone();
        if active.is_full() && !active.is_frozen() {
            self.make_room(&active, Admission::deadline(&self.config)?)?;
        }
        Ok(())
    }

    /// Freeze the active generation and queue its seal. Returns once the
    /// freeze is durable; it does not wait for the segment.
    pub(crate) fn seal(&self) -> DbResult<()> {
        let admission = Admission::deadline(&self.config)?;
        let target = self.view().active.clone();
        if target.keys() == 0 {
            self.check_writable()?;
            return Ok(());
        }
        self.make_room(&target, admission)
    }

    /// The freeze protocol. The caller holds the manifest mutex.
    pub(crate) fn freeze_locked(&self, manifest: &mut Manifest) -> DbResult<()> {
        self.check_writable()?;
        let view = self.view();
        let old = view.active.clone();
        if old.keys() == 0 {
            return Ok(());
        }

        // Shutdown and freeze publication are serialized by the manifest
        // mutex. Recheck here too: maintenance may call this method directly.
        if self.shut_down.load(Ordering::Acquire) {
            return Err(self.backpressure());
        }

        // Step 0: the id is burned before anything is written under it.
        let (reserved, gen_id) = manifest.reserve_gen_id()?;
        self.publish_next(manifest, reserved)?;
        super::failpoint!(GENERATION_ID_RESERVED);

        // Step 1, outside the shard locks. The generation is dated in step 2.
        let mut new = Generation::create(
            self.fs.clone(),
            &self.gen_root,
            gen_id,
            &self.config,
            0,
            self.order,
        )?;
        new.bind_fence(self.collection_fence.clone());
        super::failpoint!(GENERATION_CREATED);

        // Step 2: no write is in flight and none can start. The freeze time
        // is read only now: every write the old generation holds landed
        // before it, so a `try_get_hinted` claim that holds never prunes
        // that generation, and neither does retention. Clamped by I7, so
        // the new generation never opens before the old one froze.
        let guards = old.lock_all();
        // A logged failure may fence us while we wait for these locks. The
        // reserved id stays burned, but the unpublished generation is removed.
        if let Err(e) = self.check_writable() {
            new.doom();
            return Err(e);
        }
        let frozen_at_ms = manifest.monotone_time(self.now_ms());
        new.set_opened_at_ms(frozen_at_ms);
        let next_gsn = old.next_gsn();
        let max_gsn = next_gsn - 1;
        old.mark_frozen(frozen_at_ms, max_gsn);
        new.seed_gsn(next_gsn);

        // Step 3, under the locks: no write into the new generation can
        // become durable before the manifest knows that generation.
        let record = GenRecord {
            gen_id,
            state: GenState::Active,
            shard_count: new.shard_count() as u8,
            opened_at_ms: frozen_at_ms,
            frozen_at_ms: 0,
            min_gsn: next_gsn,
            max_gsn: 0,
        };
        let rollback = |e: DbError| {
            old.unmark_frozen();
            new.doom();
            e
        };
        let next = match manifest.with_freeze(frozen_at_ms, max_gsn, record) {
            Ok(next) => next,
            Err(e) => return Err(rollback(e)),
        };
        match manifest::publish(&*self.fs, &self.dir, &next) {
            Ok(()) => {
                *manifest = next;
                super::failpoint!(FREEZE_PUBLISHED);
            }
            Err(PublishError::NotPublished(e)) => return Err(rollback(e)),
            Err(PublishError::Indeterminate(e)) => {
                // The disk may already name the new generation. Both stay,
                // and the old one stays marked: nothing more is written.
                return Err(self.fence(format!(
                    "the outcome of the freeze of generation {:#x} is unknown: {e}",
                    old.id()
                )));
            }
        }

        // Step 4.
        let mut frozen = Vec::with_capacity(view.frozen.len() + 1);
        frozen.push(old.clone());
        frozen.extend(view.frozen.iter().cloned());
        self.set_view(View {
            active: Arc::new(new),
            frozen,
            sealed: view.sealed.clone(),
        });

        // Step 5.
        drop(guards);
        metrics::counter!("armdb.seg.freezes", "collection" => self.meta.name).increment(1);
        self.signal.wake();
        Ok(())
    }
}

#[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::{GenState, MANIFEST_NAME, load};
    use crate::seg::seal::sdat_name;
    use crate::seg::testkit::{
        TestClock, build_collection, key_of, open_core, try_open_core, value,
    };
    use std::time::Duration;

    #[test]
    fn fence_stops_append_and_insert_waiting_on_generation_locks() {
        for insert in [false, true] {
            let dir = tempfile::tempdir().unwrap();
            let core = open_core(dir.path(), roomy());
            let active = core.view().active.clone();
            let guards = active.lock_all();
            let waiting = active.observe_index_lock_attempt();
            let key = key_of(12);
            let h = key_hash(&key, core.seed);
            std::thread::scope(|scope| {
                // Own the guards inside the scope body so timeout/panic releases
                // them before the scope joins the blocked waiter.
                let guards = guards;
                let active = &active;
                let core = &core;
                let waiter = scope.spawn(move || {
                    if insert {
                        active
                            .insert(h, &key, b"refused", Some(false), core.config.limits())
                            .map(drop)
                    } else {
                        active
                            .append(h, &key, Some(b"refused"), core.config.limits())
                            .map(drop)
                    }
                });
                waiting
                    .recv_timeout(Duration::from_secs(5))
                    .expect("mutation never reached its index acquisition boundary");
                core.fence("waiting operation".into());
                drop(guards);
                assert!(matches!(
                    waiter.join().unwrap(),
                    Err(DbError::CollectionFenced { .. })
                ));
            });
            assert_eq!(active.keys(), 0);
            assert_eq!(active.next_gsn(), 1);
        }
    }

    #[test]
    fn fence_stops_freeze_waiting_on_generation_locks() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        core.put(&key_of(1), b"old").unwrap();
        let active = core.view().active.clone();
        let guards = active.lock_all();
        let waiting = active.observe_index_lock_attempt();
        std::thread::scope(|scope| {
            // Release on unwind before the scope joins its blocked waiter.
            let guards = guards;
            let waiter = scope.spawn(|| core.seal());
            waiting
                .recv_timeout(Duration::from_secs(5))
                .expect("freeze never reached its index acquisition boundary");
            let manifest_before = std::fs::read(dir.path().join(MANIFEST_NAME)).unwrap();
            core.fence("waiting freeze".into());
            drop(guards);
            assert!(matches!(
                waiter.join().unwrap(),
                Err(DbError::CollectionFenced { .. })
            ));
            assert_eq!(
                std::fs::read(dir.path().join(MANIFEST_NAME)).unwrap(),
                manifest_before
            );
        });
        assert_eq!(core.view().active.id(), 1);
        assert!(!active.is_frozen());
        assert!(core.view().frozen.is_empty());
        assert!(!dir.path().join("gen/0000000000000002").exists());
    }

    #[test]
    fn an_entry_no_block_can_hold_is_refused() {
        // The largest padded entry that still fits a block with its header,
        // minus the 16-byte entry header and an 8-byte key.
        let largest = (u32::MAX as usize - BLOCK_HEADER_LEN) & !7;
        let value_max = largest - 16 - 8;
        check_entry_size(8, value_max).unwrap();
        assert!(matches!(
            check_entry_size(8, value_max + 1),
            Err(DbError::Client(_))
        ));
        assert!(matches!(
            check_entry_size(8, u32::MAX as usize + 1),
            Err(DbError::Client(_))
        ));
        check_entry_size(8, 0).unwrap();
    }

    /// No size threshold in reach, and room for many frozen generations.
    fn roomy() -> SegConfig {
        SegConfig {
            seal_max_keys: 1_000_000,
            max_frozen_generations: 64,
            ..SegConfig::test()
        }
    }

    #[test]
    fn writes_are_read_back() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        for i in 0..100 {
            core.put(&key_of(i), &value(i)).unwrap();
        }
        core.put(&key_of(7), b"again").unwrap();
        core.delete(&key_of(8)).unwrap();
        assert_eq!(core.get(&key_of(1)).unwrap(), Some(value(1)));
        assert_eq!(core.get(&key_of(7)).unwrap(), Some(b"again".to_vec()));
        assert_eq!(core.get(&key_of(8)).unwrap(), None);
        assert_eq!(core.len(), 99);
    }

    #[test]
    fn a_delete_masks_a_value_in_an_older_layer() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), roomy());
        // Key 50 lives in the sealed segment only.
        assert!(core.get(&key_of(50)).unwrap().is_some());
        core.delete(&key_of(50)).unwrap();
        assert_eq!(core.get(&key_of(50)).unwrap(), None);
        assert!(!core.contains(&key_of(50)).unwrap());

        core.put(&key_of(50), b"back").unwrap();
        assert_eq!(core.get(&key_of(50)).unwrap(), Some(b"back".to_vec()));
    }

    #[test]
    fn a_freeze_opens_a_new_generation() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        for i in 0..50 {
            core.put(&key_of(i), &value(i)).unwrap();
        }
        core.seal().unwrap();

        let view = core.view();
        assert_eq!(view.active.id(), 2);
        assert_eq!(view.active.keys(), 0);
        assert_eq!(view.frozen.len(), 1);
        assert_eq!(view.frozen[0].id(), 1);
        assert!(view.frozen[0].is_frozen());

        core.put(&key_of(100), b"new").unwrap();
        assert_eq!(
            view.frozen[0].keys(),
            50,
            "the frozen generation takes no write"
        );
        assert_eq!(core.view().active.keys(), 1);
        for i in 0..50 {
            assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)));
        }

        let manifest = load(dir.path()).unwrap().unwrap();
        assert_eq!(manifest.generations.len(), 2);
        assert_eq!(manifest.generations[0].state, GenState::Frozen);
        assert_eq!(manifest.generations[0].max_gsn, 50);
        assert_eq!(manifest.generations[1].state, GenState::Active);
        assert_eq!(manifest.generations[1].min_gsn, 51);
        assert_eq!(manifest.gsn_floor, 50);
    }

    #[test]
    fn sealing_an_empty_generation_does_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        let version = load(dir.path()).unwrap().unwrap().manifest_version;
        core.seal().unwrap();
        assert_eq!(core.view().active.id(), 1);
        assert_eq!(load(dir.path()).unwrap().unwrap().manifest_version, version);
    }

    #[test]
    fn gsn_ranges_of_layers_never_overlap() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        for round in 0..5u64 {
            for i in 0..20 {
                core.put(&key_of(round * 100 + i), b"v").unwrap();
            }
            core.seal().unwrap();
        }
        let manifest = load(dir.path()).unwrap().unwrap();
        manifest.check().unwrap();
        assert_eq!(manifest.generations.len(), 6);
        for pair in manifest.generations.windows(2) {
            assert_eq!(pair[0].max_gsn + 1, pair[1].min_gsn);
        }
    }

    #[test]
    fn freeze_times_never_go_back() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(10_000);
        let core = try_open_core(dir.path(), roomy(), crate::seg::fs::real(), &clock).unwrap();
        core.put(&key_of(1), b"v").unwrap();
        core.seal().unwrap();
        clock.set(5_000);
        core.put(&key_of(2), b"v").unwrap();
        core.seal().unwrap();

        let manifest = load(dir.path()).unwrap().unwrap();
        assert_eq!(manifest.generations[0].frozen_at_ms, 10_000);
        assert_eq!(manifest.generations[1].frozen_at_ms, 10_000);
        assert_eq!(core.view().frozen[0].frozen_at_ms(), 10_000);
    }

    /// Moves the clock and writes into the collection while a freeze makes
    /// its new generation durable: a write that races the freeze.
    struct LateWriteFs {
        inner: Arc<dyn crate::seg::fs::SegFs>,
        clock: TestClock,
        core: std::sync::Mutex<Option<std::sync::Weak<SegCore<crate::seg::testkit::TestKey>>>>,
    }

    impl crate::seg::fs::SegFs for LateWriteFs {
        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<()> {
            self.inner.write_all(out, path, bytes)
        }
        fn sync_file(&self, file: &std::fs::File, path: &std::path::Path) -> std::io::Result<()> {
            self.inner.sync_file(file, path)
        }
        fn rename(&self, from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> {
            self.inner.rename(from, to)
        }
        fn sync_dir(&self, dir: &std::path::Path) -> std::io::Result<()> {
            if dir.ends_with("0000000000000002") {
                let core = self.core.lock().unwrap().take();
                if let Some(core) = core.and_then(|core| core.upgrade()) {
                    self.clock.set(2_000);
                    core.put(&key_of(7), b"late").unwrap();
                }
            }
            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)
        }
    }

    #[test]
    fn a_layer_is_not_frozen_before_a_write_it_holds() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1_000);
        let fs = Arc::new(LateWriteFs {
            inner: crate::seg::fs::real(),
            clock: clock.clone(),
            core: std::sync::Mutex::new(None),
        });
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &clock).unwrap();
        core.put(&key_of(1), b"v").unwrap();
        *fs.core.lock().unwrap() = Some(Arc::downgrade(&core));
        core.seal().unwrap();

        // The late write landed in the generation that was being frozen.
        let view = core.view();
        assert_eq!(view.frozen.len(), 1);
        assert!(fs.core.lock().unwrap().is_none(), "the late write ran");
        assert_eq!(view.frozen[0].frozen_at_ms(), 2_000);
        assert_eq!(view.active.opened_at_ms(), 2_000);
        let manifest = load(dir.path()).unwrap().unwrap();
        assert_eq!(manifest.generations[0].frozen_at_ms, 2_000);
        assert_eq!(manifest.generations[1].opened_at_ms, 2_000);

        // A claim that holds for the late write does not prune its layer.
        assert_eq!(
            core.get_pruned(&key_of(7), Some(2_000)).unwrap(),
            Some(b"late".to_vec())
        );
    }

    #[test]
    fn an_id_is_reserved_before_anything_is_written_under_it() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        core.put(&key_of(1), b"v").unwrap();
        fs.clear();
        core.seal().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, "one reservation, one freeze");
        let generation = fs.position(FsOpKind::SyncDir, "0000000000000002").unwrap();
        assert!(publications[0] < generation, "the id is reserved first");
        assert!(
            generation < publications[1],
            "the directory is durable before it is named"
        );
    }

    #[test]
    fn a_full_generation_is_frozen_by_the_next_write() {
        let dir = tempfile::tempdir().unwrap();
        let config = SegConfig {
            seal_max_keys: 10,
            max_frozen_generations: 4,
            ..SegConfig::test()
        };
        let core = open_core(dir.path(), config);
        for i in 0..10 {
            core.put(&key_of(i), &value(i)).unwrap();
        }
        assert!(core.view().active.is_full());
        assert_eq!(
            core.view().active.id(),
            1,
            "the crossing write does not freeze"
        );

        core.put(&key_of(10), &value(10)).unwrap();
        let view = core.view();
        assert_eq!(view.active.id(), 2);
        assert_eq!(view.active.keys(), 1);
        assert_eq!(view.frozen[0].keys(), 10);
        for i in 0..11 {
            assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)));
        }
    }

    #[test]
    fn a_write_without_room_fails_and_changes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let config = SegConfig {
            seal_max_keys: 5,
            max_frozen_generations: 1,
            seal_wait_timeout: Duration::from_millis(100),
            ..SegConfig::test()
        };
        let core = open_core(dir.path(), config);
        // Generation 1 fills and is frozen; generation 2 fills.
        for i in 0..10 {
            core.put(&key_of(i), &value(i)).unwrap();
        }
        assert_eq!(core.view().frozen.len(), 1);
        assert!(core.view().active.is_full());
        let len = core.len();

        let started = std::time::Instant::now();
        let err = core.put(&key_of(10), b"refused").unwrap_err();
        assert!(matches!(
            err,
            DbError::SealBackpressure {
                collection: "test_seg"
            }
        ));
        assert!(started.elapsed() >= Duration::from_millis(100));
        assert_eq!(
            core.get(&key_of(10)).unwrap(),
            None,
            "the write was not applied"
        );
        assert_eq!(core.len(), len);
        assert_eq!(core.view().active.keys(), 5);

        // A delete and an explicit seal wait and fail the same way.
        assert!(matches!(
            core.delete(&key_of(1)),
            Err(DbError::SealBackpressure { .. })
        ));
        assert_eq!(core.get(&key_of(1)).unwrap(), Some(value(1)));
        assert!(matches!(core.seal(), Err(DbError::SealBackpressure { .. })));
    }

    #[test]
    fn writers_racing_a_freeze_lose_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        const WRITERS: u64 = 4;
        const PER_WRITER: u64 = 2_000;
        let populated = std::sync::Barrier::new(WRITERS as usize + 1);

        std::thread::scope(|scope| {
            for w in 0..WRITERS {
                let (core, populated) = (&core, &populated);
                scope.spawn(move || {
                    for i in 0..PER_WRITER {
                        let n = w * 1_000_000 + i;
                        core.put(&key_of(n), &value(n)).unwrap();
                        if i == 0 {
                            populated.wait();
                        }
                    }
                });
            }
            populated.wait();
            for _ in 0..20 {
                core.seal().unwrap();
                std::thread::yield_now();
            }
        });

        for w in 0..WRITERS {
            for i in 0..PER_WRITER {
                let n = w * 1_000_000 + i;
                assert_eq!(core.get(&key_of(n)).unwrap(), Some(value(n)), "key {n}");
            }
        }
        let manifest = load(dir.path()).unwrap().unwrap();
        manifest.check().unwrap();
        let view = core.view();
        let written: u64 = view.active.keys() + view.frozen.iter().map(|g| g.keys()).sum::<u64>();
        assert_eq!(
            written,
            WRITERS * PER_WRITER,
            "no write landed in two generations"
        );
        assert!(
            !view.frozen.is_empty(),
            "at least one populated freeze occurred"
        );
        // A frozen generation holds exactly the GSNs its record names.
        for (generation, rec) in view.frozen.iter().rev().zip(&manifest.generations) {
            assert_eq!(generation.id(), rec.gen_id);
            assert_eq!(generation.next_gsn() - 1, rec.max_gsn);
        }
    }

    #[test]
    fn a_freeze_that_was_not_published_is_rolled_back() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        core.put(&key_of(1), b"v").unwrap();

        // The first publication reserves the id, the second is the freeze.
        fs.fail_on(FsOpKind::Rename, MANIFEST_NAME, 1);
        assert!(core.seal().is_err());

        let view = core.view();
        assert_eq!(view.active.id(), 1);
        assert!(!view.active.is_frozen());
        assert!(view.frozen.is_empty());
        assert!(!dir.path().join("gen/0000000000000002").exists());
        core.check_writable().unwrap();
        core.put(&key_of(2), b"v").unwrap();
        assert_eq!(core.view().active.keys(), 2);

        let manifest = load(dir.path()).unwrap().unwrap();
        assert_eq!(manifest.generations.len(), 1);
        assert_eq!(manifest.next_gen_id, 3, "the reserved id stays burned");

        core.seal().unwrap();
        assert_eq!(core.view().active.id(), 3);
    }

    #[test]
    fn a_generation_that_cannot_be_made_durable_fails_the_write() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let config = SegConfig {
            seal_max_keys: 3,
            max_frozen_generations: 4,
            ..SegConfig::test()
        };
        let core = try_open_core(dir.path(), config, fs.clone(), &TestClock::new(1)).unwrap();
        for i in 0..3 {
            core.put(&key_of(i), &value(i)).unwrap();
        }

        fs.fail_on(FsOpKind::SyncDir, "0000000000000002", 0);
        let err = core.put(&key_of(3), b"refused").unwrap_err();
        assert!(matches!(err, DbError::Io(_)), "{err:?}");
        assert_eq!(
            core.get(&key_of(3)).unwrap(),
            None,
            "the write was not applied"
        );

        let view = core.view();
        assert_eq!(view.active.id(), 1);
        assert!(!view.active.is_frozen());
        assert!(view.frozen.is_empty());
        assert!(!dir.path().join("gen/0000000000000002").exists());
        core.check_writable().unwrap();
        let manifest = load(dir.path()).unwrap().unwrap();
        assert_eq!(manifest.next_gen_id, 3, "the reserved id stays burned");
        assert_eq!(manifest.generations.len(), 1);
        assert_eq!(manifest.generations[0].gen_id, 1);
        for i in 0..3 {
            assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)));
        }

        // The next write gets its room under a fresh id.
        core.put(&key_of(3), &value(3)).unwrap();
        assert_eq!(core.view().active.id(), 3);
        assert_eq!(core.get(&key_of(3)).unwrap(), Some(value(3)));
    }

    #[test]
    fn a_fenced_collection_refuses_changes_and_keeps_its_barriers() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), roomy());
        core.put(&key_of(900), b"before the fence").unwrap();
        // Read one key resolved from each layer before and after fencing.
        let layer_keys = [key_of(50), key_of(150), key_of(250)];
        let values = layer_keys.map(|key| core.get(&key).unwrap().unwrap());
        core.fence("test".into());

        let fenced = |result: DbResult<()>| {
            assert!(
                matches!(result, Err(DbError::CollectionFenced { .. })),
                "{result:?}"
            );
        };
        fenced(core.put(&key_of(901), b"v"));
        fenced(core.delete(&key_of(900)));
        fenced(core.insert(&key_of(902), b"v"));
        fenced(core.seal());
        fenced(core.seal_oldest().map(drop));
        fenced(core.drop_segments_before(u64::MAX).map(drop));
        fenced(core.wait_sealed(Duration::from_millis(10)).map(drop));

        // Writes already taken can still be made durable, and read.
        core.flush().unwrap();
        core.durable_flush().unwrap();
        assert_eq!(core.dirty_shards(), 0);
        assert_eq!(
            core.get(&key_of(900)).unwrap(),
            Some(b"before the fence".to_vec())
        );
        assert_eq!(core.get(&key_of(901)).unwrap(), None);
        assert_eq!(core.get(&key_of(902)).unwrap(), None);
        for (key, expected) in layer_keys.iter().zip(values) {
            assert_eq!(core.get(key).unwrap(), Some(expected));
        }
        assert_eq!(core.view().sealed.len(), 1);
        assert_eq!(core.view().frozen.len(), 1);
    }

    #[test]
    fn a_freeze_with_an_unknown_outcome_fences_the_collection() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        for i in 0..10 {
            core.put(&key_of(i), &value(i)).unwrap();
        }

        // Directory syncs of a freeze: the reservation, the generation, its
        // parent, the freeze itself.
        fs.fail_on(FsOpKind::SyncDir, "", 3);
        assert!(matches!(core.seal(), Err(DbError::CollectionFenced { .. })));
        assert!(matches!(
            core.put(&key_of(99), b"v"),
            Err(DbError::CollectionFenced { .. })
        ));
        assert!(matches!(core.seal(), Err(DbError::CollectionFenced { .. })));
        // Reads keep working, and nothing was deleted.
        assert_eq!(core.get(&key_of(3)).unwrap(), Some(value(3)));
        assert!(dir.path().join("gen/0000000000000001").exists());
        assert!(dir.path().join("gen/0000000000000002").exists());

        drop(core);
        let core = open_core(dir.path(), roomy());
        core.check_writable().unwrap();
        for i in 0..10 {
            assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)));
        }
        core.put(&key_of(99), b"v").unwrap();
    }
    #[test]
    fn shutdown_blocks_a_freeze_waiting_for_the_manifest() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        core.put(&key_of(1), b"v").unwrap();
        let manifest = sync::lock(&core.manifest);
        fs.clear();
        std::thread::scope(|scope| {
            let (started, waiting) = std::sync::mpsc::channel();
            let core = &core;
            let seal = scope.spawn(move || {
                started.send(()).unwrap();
                core.seal()
            });
            waiting.recv().unwrap();
            // Let the sealer reach the manifest mutex: raised earlier, the
            // flag would be seen before the lock and prove nothing about
            // the recheck under it.
            std::thread::sleep(Duration::from_millis(100));
            core.shut_down.store(true, Ordering::Release);
            drop(manifest);
            assert!(matches!(
                seal.join().unwrap(),
                Err(DbError::SealBackpressure { .. })
            ));
        });
        assert!(fs.ops().is_empty(), "shutdown prevents even id reservation");
        assert_eq!(core.view().active.id(), 1);
        assert!(!core.view().active.is_frozen());
        assert_eq!(core.get(&key_of(1)).unwrap(), Some(b"v".to_vec()));
    }

    #[test]
    fn freeze_locked_rechecks_shutdown_before_reserving_an_id() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        core.put(&key_of(1), b"v").unwrap();
        let mut manifest = sync::lock(&core.manifest);
        core.shut_down.store(true, Ordering::Release);
        fs.clear();
        assert!(matches!(
            core.freeze_locked(&mut manifest),
            Err(DbError::SealBackpressure { .. })
        ));
        assert_eq!(manifest.next_gen_id, 2);
        assert!(fs.ops().is_empty());
        assert!(!core.view().active.is_frozen());
    }

    #[test]
    fn shutdown_allows_writes_with_room_and_refuses_the_next_write() {
        let dir = tempfile::tempdir().unwrap();
        let config = SegConfig {
            seal_max_keys: 2,
            ..roomy()
        };
        let core = open_core(dir.path(), config);
        {
            let _manifest = sync::lock(&core.manifest);
            core.shut_down.store(true, Ordering::Release);
        }
        core.put(&key_of(1), b"v").unwrap();
        core.delete(&key_of(1)).unwrap();
        core.put(&key_of(2), b"v").unwrap();
        assert!(core.view().active.is_full());
        assert!(matches!(
            core.put(&key_of(3), b"v"),
            Err(DbError::SealBackpressure { .. })
        ));
        assert_eq!(core.get(&key_of(3)).unwrap(), None);
        assert_eq!(core.get(&key_of(1)).unwrap(), None);
        assert_eq!(core.view().active.id(), 1);
        assert!(core.view().frozen.is_empty());
    }

    #[test]
    fn a_byte_threshold_crossing_write_is_applied_before_freezing() {
        let dir = tempfile::tempdir().unwrap();
        let config = SegConfig {
            seal_max_bytes: 1,
            ..roomy()
        };
        let core = open_core(dir.path(), config);
        core.put(&key_of(1), b"crossing").unwrap();
        assert!(core.view().active.is_full());
        assert_eq!(core.view().active.id(), 1);
        assert_eq!(core.get(&key_of(1)).unwrap(), Some(b"crossing".to_vec()));
        core.put(&key_of(2), b"next").unwrap();
        assert_eq!(core.view().active.id(), 2);
        assert_eq!(core.view().frozen[0].keys(), 1);
        assert_eq!(core.get(&key_of(2)).unwrap(), Some(b"next".to_vec()));
    }

    #[test]
    fn a_reservation_failure_creates_no_generation() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), roomy(), fs.clone(), &TestClock::new(1)).unwrap();
        core.put(&key_of(1), b"v").unwrap();
        fs.fail_on(FsOpKind::Rename, MANIFEST_NAME, 0);
        assert!(core.seal().is_err());
        assert!(!dir.path().join("gen/0000000000000002").exists());
        assert!(!core.view().active.is_frozen());
        assert_eq!(load(dir.path()).unwrap().unwrap().next_gen_id, 2);
        core.put(&key_of(2), b"still writable").unwrap();
        core.seal().unwrap();
        assert_eq!(core.view().active.id(), 2);
    }

    #[test]
    fn insert_refuses_a_key_that_is_live_in_any_layer() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), roomy());

        // Live in the active generation, the frozen one, the segment.
        for i in [250u64, 150, 50] {
            assert!(
                matches!(core.insert(&key_of(i), b"x"), Err(DbError::KeyExists)),
                "key {i}"
            );
        }
        assert_eq!(
            core.get(&key_of(50)).unwrap(),
            Some(crate::seg::testkit::value_of(50))
        );

        // Deleted in the active generation, the frozen one, the segment.
        for i in [205u64, 105, 9] {
            core.insert(&key_of(i), b"reborn").unwrap();
            assert_eq!(
                core.get(&key_of(i)).unwrap(),
                Some(b"reborn".to_vec()),
                "key {i}"
            );
        }
        // Never written.
        core.insert(&key_of(5_000), b"new").unwrap();
        assert!(matches!(
            core.insert(&key_of(5_000), b"again"),
            Err(DbError::KeyExists)
        ));
        assert_eq!(core.get(&key_of(5_000)).unwrap(), Some(b"new".to_vec()));
    }

    #[test]
    fn a_newer_tombstone_wins_over_an_older_value() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), roomy());
        // The segment holds key 50; the active generation deletes it.
        core.delete(&key_of(50)).unwrap();
        core.insert(&key_of(50), b"fresh").unwrap();
        assert_eq!(core.get(&key_of(50)).unwrap(), Some(b"fresh".to_vec()));
    }

    #[test]
    fn a_damaged_older_layer_matters_only_when_the_answer_depends_on_it() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), roomy());
        core.put(&key_of(50), b"live above").unwrap();
        core.delete(&key_of(51)).unwrap();

        // Cut the data file of the segment down to its header.
        let sdat = dir.path().join("seg").join(sdat_name(1, 1));
        std::fs::OpenOptions::new()
            .write(true)
            .open(&sdat)
            .unwrap()
            .set_len(64)
            .unwrap();

        assert!(matches!(
            core.insert(&key_of(50), b"x"),
            Err(DbError::KeyExists)
        ));
        core.insert(&key_of(51), b"reborn").unwrap();
        // Key 52 is known to the segment only.
        assert!(matches!(
            core.insert(&key_of(52), b"x"),
            Err(DbError::SegmentCorrupt { segment_id: 1, .. })
        ));
        assert_eq!(
            core.view().active.probe(
                crate::seg::hash::key_hash(key_of(52).as_slice(), core.seed),
                &key_of(52)
            ),
            crate::seg::generation::GenProbe::Absent,
            "a failed insert writes nothing"
        );
    }

    #[test]
    fn one_of_many_concurrent_inserts_wins() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        let wins = std::sync::atomic::AtomicUsize::new(0);
        std::thread::scope(|scope| {
            for t in 0..8u64 {
                let (core, wins) = (&core, &wins);
                scope.spawn(move || {
                    for i in 0..200u64 {
                        match core.insert(&key_of(i), &value(t)) {
                            Ok(()) => {
                                wins.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                            }
                            Err(DbError::KeyExists) => {}
                            Err(other) => panic!("{other:?}"),
                        }
                    }
                });
            }
        });
        assert_eq!(wins.load(std::sync::atomic::Ordering::Relaxed), 200);
        assert_eq!(core.len(), 200);
    }

    #[test]
    fn inserts_racing_a_freeze_land_exactly_once() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        let populated = std::sync::Barrier::new(5);
        std::thread::scope(|scope| {
            for t in 0..4u64 {
                let (core, populated) = (&core, &populated);
                scope.spawn(move || {
                    for i in 0..1_000u64 {
                        core.insert(&key_of(t * 1_000_000 + i), b"v").unwrap();
                        if i == 0 {
                            populated.wait();
                        }
                    }
                });
            }
            populated.wait();
            for _ in 0..20 {
                core.seal().unwrap();
                std::thread::yield_now();
            }
        });
        let view = core.view();
        assert!(!view.frozen.is_empty(), "a populated freeze occurred");
        let written: u64 = view.active.keys() + view.frozen.iter().map(|g| g.keys()).sum::<u64>();
        assert_eq!(written, 4_000);
        for t in 0..4u64 {
            assert!(matches!(
                core.insert(&key_of(t * 1_000_000 + 7), b"x"),
                Err(DbError::KeyExists)
            ));
        }
    }

    #[test]
    fn an_insert_without_room_changes_nothing() {
        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 core = open_core(dir.path(), config);
        for i in 0..10 {
            core.insert(&key_of(i), &value(i)).unwrap();
        }
        assert!(matches!(
            core.insert(&key_of(10), b"refused"),
            Err(DbError::SealBackpressure { .. })
        ));
        assert_eq!(core.get(&key_of(10)).unwrap(), None);
        // A key that exists is still reported as existing, not as backpressure.
        assert!(matches!(
            core.insert(&key_of(3), b"x"),
            Err(DbError::KeyExists)
        ));
    }

    #[test]
    fn shared_key_delete_insert_and_populated_freeze_have_linearized_outcomes() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), roomy());
        let key = key_of(7);
        for round in 0..24 {
            core.put(&key, b"before").unwrap();
            let before = core.view().active.id();
            let start = std::sync::Barrier::new(3);
            let inserted = std::thread::scope(|scope| {
                let deleted = scope.spawn(|| {
                    start.wait();
                    core.delete(&key).unwrap();
                });
                let inserted = scope.spawn(|| {
                    start.wait();
                    core.insert(&key, b"after")
                });
                let frozen = scope.spawn(|| {
                    start.wait();
                    core.seal().unwrap();
                });
                deleted.join().unwrap();
                frozen.join().unwrap();
                inserted.join().unwrap()
            });
            // The preexisting live key guarantees a populated freeze every round.
            let view = core.view();
            assert_ne!(view.active.id(), before, "round {round}");
            assert!(view.frozen.iter().any(|g| g.id() == before && g.keys() > 0));
            // Success requires delete before insert; KeyExists requires insert
            // before delete. Freeze may occur anywhere in either ordering.
            match inserted {
                Ok(()) => assert_eq!(core.get(&key).unwrap(), Some(b"after".to_vec())),
                Err(DbError::KeyExists) => assert_eq!(core.get(&key).unwrap(), None),
                Err(other) => panic!("round {round}: {other:?}"),
            }
        }
    }
}