commonware-storage 2026.7.0

Persist and retrieve data from an abstract store.
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
//! A prunable key-value store for ordered data.
//!
//! Data is stored across two backends: [crate::journal::segmented::fixed] for fixed-size index entries and
//! [crate::journal::segmented::glob::Glob] for values (managed by [crate::journal::segmented::oversized]).
//! The location of written data is stored in-memory by both index and key (via [crate::index::unordered::Index])
//! to enable efficient lookups (on average).
//!
//! _Notably, [Archive] does not make use of compaction nor on-disk indexes (and thus has no read
//! nor write amplification during normal operation).
//!
//! # Format
//!
//! [Archive] uses a two-journal structure for efficient page cache usage:
//!
//! **Index Journal (segmented/fixed)** - Fixed-size entries for fast startup replay:
//! ```text
//! +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
//! | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 |12 |13 |14 |15 |16 |17 |18 |19 |20 |21 |22 |23 |
//! +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
//! |          Index(u64)           |Key(Fixed Size)|        val_offset(u64)        | val_size(u32) |
//! +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
//! ```
//!
//! **Value Blob** - Raw values with CRC32 checksums (direct reads, no page cache):
//! ```text
//! +---+---+---+---+---+---+---+---+---+---+---+---+
//! |     Compressed Data (variable)    |   CRC32   |
//! +---+---+---+---+---+---+---+---+---+---+---+---+
//! ```
//!
//! # Uniqueness
//!
//! Indices are unique for [Archive] and writing to an occupied index is a no-op. Duplicate
//! indices can be stored via [`crate::archive::MultiArchive::put_multi`].
//!
//! Keys may be stored at multiple indices with either put variant. A lookup by
//! [`crate::archive::Identifier::Key`] may return any of the values at that key. Entries
//! whose index has been pruned are never returned or reported as present, so a key matching
//! both a pruned and a non-pruned entry resolves to the non-pruned entry.
//!
//! ## Conflicts
//!
//! Because a translated representation of a key is only ever stored in memory, it is possible (and
//! expected) that two keys will eventually be represented by the same translated key. To handle
//! this case, [Archive] must check the persisted form of all conflicting keys to ensure data from
//! the correct key is returned. To support efficient checks, [Archive] (via
//! [crate::index::unordered::Index]) keeps a linked list of all keys with the same translated
//! prefix:
//!
//! ```rust
//! struct Record {
//!     index: u64,
//!
//!     next: Option<Box<Record>>,
//! }
//! ```
//!
//! _To avoid random memory reads in the common case, the in-memory index directly stores the first
//! item in the linked list instead of a pointer to the first item._
//!
//! `index` is the key to the map used to serve lookups by `index` that stores the position in the
//! index journal (selected by `section = index / items_per_section * items_per_section` to minimize
//! the number of open blobs):
//!
//! ```text
//! // Maps index -> position in index journal
//! indices: BTreeMap<u64, u64>
//! ```
//!
//! _If the [Translator] provided by the caller does not uniformly distribute keys across the key
//! space or uses a translated representation that means keys on average have many conflicts,
//! performance will degrade._
//!
//! ## Memory Overhead
//!
//! [Archive] uses two maps to enable lookups by both index and key. The memory used to track each
//! index item is `8 + 8` (where `8` is the index and `8` is the position in the index journal).
//! The memory used to track each key item is `~translated(key).len() + 16` bytes (where `16` is the
//! size of the `Record` struct). This means that an [Archive] employing a [Translator] that uses
//! the first `8` bytes of a key will use `~40` bytes to index each key.
//!
//! ### MultiArchive Overhead
//!
//! [Archive] stores index positions in a dual-map layout:
//! - `indices: BTreeMap<u64, u64>` tracks the first position for each index.
//! - `extra_indices: BTreeMap<u64, Vec<u64>>` tracks additional positions for indices written via
//!   [crate::archive::MultiArchive::put_multi].
//!
//! This means the baseline overhead above remains unchanged for the first item at an index. For
//! indices with duplicates, the additional in-memory payload is:
//! - one `Vec<u64>` header (`24` bytes), and
//! - `n * 8` bytes for `n` additional positions.
//!
//! Equivalently, this is `24 + (n * 8)` bytes per duplicated index, excluding `BTreeMap` node
//! overhead for `extra_indices`.
//!
//! # Pruning
//!
//! [Archive] supports pruning up to a minimum `index` using the `prune` method. After `prune` is
//! called on a `section`, all interaction with a `section` less than the pruned `section` will
//! return an error.
//!
//! ## Lazy Index Cleanup
//!
//! Instead of performing a full iteration of the in-memory index, storing an additional in-memory
//! index per `section`, or replaying a `section` of the value blob,
//! [Archive] lazily cleans up the [crate::index::unordered::Index] after pruning. When a new key is
//! stored that overlaps (same translated value) with a pruned key, the pruned key is removed from
//! the in-memory index.
//!
//! # Read Path
//!
//! All reads (by index or key) first read the index entry from the index journal to get the
//! value location (offset and size), then read the value from the value blob. The index journal
//! uses a page cache for caching, so hot entries are served from memory. Values are read directly
//! from disk without caching to avoid polluting the page cache with large values.
//!
//! # Compression
//!
//! [Archive] supports compressing data before storing it on disk. This can be enabled by setting
//! the `compression` field in the `Config` struct to a valid `zstd` compression level. This setting
//! can be changed between initializations of [Archive], however, it must remain populated if any
//! data was written with compression enabled.
//!
//! # Querying for Gaps
//!
//! [Archive] tracks gaps in the index space to enable the caller to efficiently fetch unknown keys
//! using `next_gap`. This is a very common pattern when syncing blocks in a blockchain.
//!
//! # Example
//!
//! ```rust
//! use commonware_runtime::{Spawner, Runner, deterministic, buffer::paged::CacheRef};
//! use commonware_cryptography::{Hasher as _, Sha256};
//! use commonware_storage::{
//!     translator::FourCap,
//!     archive::{
//!         Archive as _,
//!         prunable::{Archive, Config},
//!     },
//! };
//! use commonware_utils::{NZUsize, NZU16, NZU64};
//!
//! let executor = deterministic::Runner::default();
//! executor.start(|context| async move {
//!     // Create an archive
//!     let cfg = Config {
//!         translator: FourCap,
//!         key_partition: "demo-index".into(),
//!         key_page_cache: CacheRef::from_pooler(&context, NZU16!(1024), NZUsize!(10)),
//!         value_partition: "demo-value".into(),
//!         compression: Some(3),
//!         codec_config: (),
//!         items_per_section: NZU64!(1024),
//!         key_write_buffer: NZUsize!(1024 * 1024),
//!         value_write_buffer: NZUsize!(1024 * 1024),
//!         replay_buffer: NZUsize!(4096),
//!     };
//!     let mut archive = Archive::init(context, cfg).await.unwrap();
//!
//!     // Put a key
//!     archive.put(1, Sha256::hash(b"data"), 10).await.unwrap();
//!
//!     // Sync the archive
//!     archive.sync().await.unwrap();
//! });
//! ```

use crate::translator::Translator;
use commonware_runtime::buffer::paged::CacheRef;
use std::num::{NonZeroU64, NonZeroUsize};

mod storage;
pub use storage::Archive;

/// Configuration for [Archive] storage.
#[derive(Clone)]
pub struct Config<T: Translator, C> {
    /// Logic to transform keys into their index representation.
    ///
    /// [Archive] assumes that all internal keys are spread uniformly across the key space.
    /// If that is not the case, lookups may be O(n) instead of O(1).
    pub translator: T,

    /// The partition to use for the key journal (stores index+key metadata).
    pub key_partition: String,

    /// The page cache to use for the key journal.
    pub key_page_cache: CacheRef,

    /// The partition to use for the value blob (stores values).
    pub value_partition: String,

    /// The compression level to use for the value blob.
    pub compression: Option<u8>,

    /// The [commonware_codec::Codec] configuration to use for the value stored in the archive.
    pub codec_config: C,

    /// The number of items per section (the granularity of pruning).
    pub items_per_section: NonZeroU64,

    /// The amount of bytes that can be buffered for the key journal before being written to a
    /// [commonware_runtime::Blob].
    pub key_write_buffer: NonZeroUsize,

    /// The amount of bytes that can be buffered for the value journal before being written to a
    /// [commonware_runtime::Blob].
    pub value_write_buffer: NonZeroUsize,

    /// The buffer size to use when replaying a [commonware_runtime::Blob].
    pub replay_buffer: NonZeroUsize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        archive::{Archive as _, Error, Identifier, MultiArchive as _},
        journal::Error as JournalError,
        translator::{FourCap, TwoCap},
    };
    use commonware_codec::{DecodeExt, Error as CodecError};
    use commonware_macros::{test_group, test_traced};
    use commonware_runtime::{
        deterministic,
        mocks::{
            fail_pending_syncs, release_next_pending_syncs, release_pending_syncs,
            DelayedSyncContext, PendingSyncs,
        },
        telemetry::metrics::has_metric_value,
        BufferPooler, Error as RError, Metrics as _, Runner, Spawner as _, Supervisor as _,
    };
    use commonware_utils::{sequence::FixedBytes, NZUsize, NZU16, NZU64};
    use rand::RngExt as _;
    use std::{
        collections::BTreeMap,
        num::{NonZeroU16, NonZeroU64},
        sync::{
            atomic::{AtomicUsize, Ordering},
            Arc,
        },
    };

    fn test_key(key: &str) -> FixedBytes<64> {
        let mut buf = [0u8; 64];
        let key = key.as_bytes();
        assert!(key.len() <= buf.len());
        buf[..key.len()].copy_from_slice(key);
        FixedBytes::decode(buf.as_ref()).unwrap()
    }

    const DEFAULT_ITEMS_PER_SECTION: u64 = 65536;
    const DEFAULT_WRITE_BUFFER: usize = 1024;
    const DEFAULT_REPLAY_BUFFER: usize = 4096;
    const PAGE_SIZE: NonZeroU16 = NZU16!(1024);
    const PAGE_CACHE_SIZE: NonZeroUsize = NZUsize!(10);

    fn test_config<E: BufferPooler>(
        context: &E,
        items_per_section: NonZeroU64,
    ) -> Config<FourCap, ()> {
        Config {
            translator: FourCap,
            key_partition: "test-index".into(),
            key_page_cache: CacheRef::from_pooler(context, PAGE_SIZE, PAGE_CACHE_SIZE),
            value_partition: "test-value".into(),
            codec_config: (),
            compression: None,
            key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
            value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
            replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
            items_per_section,
        }
    }

    #[test_traced]
    fn test_put_after_start_sync_is_accepted_before_handle_completes() {
        let executor = deterministic::Runner::default();
        let (_, checkpoint) = executor.start_and_recover(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(DEFAULT_ITEMS_PER_SECTION));
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            let handle = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            let pending_after_start = pending.lock().len();
            assert!(
                pending_after_start > 0,
                "put_start_sync should return while the sync handle is still pending"
            );

            archive
                .put(2, test_key("bbb"), 20)
                .await
                .expect("archive should remain usable before sync completion");
            assert_eq!(
                pending.lock().len(),
                pending_after_start,
                "put should not issue a new storage sync while accepting later data"
            );
            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), Some(10));

            release_pending_syncs(&pending);
            handle.await.expect("sync handle should complete");

            let follow_up = archive
                .start_sync()
                .await
                .expect("Failed to start next sync");
            assert!(
                !pending.lock().is_empty(),
                "the later put must remain pending for a future sync"
            );
            release_pending_syncs(&pending);
            follow_up.await.expect("follow-up sync should complete");
        });

        deterministic::Runner::from(checkpoint).start(|context| async move {
            let cfg = test_config(&context, NZU64!(DEFAULT_ITEMS_PER_SECTION));
            let archive = Archive::<_, _, FixedBytes<64>, i32>::init(context.child("reopen"), cfg)
                .await
                .expect("Failed to reopen archive");

            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), Some(10));
            assert_eq!(archive.get(Identifier::Index(2)).await.unwrap(), Some(20));
        });
    }

    #[test_traced]
    fn test_duplicate_put_start_sync_observes_in_flight_sync() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(DEFAULT_ITEMS_PER_SECTION));
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            assert_eq!(pending.lock().len(), 2);

            let second = archive
                .put_start_sync(1, test_key("duplicate"), 99)
                .await
                .expect("Failed to start duplicate sync");
            assert_eq!(
                pending.lock().len(),
                2,
                "duplicate put_start_sync must not issue a new storage sync"
            );

            let started = Arc::new(AtomicUsize::new(0));
            let completed = Arc::new(AtomicUsize::new(0));
            let started_clone = started.clone();
            let completed_clone = completed.clone();
            let waiter = context.inner.child("duplicate").spawn(|_| async move {
                started_clone.fetch_add(1, Ordering::Relaxed);
                second.await.expect("duplicate sync handle should complete");
                completed_clone.fetch_add(1, Ordering::Relaxed);
            });

            while started.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            commonware_runtime::reschedule().await;
            assert_eq!(
                completed.load(Ordering::Relaxed),
                0,
                "duplicate put_start_sync must observe the original in-flight sync"
            );

            release_pending_syncs(&pending);
            first.await.expect("first sync handle should complete");
            while completed.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            waiter.await.expect("duplicate waiter failed");

            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), Some(10));
        });
    }

    #[test_traced]
    fn test_overlapping_put_start_sync_waits_for_in_flight_sync() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(DEFAULT_ITEMS_PER_SECTION));
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            let pending_after_first = pending.lock().len();
            assert!(pending_after_first > 0);

            let started = Arc::new(AtomicUsize::new(0));
            let completed = Arc::new(AtomicUsize::new(0));
            let started_clone = started.clone();
            let completed_clone = completed.clone();
            let waiter = context.inner.child("second").spawn(|_| async move {
                started_clone.fetch_add(1, Ordering::Relaxed);
                let second = archive
                    .put_start_sync(2, test_key("bbb"), 20)
                    .await
                    .expect("Failed to start second sync");
                completed_clone.fetch_add(1, Ordering::Relaxed);
                (archive, second)
            });

            while started.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            commonware_runtime::reschedule().await;
            assert_eq!(completed.load(Ordering::Relaxed), 0);
            assert_eq!(
                pending.lock().len(),
                pending_after_first,
                "second put_start_sync must not start new syncs before the first completes"
            );

            release_pending_syncs(&pending);
            first.await.expect("first sync handle should complete");
            while completed.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            let (archive, second) = waiter.await.expect("second put task failed");
            assert!(!pending.lock().is_empty());
            release_pending_syncs(&pending);
            second.await.expect("second sync handle should complete");

            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), Some(10));
            assert_eq!(archive.get(Identifier::Index(2)).await.unwrap(), Some(20));
        });
    }

    #[test_traced]
    fn test_sync_after_put_start_sync_waits_for_in_flight_sync() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(DEFAULT_ITEMS_PER_SECTION));
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            assert!(!pending.lock().is_empty());

            let started = Arc::new(AtomicUsize::new(0));
            let completed = Arc::new(AtomicUsize::new(0));
            let started_clone = started.clone();
            let completed_clone = completed.clone();
            let waiter = context.inner.child("sync").spawn(|_| async move {
                started_clone.fetch_add(1, Ordering::Relaxed);
                archive.sync().await.expect("sync should complete");
                completed_clone.fetch_add(1, Ordering::Relaxed);
                archive
            });

            while started.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            commonware_runtime::reschedule().await;
            assert_eq!(
                completed.load(Ordering::Relaxed),
                0,
                "shutdown sync must wait for the in-flight put_start_sync handle"
            );

            release_pending_syncs(&pending);
            first.await.expect("first sync handle should complete");
            while completed.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            let archive = waiter.await.expect("sync task failed");
            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), Some(10));
        });
    }

    #[test_traced]
    fn test_destroy_after_put_start_sync_waits_for_in_flight_sync() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(DEFAULT_ITEMS_PER_SECTION));
            let mut archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("storage"), cfg)
                    .await
                    .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            assert!(!pending.lock().is_empty());

            let started = Arc::new(AtomicUsize::new(0));
            let completed = Arc::new(AtomicUsize::new(0));
            let started_clone = started.clone();
            let completed_clone = completed.clone();
            let waiter = context.inner.child("destroy").spawn(|_| async move {
                started_clone.fetch_add(1, Ordering::Relaxed);
                archive.destroy().await.expect("destroy should complete");
                completed_clone.fetch_add(1, Ordering::Relaxed);
            });

            while started.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            commonware_runtime::reschedule().await;
            assert_eq!(
                completed.load(Ordering::Relaxed),
                0,
                "destroy must wait for the in-flight put_start_sync handle"
            );

            release_pending_syncs(&pending);
            first.await.expect("first sync handle should complete");
            while completed.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            waiter.await.expect("destroy task failed");
        });
    }

    #[test_traced]
    fn test_prune_after_put_start_sync_waits_for_in_flight_sync() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(1));
            let mut archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("storage"), cfg)
                    .await
                    .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            assert!(!pending.lock().is_empty());

            let started = Arc::new(AtomicUsize::new(0));
            let completed = Arc::new(AtomicUsize::new(0));
            let started_clone = started.clone();
            let completed_clone = completed.clone();
            let waiter = context.inner.child("prune").spawn(|_| async move {
                started_clone.fetch_add(1, Ordering::Relaxed);
                archive.prune(2).await.expect("prune should complete");
                completed_clone.fetch_add(1, Ordering::Relaxed);
                archive
            });

            while started.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            commonware_runtime::reschedule().await;
            assert_eq!(
                completed.load(Ordering::Relaxed),
                0,
                "prune must wait for in-flight syncs on pruned sections"
            );

            release_pending_syncs(&pending);
            first
                .await
                .expect("sync handle should complete despite pruning");
            while completed.load(Ordering::Relaxed) == 0 {
                commonware_runtime::reschedule().await;
            }
            let archive = waiter.await.expect("prune task failed");
            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), None);
        });
    }

    #[test_traced]
    fn test_prune_surfaces_failed_in_flight_sync() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(1));
            let mut archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("storage"), cfg)
                    .await
                    .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            fail_pending_syncs(&pending);

            let err = archive
                .prune(2)
                .await
                .expect_err("prune must surface a failed in-flight sync");
            assert!(matches!(
                err,
                Error::Journal(JournalError::Runtime(RError::Io(_)))
            ));

            let err = first.await.expect_err("first sync handle should fail");
            assert!(matches!(err, RError::Io(_)));
        });
    }

    #[test_traced]
    fn test_put_start_sync_after_prune_drops_pruned_sync_requests() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(1));
            let mut archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("storage"), cfg)
                    .await
                    .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            release_pending_syncs(&pending);
            first.await.expect("first sync handle should complete");

            archive.prune(2).await.expect("Failed to prune");

            // If pruning left section 1 in the retained sync-request set, these calls would trip
            // the journal's prune guard.
            let second = archive
                .put_start_sync(2, test_key("bbb"), 20)
                .await
                .expect("put_start_sync after prune should succeed");
            release_pending_syncs(&pending);
            second.await.expect("second sync handle should complete");
            archive
                .sync()
                .await
                .expect("sync after prune should succeed");

            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), None);
            assert_eq!(archive.get(Identifier::Index(2)).await.unwrap(), Some(20));
        });
    }

    #[test_traced]
    fn test_overlapping_put_start_sync_restarts_after_all_handles_complete() {
        let executor = deterministic::Runner::default();
        let (_, checkpoint) = executor.start_and_recover(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(1));
            let mut archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("storage"), cfg)
                    .await
                    .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start first sync");
            assert_eq!(pending.lock().len(), 2);

            let second = archive
                .put_start_sync(2, test_key("bbb"), 20)
                .await
                .expect("Failed to start second sync");
            assert_eq!(
                pending.lock().len(),
                4,
                "different sections should be able to have independent in-flight syncs"
            );

            release_pending_syncs(&pending);
            first.await.expect("first sync handle should complete");
            second.await.expect("second sync handle should complete");
        });

        deterministic::Runner::from(checkpoint).start(|context| async move {
            let cfg = test_config(&context, NZU64!(1));
            let archive = Archive::<_, _, FixedBytes<64>, i32>::init(context.child("reopen"), cfg)
                .await
                .expect("Failed to reopen archive");

            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), Some(10));
            assert_eq!(archive.get(Identifier::Index(2)).await.unwrap(), Some(20));
        });
    }

    #[test_traced]
    fn test_overlapping_put_start_sync_restarts_only_completed_handles() {
        let executor = deterministic::Runner::default();
        let (_, checkpoint) = executor.start_and_recover(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(1));
            let mut archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("storage"), cfg)
                    .await
                    .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start first sync");
            let second = archive
                .put_start_sync(2, test_key("bbb"), 20)
                .await
                .expect("Failed to start second sync");
            assert_eq!(pending.lock().len(), 4);

            release_next_pending_syncs(&pending, 2);
            first.await.expect("first sync handle should complete");

            drop(second);
            drop(archive);
        });

        deterministic::Runner::from(checkpoint).start(|context| async move {
            let cfg = test_config(&context, NZU64!(1));
            let archive = Archive::<_, _, FixedBytes<64>, i32>::init(context.child("reopen"), cfg)
                .await
                .expect("Failed to reopen archive");

            assert_eq!(archive.get(Identifier::Index(1)).await.unwrap(), Some(10));
            assert_eq!(archive.get(Identifier::Index(2)).await.unwrap(), None);
        });
    }

    #[test_traced]
    fn test_failed_start_sync_is_returned_by_next_start_sync_handle() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let pending = PendingSyncs::default();
            let context = DelayedSyncContext {
                inner: context,
                pending: pending.clone(),
            };
            let cfg = test_config(&context, NZU64!(DEFAULT_ITEMS_PER_SECTION));
            let mut archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("storage"), cfg)
                    .await
                    .expect("Failed to initialize archive");

            let first = archive
                .put_start_sync(1, test_key("aaa"), 10)
                .await
                .expect("Failed to start sync");
            assert_eq!(pending.lock().len(), 2);
            fail_pending_syncs(&pending);

            archive
                .put(2, test_key("bbb"), 20)
                .await
                .expect("write should be accepted before observing the failed sync");

            let second = archive
                .start_sync()
                .await
                .expect("start_sync should return a handle for the failed sync");
            let err = second
                .await
                .expect_err("next start_sync handle should observe failed in-flight sync");
            assert!(matches!(err, RError::Io(_)));

            let err = first.await.expect_err("first sync handle should fail");
            assert!(matches!(err, RError::Io(_)));
        });
    }

    #[test_traced]
    fn test_archive_compression_then_none() {
        // Initialize the deterministic context
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            // Initialize the archive
            let cfg = Config {
                translator: FourCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: Some(3),
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(DEFAULT_ITEMS_PER_SECTION),
            };
            let mut archive = Archive::init(context.child("first"), cfg.clone())
                .await
                .expect("Failed to initialize archive");

            // Put the key-data pair
            let index = 1u64;
            let key = test_key("testkey");
            let data = 1;
            archive
                .put(index, key.clone(), data)
                .await
                .expect("Failed to put data");

            // Sync and drop the archive
            archive.sync().await.expect("Failed to sync archive");
            drop(archive);

            // Initialize the archive again without compression.
            // Index journal replay succeeds (no compression), but value reads will fail.
            let cfg = Config {
                translator: FourCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(DEFAULT_ITEMS_PER_SECTION),
            };
            let archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("second"), cfg.clone())
                    .await
                    .unwrap();

            // Getting the value should fail because compression settings mismatch.
            // Without compression, the codec sees extra bytes after decoding the value
            // (because the compressed data doesn't match the expected format).
            let result: Result<Option<i32>, _> = archive.get(Identifier::Index(index)).await;
            assert!(matches!(
                result,
                Err(Error::Journal(JournalError::Codec(CodecError::ExtraData(
                    _
                ))))
            ));
        });
    }

    #[test_traced]
    fn test_archive_overlapping_key_basic() {
        // Initialize the deterministic context
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            // Initialize the archive
            let cfg = Config {
                translator: FourCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(DEFAULT_ITEMS_PER_SECTION),
            };
            let mut archive = Archive::init(context.child("storage"), cfg.clone())
                .await
                .expect("Failed to initialize archive");

            let index1 = 1u64;
            let key1 = test_key("keys1");
            let data1 = 1;
            let index2 = 2u64;
            let key2 = test_key("keys2");
            let data2 = 2;

            // Put the key-data pair
            archive
                .put(index1, key1.clone(), data1)
                .await
                .expect("Failed to put data");

            // Put the key-data pair
            archive
                .put(index2, key2.clone(), data2)
                .await
                .expect("Failed to put data");

            // Get the data back
            let retrieved = archive
                .get(Identifier::Key(&key1))
                .await
                .expect("Failed to get data")
                .expect("Data not found");
            assert_eq!(retrieved, data1);

            // Get the data back
            let retrieved = archive
                .get(Identifier::Key(&key2))
                .await
                .expect("Failed to get data")
                .expect("Data not found");
            assert_eq!(retrieved, data2);

            // Check metrics
            let buffer = context.encode();
            assert!(has_metric_value(&buffer, "items_tracked", 2));
            assert!(buffer.contains("unnecessary_reads_total 1"));
            assert!(buffer.contains("gets_total 2"));
        });
    }

    #[test_traced]
    fn test_archive_overlapping_key_multiple_sections() {
        // Initialize the deterministic context
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            // Initialize the archive
            let cfg = Config {
                translator: FourCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(DEFAULT_ITEMS_PER_SECTION),
            };
            let mut archive = Archive::init(context.child("storage"), cfg.clone())
                .await
                .expect("Failed to initialize archive");

            let index1 = 1u64;
            let key1 = test_key("keys1");
            let data1 = 1;
            let index2 = 2_000_000u64;
            let key2 = test_key("keys2");
            let data2 = 2;

            // Put the key-data pair
            archive
                .put(index1, key1.clone(), data1)
                .await
                .expect("Failed to put data");

            // Put the key-data pair
            archive
                .put(index2, key2.clone(), data2)
                .await
                .expect("Failed to put data");

            // Get the data back
            let retrieved = archive
                .get(Identifier::Key(&key1))
                .await
                .expect("Failed to get data")
                .expect("Data not found");
            assert_eq!(retrieved, data1);

            // Get the data back
            let retrieved = archive
                .get(Identifier::Key(&key2))
                .await
                .expect("Failed to get data")
                .expect("Data not found");
            assert_eq!(retrieved, data2);
        });
    }

    #[test_traced]
    fn test_archive_prune_keys() {
        // Initialize the deterministic context
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            // Initialize the archive
            let cfg = Config {
                translator: FourCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(1), // no mask - each item is its own section
            };
            let mut archive = Archive::init(context.child("storage"), cfg.clone())
                .await
                .expect("Failed to initialize archive");

            // Insert multiple keys across different sections
            let keys = vec![
                (1u64, test_key("key1-blah"), 1),
                (2u64, test_key("key2-blah"), 2),
                (3u64, test_key("key3-blah"), 3),
                (4u64, test_key("key3-bleh"), 3),
                (5u64, test_key("key4-blah"), 4),
            ];

            for (index, key, data) in &keys {
                archive
                    .put(*index, key.clone(), *data)
                    .await
                    .expect("Failed to put data");
            }

            // Check metrics
            let buffer = context.encode();
            assert!(has_metric_value(&buffer, "items_tracked", 5));

            // Prune sections less than 3
            archive.prune(3).await.expect("Failed to prune");

            // Ensure keys 1 and 2 are no longer present
            for (index, key, data) in keys {
                let retrieved = archive
                    .get(Identifier::Key(&key))
                    .await
                    .expect("Failed to get data");
                if index < 3 {
                    assert!(retrieved.is_none());
                } else {
                    assert_eq!(retrieved.expect("Data not found"), data);
                }
            }

            // Check metrics
            let buffer = context.encode();
            assert!(has_metric_value(&buffer, "items_tracked", 3));
            assert!(has_metric_value(&buffer, "indices_pruned_total", 2));
            assert!(has_metric_value(&buffer, "pruned_total", 0)); // no lazy cleanup yet

            // Try to prune older section
            archive.prune(2).await.expect("Failed to prune");

            // Try to prune current section again
            archive.prune(3).await.expect("Failed to prune");

            // Try to put older index
            let result = archive.put(1, test_key("key1-blah"), 1).await;
            assert!(matches!(result, Err(Error::AlreadyPrunedTo(3))));

            // Trigger lazy removal of keys
            archive
                .put(6, test_key("key2-blfh"), 5)
                .await
                .expect("Failed to put data");

            // Check metrics
            let buffer = context.encode();
            assert!(has_metric_value(&buffer, "items_tracked", 4)); // lazily remove one, add one
            assert!(has_metric_value(&buffer, "indices_pruned_total", 2));
            assert!(has_metric_value(&buffer, "pruned_total", 1));
        });
    }

    fn test_archive_keys_and_restart(num_keys: usize) -> String {
        // Initialize the deterministic context
        let executor = deterministic::Runner::default();
        executor.start(|mut context| async move {
            // Initialize the archive
            let items_per_section = 256u64;
            let cfg = Config {
                translator: TwoCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(items_per_section),
            };
            let mut archive = Archive::init(
                context.child("init").with_attribute("index", 1),
                cfg.clone(),
            )
            .await
            .expect("Failed to initialize archive");

            // Insert multiple keys across different sections
            let mut keys = BTreeMap::new();
            while keys.len() < num_keys {
                let index = keys.len() as u64;
                let mut key = [0u8; 64];
                context.fill(&mut key);
                let key = FixedBytes::<64>::decode(key.as_ref()).unwrap();
                let mut data = [0u8; 1024];
                context.fill(&mut data);
                let data = FixedBytes::<1024>::decode(data.as_ref()).unwrap();

                archive
                    .put(index, key.clone(), data.clone())
                    .await
                    .expect("Failed to put data");
                keys.insert(key, (index, data));
            }

            // Ensure all keys can be retrieved
            for (key, (index, data)) in &keys {
                let retrieved = archive
                    .get(Identifier::Index(*index))
                    .await
                    .expect("Failed to get data")
                    .expect("Data not found");
                assert_eq!(&retrieved, data);
                let retrieved = archive
                    .get(Identifier::Key(key))
                    .await
                    .expect("Failed to get data")
                    .expect("Data not found");
                assert_eq!(&retrieved, data);
            }

            // Check metrics
            let buffer = context.encode();
            assert!(has_metric_value(&buffer, "items_tracked", num_keys));
            assert!(has_metric_value(&buffer, "pruned_total", 0));

            // Sync and drop the archive
            archive.sync().await.expect("Failed to sync archive");
            drop(archive);

            // Reinitialize the archive
            let cfg = Config {
                translator: TwoCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(items_per_section),
            };
            let mut archive = Archive::<_, _, _, FixedBytes<1024>>::init(
                context.child("init").with_attribute("index", 2),
                cfg.clone(),
            )
            .await
            .expect("Failed to initialize archive");

            // Ensure all keys can be retrieved
            for (key, (index, data)) in &keys {
                let retrieved = archive
                    .get(Identifier::Index(*index))
                    .await
                    .expect("Failed to get data")
                    .expect("Data not found");
                assert_eq!(&retrieved, data);
                let retrieved = archive
                    .get(Identifier::Key(key))
                    .await
                    .expect("Failed to get data")
                    .expect("Data not found");
                assert_eq!(&retrieved, data);
            }

            // Prune first half
            let min = (keys.len() / 2) as u64;
            archive.prune(min).await.expect("Failed to prune");

            // Ensure all keys can be retrieved that haven't been pruned
            let min = (min / items_per_section) * items_per_section;
            let mut removed = 0;
            for (key, (index, data)) in keys {
                if index >= min {
                    let retrieved = archive
                        .get(Identifier::Key(&key))
                        .await
                        .expect("Failed to get data")
                        .expect("Data not found");
                    assert_eq!(retrieved, data);

                    // Check range
                    let (current_end, start_next) = archive.next_gap(index);
                    assert_eq!(current_end.unwrap(), num_keys as u64 - 1);
                    assert!(start_next.is_none());
                } else {
                    let retrieved = archive
                        .get(Identifier::Key(&key))
                        .await
                        .expect("Failed to get data");
                    assert!(retrieved.is_none());
                    removed += 1;

                    // Check range
                    let (current_end, start_next) = archive.next_gap(index);
                    assert!(current_end.is_none());
                    assert_eq!(start_next.unwrap(), min);
                }
            }

            // Check metrics
            let buffer = context.encode();
            assert!(has_metric_value(
                &buffer,
                "items_tracked",
                num_keys - removed
            ));
            assert!(has_metric_value(&buffer, "indices_pruned_total", removed));
            assert!(has_metric_value(&buffer, "pruned_total", 0)); // have not lazily removed keys yet

            context.auditor().state()
        })
    }

    #[test_group("slow")]
    #[test_traced]
    fn test_archive_many_keys_and_restart() {
        test_archive_keys_and_restart(100_000);
    }

    #[test_group("slow")]
    #[test_traced]
    fn test_determinism() {
        let state1 = test_archive_keys_and_restart(5_000);
        let state2 = test_archive_keys_and_restart(5_000);
        assert_eq!(state1, state2);
    }

    /// Regression: when the same key is stored at multiple indices and the
    /// earlier index is pruned, a subsequent `get`/`has` by key must resolve
    /// to the surviving, non-pruned entry rather than report the pruned one.
    /// Callers such as consensus's marshal cache rely on this to retain a
    /// reproposal of the same block at a later index even after the
    /// earlier index's retention window closes.
    #[test_traced]
    fn test_archive_key_lookup_skips_pruned_duplicates() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let cfg = Config {
                translator: FourCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(1),
            };
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            // Same key stored at two different indices. Distinct values only
            // to make it observable which entry wins; a real caller would
            // store the same value (e.g. the same block) at both indices.
            let key = test_key("dupe-key");
            archive.put(2, key.clone(), 20).await.unwrap();
            archive.put(5, key.clone(), 50).await.unwrap();

            // Before pruning, either entry is a permitted answer per the
            // trait contract. The implementation happens to return the
            // earlier index, but we only assert a value is present.
            assert!(archive.get(Identifier::Key(&key)).await.unwrap().is_some());
            assert!(archive.has(Identifier::Key(&key)).await.unwrap());

            // Prune the earlier index (section 2). The later index must be
            // the sole surviving answer.
            archive.prune(3).await.unwrap();
            let got = archive.get(Identifier::Key(&key)).await.unwrap();
            assert_eq!(
                got,
                Some(50),
                "key lookup must skip the pruned entry and return the surviving one"
            );
            assert!(archive.has(Identifier::Key(&key)).await.unwrap());

            // Prune past the later index too — now nothing survives.
            archive.prune(6).await.unwrap();
            assert_eq!(archive.get(Identifier::Key(&key)).await.unwrap(), None);
            assert!(!archive.has(Identifier::Key(&key)).await.unwrap());
        });
    }

    #[test_traced]
    fn test_get_all_after_prune() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let cfg = Config {
                translator: FourCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(1),
            };
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            archive.put_multi(1, test_key("aaa"), 10).await.unwrap();
            archive.put_multi(1, test_key("bbb"), 20).await.unwrap();
            archive.put_multi(3, test_key("ccc"), 30).await.unwrap();

            // Prune below index 3
            archive.prune(3).await.unwrap();

            // Pruned index returns None
            let all = archive.get_all(1).await.unwrap();
            assert_eq!(all, None);

            // Surviving index still works
            let all = archive.get_all(3).await.unwrap();
            assert_eq!(all, Some(vec![30]));
        });
    }

    #[test_traced]
    fn test_has_at() {
        let executor = deterministic::Runner::default();
        let (_, checkpoint) = executor.start_and_recover(|context| async move {
            let cfg = test_config(&context, NZU64!(2));
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            // Vacant index
            assert!(!archive.has_at(1, &test_key("aaaa1")).await.unwrap());

            // Exact key at the index
            archive.put_multi(1, test_key("aaaa1"), 10).await.unwrap();
            assert!(archive.has_at(1, &test_key("aaaa1")).await.unwrap());

            // Same key is not reported at other indices
            assert!(!archive.has_at(2, &test_key("aaaa1")).await.unwrap());

            // A translated-key collision (FourCap shares the "aaaa" prefix)
            // must not produce a false positive
            assert!(!archive.has_at(1, &test_key("aaaa2")).await.unwrap());

            // A second entry at the same index is visible alongside the first
            archive.put_multi(1, test_key("aaaa2"), 20).await.unwrap();
            assert!(archive.has_at(1, &test_key("aaaa1")).await.unwrap());
            assert!(archive.has_at(1, &test_key("aaaa2")).await.unwrap());

            // A different key at an occupied index is absent
            assert!(!archive.has_at(1, &test_key("bbbb")).await.unwrap());

            archive.put_multi(3, test_key("cccc"), 30).await.unwrap();
            archive.sync().await.unwrap();
        });

        deterministic::Runner::from(checkpoint).start(|context| async move {
            let cfg = test_config(&context, NZU64!(2));
            let mut archive =
                Archive::<_, _, FixedBytes<64>, i32>::init(context.child("reopen"), cfg)
                    .await
                    .expect("Failed to reopen archive");

            // Replay rebuilds both entries at the shared index
            assert!(archive.has_at(1, &test_key("aaaa1")).await.unwrap());
            assert!(archive.has_at(1, &test_key("aaaa2")).await.unwrap());
            assert!(!archive.has_at(1, &test_key("bbbb")).await.unwrap());

            // Pruned indices report absent
            archive.prune(2).await.unwrap();
            assert!(!archive.has_at(1, &test_key("aaaa1")).await.unwrap());
            assert!(!archive.has_at(1, &test_key("aaaa2")).await.unwrap());
            assert!(archive.has_at(3, &test_key("cccc")).await.unwrap());

            archive.destroy().await.unwrap();
        });
    }

    #[test_traced]
    fn test_has_key() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let cfg = test_config(&context, NZU64!(2));
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            // Absent key
            let key = test_key("aaaa1");
            assert!(!archive.has(Identifier::Key(&key)).await.unwrap());

            // Exact key
            archive.put(1, key.clone(), 10).await.unwrap();
            assert!(archive.has(Identifier::Key(&key)).await.unwrap());

            // A translated-key collision (FourCap shares the "aaaa" prefix)
            // must not produce a false positive
            let collision = test_key("aaaa2");
            assert!(!archive.has(Identifier::Key(&collision)).await.unwrap());
            archive.put(2, collision.clone(), 20).await.unwrap();
            assert!(archive.has(Identifier::Key(&collision)).await.unwrap());

            // Pruned keys report absent. Pruning is section-granular
            // (items_per_section = 2), so prune at a section boundary that
            // drops indices 1 and 2 while retaining index 4.
            archive.put(4, test_key("cccc"), 30).await.unwrap();
            archive.prune(4).await.unwrap();
            assert!(!archive.has(Identifier::Key(&key)).await.unwrap());
            assert!(!archive.has(Identifier::Key(&collision)).await.unwrap());
            assert!(archive
                .has(Identifier::Key(&test_key("cccc")))
                .await
                .unwrap());

            archive.destroy().await.unwrap();
        });
    }

    #[test_traced]
    fn test_put_multi_prune() {
        let executor = deterministic::Runner::default();
        executor.start(|context| async move {
            let cfg = Config {
                translator: FourCap,
                key_partition: "test-index".into(),
                key_page_cache: CacheRef::from_pooler(&context, PAGE_SIZE, PAGE_CACHE_SIZE),
                value_partition: "test-value".into(),
                codec_config: (),
                compression: None,
                key_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                value_write_buffer: NZUsize!(DEFAULT_WRITE_BUFFER),
                replay_buffer: NZUsize!(DEFAULT_REPLAY_BUFFER),
                items_per_section: NZU64!(1),
            };
            let mut archive = Archive::init(context.child("storage"), cfg)
                .await
                .expect("Failed to initialize archive");

            // Two items at index 1, one at index 3
            archive.put_multi(1, test_key("aaa"), 10).await.unwrap();
            archive.put_multi(1, test_key("bbb"), 20).await.unwrap();
            archive.put_multi(3, test_key("ccc"), 30).await.unwrap();

            let buffer = context.encode();
            assert!(has_metric_value(&buffer, "items_tracked", 2));

            // Prune below index 3
            archive.prune(3).await.unwrap();

            // Both items at index 1 are gone
            assert_eq!(
                archive
                    .get(Identifier::Key(&test_key("aaa")))
                    .await
                    .unwrap(),
                None
            );
            assert_eq!(
                archive
                    .get(Identifier::Key(&test_key("bbb")))
                    .await
                    .unwrap(),
                None
            );

            // Item at index 3 survives
            assert_eq!(
                archive
                    .get(Identifier::Key(&test_key("ccc")))
                    .await
                    .unwrap(),
                Some(30)
            );

            let buffer = context.encode();
            assert!(has_metric_value(&buffer, "items_tracked", 1));
            assert!(has_metric_value(&buffer, "indices_pruned_total", 1));

            // put_multi below pruned index is rejected
            let result = archive.put_multi(2, test_key("ddd"), 40).await;
            assert!(matches!(result, Err(Error::AlreadyPrunedTo(3))));
        });
    }
}