fasm-storage 0.1.1

Ordered async byte-oriented key-value storage: the KvStore/Commit traits and the Storage Scoping adapter shared by FASM state machines and their storage backends
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
//! The flat directory layout engines over [`RawKv`] and [`AsyncRawKv`] views.
//!
//! One layout, written and tested once here; the synchronous flat backends
//! (btreemap, redb) implement [`RawKv`] over their transaction views and
//! route every operation through [`FlatEngine`], while asynchronous flat
//! backends (IndexedDB) implement [`AsyncRawKv`] and route through
//! [`AsyncFlatEngine`]. FDB does not use these — it uses FDB's native
//! directory layer over the same row layouts (the [`crate::flatdir`] module
//! documents the shared layouts).
//!
//! The engine's layout is a verbatim port of FoundationDB's
//! `DirectoryLayer` (see [`crate::flatdir`]): a node tree of allocated
//! prefixes (packed `i64`s from the High Contention Allocator), a version
//! row, and HCA counter/recent rows, all under the `0xFE` node region.
//! Data keys are `prefix ‖ key` in the `0x00`–`0xFD` region; `0xFF` is
//! reserved.
//!
//! Stores are opened lazily: a fresh store (no version row) answers
//! empty on reads, and the first create writes the version row. A store
//! whose version row this layout does not read fails every operation
//! with [`FlatError::Foreign`].

use core::ops::Bound;
use rand::rng as thread_rng;

use crate::flatdir::hca::ThreadRngSource;
use crate::flatdir::layout::{ROOT_PATH_SEGMENT, data_region};
use crate::flatdir::ops;
use crate::key::validate_dir;
use crate::rawkv::{AsyncRawKv, RawKv};
use crate::stream::KvPair;

/// Re-exported for the backends' error types (defined with the layout
/// machinery it guards).
pub use crate::flatdir::error::FlatError;

/// The flat directory layout over a raw byte view.
///
/// Not itself a [`KvStore`](crate::KvStore): it has no async boundary and
/// no engine error identity. The flat backends wrap it.
///
/// Directory paths are the fasm form (`&[&[u8]]`, UTF-8, validated with
/// [`validate_dir`]); each fasm directory maps to the layer path
/// `[ROOT_PATH_SEGMENT] ‖ dir`, so the fasm root `[]` is the layer's
/// anchor directory — a real, allocated node, never the layer root.
pub struct FlatEngine<R: RawKv> {
    raw: R,
}

impl<R: RawKv> FlatEngine<R> {
    /// Wrap a raw view.
    pub fn new(raw: R) -> Self {
        Self { raw }
    }

    /// The underlying view, for backends that need to reach it directly
    /// (streaming, raw-handle accessors, the open-time probe).
    pub fn raw(&self) -> &R {
        &self.raw
    }

    /// The mutable underlying view.
    pub fn raw_mut(&mut self) -> &mut R {
        &mut self.raw
    }

    /// The layer path for a fasm directory: the anchor segment plus the
    /// directory's segments (already UTF-8-validated by the caller).
    fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
        let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
        v.push(ROOT_PATH_SEGMENT.as_bytes());
        v.extend_from_slice(dir);
        v
    }

    // -- directory resolution ---------------------------------------------

    /// Resolve `dir` to its allocated prefix.
    ///
    /// `Ok(None)` when the store is fresh or the directory does not
    /// exist. `Err(FlatError::Foreign)` when the store's version row is
    /// one this layout does not read; `Err(FlatError::Corrupt)` when a
    /// node row's value is malformed. Write operations use
    /// [`allocate_dir`](Self::allocate_dir) instead.
    pub fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        ops::check_version_read(&self.raw)?;
        ops::find(&self.raw, &Self::layer_path(dir))
    }

    /// Resolve `dir`, allocating every missing directory (and only
    /// those) along the way — the anchor included, which is what writes
    /// the version row on a fresh store. Returns the resolved prefix.
    ///
    /// Creation is recursive on the *path*: creating `[a, b]` creates
    /// both `a` and `b` (lazy parent creation, verbatim from the layer).
    /// Each new node takes a candidate from the HCA; the allocation and
    /// the node rows land in the same transaction view, so a rolled-back
    /// creation leaves no trace. Idempotent: an existing directory
    /// resolves to its prefix without a new allocation.
    pub fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        let mut rng = thread_rng();
        ops::create_or_open(&mut self.raw, &Self::layer_path(dir), true, &mut rng)
            .map(|p| p.expect("create_or_open with creation returns Some"))
    }

    // -- data operations ----------------------------------------------------

    /// Get `key` within `dir`. A missing directory yields `Ok(None)`.
    pub fn get(&self, dir: &[&[u8]], key: &[u8]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir)? else {
            return Ok(None);
        };
        let mut raw_key = prefix;
        raw_key.extend_from_slice(key);
        Ok(self.raw.get(&raw_key)?)
    }

    /// Scan within `dir` between `start` and `end` (bounds over the key
    /// part), ascending or descending. A missing directory yields no rows.
    /// The returned keys are the within-directory keys.
    pub fn scan(
        &self,
        dir: &[&[u8]],
        start: Bound<&[u8]>,
        end: Bound<&[u8]>,
        forward: bool,
    ) -> Result<Vec<KvPair>, FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir)? else {
            return Ok(Vec::new());
        };
        let owned = map_bounds(&prefix, start, end);
        if raw_range_empty(&owned.0, &owned.1) {
            return Ok(Vec::new());
        }
        let (rs, re) = bounds_ref(&owned);
        let rows = self.raw.scan(rs, re, forward)?;
        let plen = prefix.len();
        Ok(rows
            .into_iter()
            .map(|pair| KvPair {
                key: pair.key[plen..].to_vec(),
                value: pair.value,
            })
            .collect())
    }

    /// The raw engine range holding `dir`'s data for `start <= k < end`
    /// (bounds over the within-directory key part): the resolved prefix
    /// plus the raw start/end byte bounds, or `Ok(None)` when `dir` does
    /// not exist or the bound pair names no keys.
    ///
    /// The seam for backends that stream a lazy cursor over the engine's
    /// raw range (one page or one reseek at a time) instead of
    /// [`scan`](Self::scan)'s materialized merge. The raw range is
    /// `[start, end)` in the engine's whole keyspace; the keys a cursor
    /// yields there carry the prefix, which the caller strips
    /// (`prefix.len()` bytes) to get the within-directory key.
    pub fn data_bounds(
        &self,
        dir: &[&[u8]],
        start: Bound<&[u8]>,
        end: Bound<&[u8]>,
    ) -> Result<Option<DataBounds>, FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir)? else {
            return Ok(None);
        };
        Ok(map_data_bounds(&prefix, start, end))
    }

    /// Set `key` within `dir`, allocating `dir` (and any missing
    /// ancestor, and the anchor) if needed.
    pub fn set(
        &mut self,
        dir: &[&[u8]],
        key: &[u8],
        value: &[u8],
    ) -> Result<(), FlatError<R::Error>> {
        let prefix = self.allocate_dir(dir)?;
        let mut raw_key = prefix;
        raw_key.extend_from_slice(key);
        self.raw.insert(&raw_key, value)?;
        Ok(())
    }

    /// Delete `key` within `dir` (a no-op if the directory or the key
    /// does not exist).
    pub fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir)? else {
            return Ok(());
        };
        let mut raw_key = prefix;
        raw_key.extend_from_slice(key);
        self.raw.delete(&raw_key)?;
        Ok(())
    }

    /// Clear `start <= k < end` within `dir` (a no-op if the directory
    /// does not exist).
    pub fn clear_range(
        &mut self,
        dir: &[&[u8]],
        start: Bound<&[u8]>,
        end: Bound<&[u8]>,
    ) -> Result<(), FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir)? else {
            return Ok(());
        };
        let owned = map_bounds(&prefix, start, end);
        if raw_range_empty(&owned.0, &owned.1) {
            return Ok(());
        }
        let (rs, re) = bounds_ref(&owned);
        self.raw.clear_range(rs, re)?;
        Ok(())
    }

    // -- directory navigation ----------------------------------------------

    /// The immediate child segment names under `dir`, sorted ascending.
    /// A missing directory yields an empty list.
    pub fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        ops::check_version_read(&self.raw)?;
        let Some(prefix) = ops::find(&self.raw, &Self::layer_path(dir))? else {
            return Ok(Vec::new());
        };
        let names = ops::list_children(&self.raw, &prefix)?;
        Ok(names.into_iter().map(|s| s.into_bytes()).collect())
    }

    /// Whether `dir` exists. The fasm root `[]` exists iff its anchor
    /// node has been created (the store has been written); any other
    /// directory exists iff its node row is present — a directory with
    /// zero data keys still exists.
    pub fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        ops::check_version_read(&self.raw)?;
        Ok(ops::find(&self.raw, &Self::layer_path(dir))?.is_some())
    }

    /// Remove `dir` recursively: its subdirectories (node rows and data)
    /// and its own key data. `Ok(true)` if it existed, `Ok(false)`
    /// otherwise. The root is not removable.
    pub fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        if dir.is_empty() {
            // The fasm root maps to the layer's anchor directory — a
            // real node. Removing it would strand every directory under
            // it; the layer's own empty-path refusal is a second,
            // unreachable barrier.
            return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
        }
        ops::check_version_read(&self.raw)?;
        ops::remove_dir(&mut self.raw, &Self::layer_path(dir))
    }
}

/// The flat directory layout over an asynchronous raw byte view.
///
/// Mirrors [`FlatEngine`] over [`AsyncRawKv`] so asynchronous backends share
/// the exact FoundationDB `DirectoryLayer` layout, tuple encoding, HCA window
/// rules, and error contract without copying the database into memory.
pub struct AsyncFlatEngine<R: AsyncRawKv> {
    raw: R,
}

impl<R: AsyncRawKv> AsyncFlatEngine<R> {
    /// Wrap an asynchronous raw view.
    pub fn new(raw: R) -> Self {
        Self { raw }
    }

    /// The underlying view.
    pub fn raw(&self) -> &R {
        &self.raw
    }

    /// The mutable underlying view.
    pub fn raw_mut(&mut self) -> &mut R {
        &mut self.raw
    }

    /// Consume the engine and return its underlying view.
    pub fn into_raw(self) -> R {
        self.raw
    }

    fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
        let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
        v.push(ROOT_PATH_SEGMENT.as_bytes());
        v.extend_from_slice(dir);
        v
    }

    /// Resolve `dir` to its allocated prefix.
    ///
    /// Returns `Ok(None)` when the store is fresh or `dir` does not exist.
    pub async fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        ops::check_version_read_async(&self.raw).await?;
        let path = Self::layer_path(dir);
        ops::find_async(&self.raw, &path).await
    }

    /// Resolve `dir`, allocating any missing directories (and the anchor and
    /// version row on a fresh store) along the path.
    pub async fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        let path = Self::layer_path(dir);
        let mut rng = ThreadRngSource;
        ops::create_or_open_async(&mut self.raw, &path, true, &mut rng)
            .await
            .map(|p| p.expect("create_or_open_async with creation returns Some"))
    }

    /// Get `key` within `dir`. A missing directory yields `Ok(None)`.
    pub async fn get(
        &self,
        dir: &[&[u8]],
        key: &[u8],
    ) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir).await? else {
            return Ok(None);
        };
        let mut raw_key = prefix;
        raw_key.extend_from_slice(key);
        Ok(self.raw.get(&raw_key).await?)
    }

    /// Check whether `key` exists within `dir`. A missing directory yields
    /// `Ok(false)`.
    pub async fn exists(&self, dir: &[&[u8]], key: &[u8]) -> Result<bool, FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir).await? else {
            return Ok(false);
        };
        let mut raw_key = prefix;
        raw_key.extend_from_slice(key);
        Ok(self.raw.exists(&raw_key).await?)
    }

    /// Scan within `dir` between `start` and `end`, ascending or descending.
    /// A missing directory yields no rows.
    pub async fn scan(
        &self,
        dir: &[&[u8]],
        start: Bound<&[u8]>,
        end: Bound<&[u8]>,
        forward: bool,
    ) -> Result<Vec<KvPair>, FlatError<R::Error>> {
        let Some(bounds) = self.data_bounds(dir, start, end).await? else {
            return Ok(Vec::new());
        };
        let owned = (bounds.start, bounds.end);
        let (rs, re) = bounds_ref(&owned);
        let rows = self.raw.scan(rs, re, forward, None).await?;
        let plen = bounds.prefix.len();
        Ok(rows
            .into_iter()
            .map(|pair| KvPair {
                key: pair.key[plen..].to_vec(),
                value: pair.value,
            })
            .collect())
    }

    /// Resolve `dir` and map within-directory bounds to raw engine bounds.
    pub async fn data_bounds(
        &self,
        dir: &[&[u8]],
        start: Bound<&[u8]>,
        end: Bound<&[u8]>,
    ) -> Result<Option<DataBounds>, FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir).await? else {
            return Ok(None);
        };
        Ok(map_data_bounds(&prefix, start, end))
    }

    /// Set `key` within `dir`, allocating `dir` and any missing ancestors if
    /// needed.
    pub async fn set(
        &mut self,
        dir: &[&[u8]],
        key: &[u8],
        value: &[u8],
    ) -> Result<(), FlatError<R::Error>> {
        let prefix = self.allocate_dir(dir).await?;
        let mut raw_key = prefix;
        raw_key.extend_from_slice(key);
        self.raw.insert(&raw_key, value).await?;
        Ok(())
    }

    /// Delete `key` within `dir` (a no-op if the directory or key is absent).
    pub async fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
        let Some(prefix) = self.prefix_of(dir).await? else {
            return Ok(());
        };
        let mut raw_key = prefix;
        raw_key.extend_from_slice(key);
        self.raw.delete(&raw_key).await?;
        Ok(())
    }

    /// Clear `start <= k < end` within `dir` (a no-op if `dir` does not exist).
    pub async fn clear_range(
        &mut self,
        dir: &[&[u8]],
        start: Bound<&[u8]>,
        end: Bound<&[u8]>,
    ) -> Result<(), FlatError<R::Error>> {
        let Some(bounds) = self.data_bounds(dir, start, end).await? else {
            return Ok(());
        };
        let owned = (bounds.start, bounds.end);
        let (rs, re) = bounds_ref(&owned);
        self.raw.clear_range(rs, re).await?;
        Ok(())
    }

    /// List the immediate child segment names under `dir`, sorted ascending.
    pub async fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        ops::check_version_read_async(&self.raw).await?;
        let path = Self::layer_path(dir);
        let Some(prefix) = ops::find_async(&self.raw, &path).await? else {
            return Ok(Vec::new());
        };
        let names = ops::list_children_async(&self.raw, &prefix).await?;
        Ok(names.into_iter().map(|s| s.into_bytes()).collect())
    }

    /// Whether `dir` exists.
    pub async fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        ops::check_version_read_async(&self.raw).await?;
        let path = Self::layer_path(dir);
        Ok(ops::find_async(&self.raw, &path).await?.is_some())
    }

    /// Remove `dir` recursively: its subdirectories and its own key data.
    pub async fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
        validate_dir(dir).map_err(FlatError::Key)?;
        if dir.is_empty() {
            return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
        }
        ops::check_version_read_async(&self.raw).await?;
        let path = Self::layer_path(dir);
        ops::remove_dir_async(&mut self.raw, &path).await
    }
}

/// Map within-directory key bounds onto the raw engine range under an already
/// resolved directory `prefix`, returning `None` when the range is empty.
pub fn map_data_bounds(
    prefix: &[u8],
    start: Bound<&[u8]>,
    end: Bound<&[u8]>,
) -> Option<DataBounds> {
    let (rs, re) = map_bounds(prefix, start, end);
    if raw_range_empty(&rs, &re) {
        return None;
    }
    Some(DataBounds {
        prefix: prefix.to_vec(),
        start: rs,
        end: re,
    })
}

/// The raw engine range of one directory's data: the resolved prefix and
/// the raw byte bounds over the engine's whole keyspace. The start bound
/// carries its own inclusion (`Included`/`Excluded`); the end bound is
/// always `Excluded`. Cursor-yielding keys carry the prefix; strip
/// `prefix.len()` bytes to get the within-directory key.
pub struct DataBounds {
    /// The directory's allocated prefix.
    pub prefix: Vec<u8>,
    /// Raw start bound.
    pub start: Bound<Vec<u8>>,
    /// Raw end bound, exclusive.
    pub end: Bound<Vec<u8>>,
}

impl core::fmt::Debug for DataBounds {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // Lengths only: a `Debug` panic line must not dump the raw bound
        // bytes, which embed the key material of a live directory.
        f.debug_struct("DataBounds")
            .field("prefix_len", &self.prefix.len())
            .field("start", &bound_len(&self.start))
            .field("end", &bound_len(&self.end))
            .finish()
    }
}

fn bound_len(b: &Bound<Vec<u8>>) -> String {
    match b {
        Bound::Unbounded => "unbounded".to_owned(),
        Bound::Included(v) => format!("incl({} bytes)", v.len()),
        Bound::Excluded(v) => format!("excl({} bytes)", v.len()),
    }
}

/// Borrow the owned bounds of a mapped range as slice bounds, for
/// [`RawKv::scan`]/[`RawKv::clear_range`].
fn bounds_ref(b: &(Bound<Vec<u8>>, Bound<Vec<u8>>)) -> (Bound<&[u8]>, Bound<&[u8]>) {
    (bound_ref(&b.0), bound_ref(&b.1))
}

fn bound_ref(b: &Bound<Vec<u8>>) -> Bound<&[u8]> {
    match b {
        Bound::Unbounded => Bound::Unbounded,
        Bound::Included(v) => Bound::Included(v.as_slice()),
        Bound::Excluded(v) => Bound::Excluded(v.as_slice()),
    }
}

/// The exclusive raw end of `prefix`'s data region.
///
/// [`data_region`] returns a `Bound`; this is its `Excluded` byte vector,
/// for callers that need the owned form.
fn data_end_exclusive(prefix: &[u8]) -> Vec<u8> {
    match data_region(prefix).1 {
        Bound::Excluded(b) => b,
        _ => unreachable!("data_region end is always Excluded"),
    }
}

/// Map key-part bounds onto the raw range under `prefix`.
///
/// Within one directory the mapping `prefix ‖ k` is monotone, so the raw
/// range stays inside the directory's data region:
///
/// - start `Included(k)`  -> raw `Included(prefix ‖ k)`
/// - start `Excluded(k)`  -> raw `Excluded(prefix ‖ k)`
/// - start unbounded      -> raw `Included(prefix)` (the region start: the
///   directory's empty key sits at the prefix itself)
/// - end `Excluded(k)`    -> raw `Excluded(prefix ‖ k)`
/// - end `Included(k)`    -> raw `Excluded(prefix ‖ k ‖ [0x00])`:
///   `prefix ‖ k ‖ [0x00]` is the raw lexicographic immediate successor of
///   the key's raw form (a byte string's smallest greater byte string is
///   itself with a `0x00` appended), and it always lies inside the region
///   because it is an extension of `prefix`
/// - end unbounded        -> raw `Excluded` of the region end
///   (`next_prefix(prefix)`)
///
/// Note the two successor notions: the end bound uses the raw immediate
/// successor (`‖ [0x00]`), while region ends use the prefix-block successor
/// ([`crate::keyspace::next_prefix`]).
///
/// The range may name no keys (for example `Excluded(k)` to
/// `Excluded(k)`); callers check with [`raw_range_empty`].
fn map_bounds(
    prefix: &[u8],
    start: Bound<&[u8]>,
    end: Bound<&[u8]>,
) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
    let mk = |k: &[u8]| {
        let mut raw = prefix.to_vec();
        raw.extend_from_slice(k);
        raw
    };
    let rs = match start {
        Bound::Unbounded => Bound::Included(prefix.to_vec()),
        Bound::Included(k) => Bound::Included(mk(k)),
        Bound::Excluded(k) => Bound::Excluded(mk(k)),
    };
    let re = match end {
        Bound::Unbounded => Bound::Excluded(data_end_exclusive(prefix)),
        Bound::Excluded(k) => Bound::Excluded(mk(k)),
        Bound::Included(k) => {
            let mut raw = mk(k);
            raw.push(0x00);
            Bound::Excluded(raw)
        }
    };
    (rs, re)
}

/// Whether a raw `(start, end)` bound pair names no keys at all.
///
/// Only `Excluded` end bounds occur (see [`map_bounds`]), so the range is
/// empty exactly when the start bound reaches or passes the end bound.
fn raw_range_empty(start: &Bound<Vec<u8>>, end: &Bound<Vec<u8>>) -> bool {
    match (start, end) {
        (Bound::Included(a), Bound::Excluded(b)) => a >= b,
        (Bound::Excluded(a), Bound::Excluded(b)) => a >= b,
        (Bound::Unbounded, _) => false,
        (_, Bound::Unbounded) => false,
        _ => unreachable!("end bounds are always Excluded"),
    }
}

// -- test double -----------------------------------------------------------

/// An in-memory [`RawKv`] for testing the layout independently of any
/// backend. Shared by the flatdir module's test suites.
#[cfg(test)]
pub(crate) struct Mem {
    map: core::cell::RefCell<std::collections::BTreeMap<Vec<u8>, Vec<u8>>>,
}

#[cfg(test)]
impl Default for Mem {
    fn default() -> Self {
        Self {
            map: core::cell::RefCell::new(std::collections::BTreeMap::new()),
        }
    }
}

#[cfg(test)]
impl RawKv for Mem {
    type Error = std::convert::Infallible;

    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
        Ok(self.map.borrow().get(key).cloned())
    }

    fn scan(
        &self,
        start: Bound<&[u8]>,
        end: Bound<&[u8]>,
        forward: bool,
    ) -> Result<Vec<KvPair>, Self::Error> {
        let map = self.map.borrow();
        let rows: Vec<KvPair> = map
            .iter()
            .filter(|(k, _)| {
                let k = &k[..];
                let above = match start {
                    Bound::Unbounded => true,
                    Bound::Included(s) => k >= s,
                    Bound::Excluded(s) => k > s,
                };
                let below = match end {
                    Bound::Unbounded => true,
                    Bound::Excluded(e) => k < e,
                    Bound::Included(e) => k <= e,
                };
                above && below
            })
            .map(|(k, v)| KvPair {
                key: k.clone(),
                value: v.clone(),
            })
            .collect();
        if forward {
            Ok(rows)
        } else {
            Ok(rows.into_iter().rev().collect())
        }
    }

    fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
        self.map.borrow_mut().insert(key.to_vec(), value.to_vec());
        Ok(())
    }

    fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
        self.map.borrow_mut().remove(key);
        Ok(())
    }

    fn clear_range(&mut self, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Result<(), Self::Error> {
        let mut map = self.map.borrow_mut();
        let keys: Vec<Vec<u8>> = map
            .keys()
            .filter(|k| {
                let k = &k[..];
                let above = match start {
                    Bound::Unbounded => true,
                    Bound::Included(s) => k >= s,
                    Bound::Excluded(s) => k > s,
                };
                let below = match end {
                    Bound::Unbounded => true,
                    Bound::Excluded(e) => k < e,
                    Bound::Included(e) => k <= e,
                };
                above && below
            })
            .cloned()
            .collect();
        for k in keys {
            map.remove(&k);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::key::KeyError;

    fn engine() -> FlatEngine<Mem> {
        FlatEngine::new(Mem::default())
    }

    fn ok<T>(r: Result<T, FlatError<std::convert::Infallible>>) -> T {
        r.unwrap()
    }

    // -- fresh stores ------------------------------------------------------

    #[test]
    fn fresh_reads_return_empty_and_first_write_initialises() {
        let mut e = engine();
        assert_eq!(ok(e.prefix_of(&[])), None);
        assert_eq!(ok(e.get(&[], b"k")), None);
        assert!(ok(e.scan(&[], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
        assert!(ok(e.list_dirs(&[])).is_empty());
        assert!(!ok(e.dir_exists(&[])));
        // Removing from a fresh store is a miss, not an error.
        assert!(!ok(e.remove_dir(&[b"a"])));
        // The first write initialises the store lazily (version row,
        // anchor node).
        ok(e.set(&[], b"k", b"v"));
        assert!(ok(e.dir_exists(&[])));
        assert_eq!(ok(e.get(&[], b"k")), Some(b"v".to_vec()));
        // The version row is the layout's 12-byte 1.0.0.
        let version = e
            .raw()
            .map
            .borrow()
            .get(crate::flatdir::layout::VERSION_KEY)
            .cloned();
        assert_eq!(
            version,
            Some(crate::flatdir::layout::LAYOUT_VERSION.to_vec())
        );
    }

    /// A first write in a one-segment directory produces exactly nine
    /// raw rows: the version row, the anchor node's child and layer
    /// rows, the directory node's child and layer rows, the HCA
    /// counter row, two HCA recent rows, and the data row. The root
    /// node carries no layer row.
    #[test]
    fn a_first_set_produces_exactly_nine_raw_rows() {
        let mut e = engine();
        ok(e.set(&[b"a"], b"k", b"v"));
        let map = e.raw().map.borrow();
        assert_eq!(map.len(), 9, "unexpected raw rows: {map:?}");
    }

    // -- foreign stores ------------------------------------------------------

    #[test]
    fn reads_on_a_foreign_store_fail_closed() {
        // A version row this layout does not read (major = 2): every
        // operation fails with `Foreign` rather than answering over
        // someone else's data.
        let mut e = engine();
        let mut v = [0u8; 12];
        v[0..4].copy_from_slice(&2u32.to_le_bytes());
        e.raw_mut()
            .insert(crate::flatdir::layout::VERSION_KEY, &v)
            .unwrap();
        assert_eq!(e.prefix_of(&[]), Err(FlatError::Foreign));
        assert_eq!(e.get(&[], b"k"), Err(FlatError::Foreign));
        assert_eq!(
            e.scan(&[], Bound::Unbounded, Bound::Unbounded, true),
            Err(FlatError::Foreign)
        );
        assert!(matches!(
            e.data_bounds(&[], Bound::Unbounded, Bound::Unbounded),
            Err(FlatError::Foreign)
        ));
        assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
        assert_eq!(e.list_dirs(&[]), Err(FlatError::Foreign));
        assert_eq!(e.set(&[], b"k", b"v"), Err(FlatError::Foreign));
        assert_eq!(e.remove_dir(&[b"a"]), Err(FlatError::Foreign));
    }

    #[test]
    fn a_malformed_version_row_fails_closed() {
        // A short version value is not a version: fail closed.
        let mut e = engine();
        e.raw_mut()
            .insert(crate::flatdir::layout::VERSION_KEY, &[1, 0])
            .unwrap();
        assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
    }

    #[test]
    fn a_corrupt_node_value_is_corrupt_not_a_panic() {
        // A healthy store whose anchor child row's value is then flipped
        // to a non-packing byte string: the node walk reports `Corrupt`
        // rather than panicking.
        let mut e = engine();
        e.set(&[b"dir"], b"k", b"v").unwrap();
        // The anchor child row sits under the root node and is the only
        // row there tagged with INT(0) (0x14): the HCA and version rows
        // are tagged 0x01 (BYTES) and sort before it.
        let child_tag = crate::flatdir::layout::ROOT_NODE
            .iter()
            .copied()
            .chain(std::iter::once(0x14))
            .collect::<Vec<u8>>();
        let row_key = e
            .raw()
            .map
            .borrow()
            .iter()
            .find(|(k, _)| k.starts_with(&child_tag))
            .expect("the anchor child row")
            .0
            .clone();
        e.raw_mut()
            .map
            .borrow_mut()
            .insert(row_key, vec![0x99, 0x00]);
        assert_eq!(e.get(&[b"dir"], b"k"), Err(FlatError::Corrupt));
        assert_eq!(
            e.scan(&[b"dir"], Bound::Unbounded, Bound::Unbounded, true),
            Err(FlatError::Corrupt)
        );
        assert_eq!(e.remove_dir(&[b"dir"]), Err(FlatError::Corrupt));
    }

    // -- allocation ---------------------------------------------------------

    #[test]
    fn allocation_is_recursive_and_stable() {
        let mut e = engine();
        let p = ok(e.allocate_dir(&[b"a", b"b"]));
        // Re-resolving finds the same prefix (no new allocation).
        assert_eq!(ok(e.prefix_of(&[b"a", b"b"])), Some(p.clone()));
        // Siblings get different prefixes; the ancestor resolves too.
        let q = ok(e.allocate_dir(&[b"a", b"c"]));
        assert_ne!(p, q);
        assert!(ok(e.prefix_of(&[b"a"])).is_some());
        // Every allocated prefix starts in the packed-i64 band
        // (0x0c..=0x1c): never the meta (0xFE) or reserved (0xFF) region.
        let dirs: [[&[u8]; 2]; 2] = [[b"a" as &[u8], b"b"], [b"a" as &[u8], b"c"]];
        for dir in dirs {
            let p = ok(e.prefix_of(&dir)).unwrap();
            assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?}");
        }
    }

    #[test]
    fn many_allocations_stay_in_the_data_region() {
        // 300 directories (past the first HCA window advance): every
        // allocated prefix stays in the data region and every data key
        // lands outside the meta region.
        let mut e = engine();
        for i in 0..300u32 {
            let d = format!("d{i:03}").into_bytes();
            let d = [d.as_slice()];
            let p = ok(e.allocate_dir(&d));
            assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?} at {i}");
        }
    }

    #[test]
    fn resolve_missing_dir_is_none() {
        let mut e = engine();
        ok(e.set(&[], b"k", b"v"));
        assert_eq!(ok(e.prefix_of(&[b"nope"])), None);
        assert_eq!(ok(e.prefix_of(&[b"nope", b"deeper"])), None);
    }

    // -- data operations ----------------------------------------------------

    #[test]
    fn set_get_delete_round_trips_per_dir() {
        let mut e = engine();
        ok(e.set(&[b"asset", b"btc"], b"k", b"v"));
        assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), Some(b"v".to_vec()));
        // Same key, different directory: isolated.
        assert_eq!(ok(e.get(&[b"asset"], b"k")), None);
        assert_eq!(ok(e.get(&[b"btc"], b"k")), None);
        ok(e.delete(&[b"asset", b"btc"], b"k"));
        assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), None);
    }

    #[test]
    fn scan_orders_within_dir_only() {
        let mut e = engine();
        for k in [b"b", b"a", b"c"] {
            ok(e.set(&[b"d"], k, k));
            ok(e.set(&[b"other"], k, k));
        }
        let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true));
        let keys: Vec<Vec<u8>> = rows.iter().map(|p| p.key.clone()).collect();
        assert_eq!(keys, vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]);
        let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, false));
        assert_eq!(rows.first().unwrap().key, b"c".to_vec());
    }

    #[test]
    fn scan_bound_matrix() {
        let mut e = engine();
        for k in [b"a", b"b", b"c", b"\xff"] {
            ok(e.set(&[b"d"], k, b"v"));
        }
        let get = |s: core::ops::Bound<&[u8]>,
                   en: core::ops::Bound<&[u8]>,
                   e: &FlatEngine<Mem>|
         -> Vec<Vec<u8>> {
            ok(e.scan(&[b"d"], s, en, true))
                .into_iter()
                .map(|pair| pair.key)
                .collect()
        };
        assert_eq!(
            get(Bound::Included(b"b"), Bound::Excluded(b"c"), &e),
            vec![b"b".to_vec()]
        );
        assert_eq!(
            get(Bound::Excluded(b"b"), Bound::Included(b"c"), &e),
            vec![b"c".to_vec()]
        );
        assert_eq!(
            get(Bound::Excluded(&[0xFFu8]), Bound::Unbounded, &e),
            Vec::<Vec<u8>>::new()
        );
        assert_eq!(
            get(Bound::Unbounded, Bound::Included(&[0xFFu8]), &e),
            vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), vec![0xFF]]
        );
        assert_eq!(
            get(Bound::Included(&[0xFFu8]), Bound::Unbounded, &e),
            vec![vec![0xFF]]
        );
        // An Excluded bound at all-0xFF: the range is empty.
        assert_eq!(
            get(Bound::Excluded(&[0xFFu8]), Bound::Excluded(&[0xFFu8]), &e),
            Vec::<Vec<u8>>::new()
        );
    }

    #[test]
    fn clear_range_clears_within_dir_only() {
        let mut e = engine();
        for k in [b"a", b"b", b"c"] {
            ok(e.set(&[b"d"], k, b"v"));
            ok(e.set(&[b"e"], k, b"v"));
        }
        ok(e.clear_range(&[b"d"], Bound::Included(b"b"), Bound::Excluded(b"c")));
        assert_eq!(ok(e.get(&[b"d"], b"a")), Some(b"v".to_vec()));
        assert_eq!(ok(e.get(&[b"d"], b"b")), None);
        assert_eq!(ok(e.get(&[b"d"], b"c")), Some(b"v".to_vec()));
        assert_eq!(ok(e.get(&[b"e"], b"b")), Some(b"v".to_vec()));
        // Whole directory.
        ok(e.clear_range(&[b"d"], Bound::Unbounded, Bound::Unbounded));
        assert!(ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
        // The directory still exists (data-free directories are entities).
        assert!(ok(e.dir_exists(&[b"d"])));
    }

    // -- navigation ---------------------------------------------------------

    #[test]
    fn nav_list_exists_remove() {
        let mut e = engine();
        ok(e.set(&[b"a", b"1"], b"k", b"v"));
        ok(e.set(&[b"a", b"2"], b"k", b"v"));
        ok(e.set(&[b"b"], b"k", b"v"));
        assert_eq!(ok(e.list_dirs(&[])), vec![b"a".to_vec(), b"b".to_vec()]);
        assert_eq!(ok(e.list_dirs(&[b"a"])), vec![b"1".to_vec(), b"2".to_vec()]);
        assert!(ok(e.dir_exists(&[b"a"])));
        assert!(ok(e.dir_exists(&[b"a", b"1"])));
        assert!(!ok(e.dir_exists(&[b"a", b"3"])));
        // A directory with no data keys still exists.
        ok(e.allocate_dir(&[b"empty"]));
        assert!(ok(e.dir_exists(&[b"empty"])));
        assert!(ok(e.list_dirs(&[b"empty"])).is_empty());
        // Missing: empty list, not an error.
        assert!(ok(e.list_dirs(&[b"nope"])).is_empty());
        assert!(!ok(e.dir_exists(&[b"nope"])));
    }

    #[test]
    fn nav_remove_is_recursive() {
        let mut e = engine();
        ok(e.set(&[b"a", b"b", b"c"], b"k1", b"v1"));
        ok(e.set(&[b"a", b"b"], b"k2", b"v2"));
        ok(e.set(&[b"a", b"d"], b"k3", b"v3"));
        ok(e.set(&[b"z"], b"k4", b"v4"));
        // Remove the middle directory: b/c and b go, a/d stays.
        assert!(ok(e.remove_dir(&[b"a", b"b"])));
        assert_eq!(ok(e.get(&[b"a", b"b", b"c"], b"k1")), None);
        assert_eq!(ok(e.get(&[b"a", b"b"], b"k2")), None);
        assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), Some(b"v3".to_vec()));
        assert!(ok(e.dir_exists(&[b"a"])));
        assert!(!ok(e.dir_exists(&[b"a", b"b"])));
        // Removing a leaf directory removes it and its data.
        assert!(ok(e.remove_dir(&[b"a", b"d"])));
        assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), None);
        // Missing: false.
        assert!(!ok(e.remove_dir(&[b"a", b"b"])));
        // Unaffected directories keep their data.
        assert_eq!(ok(e.get(&[b"z"], b"k4")), Some(b"v4".to_vec()));
    }

    #[test]
    fn nav_root_is_not_removable() {
        let mut e = engine();
        ok(e.set(&[], b"k", b"v"));
        assert_eq!(
            e.remove_dir(&[]),
            Err(FlatError::Key(KeyError::RootNotRemovable))
        );
        // The root survived.
        assert!(ok(e.dir_exists(&[])));
    }

    #[test]
    fn nav_rejects_non_utf8() {
        let mut e = engine();
        let seg: &[u8] = b"\xFF\xFE";
        let bad = [seg];
        assert_eq!(
            e.list_dirs(&bad),
            Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
        );
        assert_eq!(
            e.remove_dir(&bad),
            Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
        );
    }

    #[test]
    fn remove_and_recreate_work() {
        // Removal leaves no trace that blocks re-creation: the HCA may
        // even re-claim the same candidate value (FDB semantics — the
        // allocator tracks windows, not used prefixes); what matters is
        // that the recreated directory is fully functional and no stale
        // row of the old one is read.
        let mut e = engine();
        ok(e.set(&[b"x"], b"k", b"v1"));
        let p1 = ok(e.prefix_of(&[b"x"])).unwrap();
        assert!(ok(e.remove_dir(&[b"x"])));
        assert!(!ok(e.dir_exists(&[b"x"])));
        assert_eq!(ok(e.get(&[b"x"], b"k")), None);
        ok(e.set(&[b"x"], b"k", b"v2"));
        let p2 = ok(e.prefix_of(&[b"x"])).unwrap();
        assert_eq!(ok(e.get(&[b"x"], b"k")), Some(b"v2".to_vec()));
        // If the allocator re-claimed the same prefix, the old data row
        // was cleared by the removal (same raw key, new value wins).
        if p1 == p2 {
            assert_eq!(
                ok(e.scan(&[b"x"], Bound::Unbounded, Bound::Unbounded, true)).len(),
                1
            );
        }
        // The store still validates as a whole layout.
        assert!(ops::validate(e.raw()).is_ok());
    }

    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    mod async_tests {
        use std::collections::BTreeMap;
        use std::sync::Mutex;

        use super::*;

        #[derive(Default)]
        struct AsyncMem {
            map: Mutex<BTreeMap<Vec<u8>, Vec<u8>>>,
        }

        impl AsyncRawKv for AsyncMem {
            type Error = std::convert::Infallible;

            async fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
                Ok(self.map.lock().unwrap().get(key).cloned())
            }

            async fn exists(&self, key: &[u8]) -> Result<bool, Self::Error> {
                Ok(self.map.lock().unwrap().contains_key(key))
            }

            async fn scan(
                &self,
                start: Bound<&[u8]>,
                end: Bound<&[u8]>,
                forward: bool,
                limit: Option<usize>,
            ) -> Result<Vec<KvPair>, Self::Error> {
                if limit == Some(0) {
                    return Ok(Vec::new());
                }
                let map = self.map.lock().unwrap();
                let mut rows: Vec<KvPair> = map
                    .iter()
                    .filter(|(k, _)| {
                        let k = k.as_slice();
                        let above = match start {
                            Bound::Unbounded => true,
                            Bound::Included(s) => k >= s,
                            Bound::Excluded(s) => k > s,
                        };
                        let below = match end {
                            Bound::Unbounded => true,
                            Bound::Excluded(e) => k < e,
                            Bound::Included(e) => k <= e,
                        };
                        above && below
                    })
                    .map(|(k, v)| KvPair {
                        key: k.clone(),
                        value: v.clone(),
                    })
                    .collect();
                if !forward {
                    rows.reverse();
                }
                if let Some(limit) = limit {
                    rows.truncate(limit);
                }
                Ok(rows)
            }

            async fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
                self.map
                    .lock()
                    .unwrap()
                    .insert(key.to_vec(), value.to_vec());
                Ok(())
            }

            async fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
                self.map.lock().unwrap().remove(key);
                Ok(())
            }

            async fn clear_range(
                &mut self,
                start: Bound<&[u8]>,
                end: Bound<&[u8]>,
            ) -> Result<(), Self::Error> {
                let mut map = self.map.lock().unwrap();
                let keys: Vec<Vec<u8>> = map
                    .keys()
                    .filter(|k| {
                        let k = k.as_slice();
                        let above = match start {
                            Bound::Unbounded => true,
                            Bound::Included(s) => k >= s,
                            Bound::Excluded(s) => k > s,
                        };
                        let below = match end {
                            Bound::Unbounded => true,
                            Bound::Excluded(e) => k < e,
                            Bound::Included(e) => k <= e,
                        };
                        above && below
                    })
                    .cloned()
                    .collect();
                for k in keys {
                    map.remove(&k);
                }
                Ok(())
            }
        }

        fn assert_send<T: Send>(_: &T) {}

        #[tokio::test]
        async fn async_engine_futures_are_send_and_round_trip() {
            let mut e = AsyncFlatEngine::new(AsyncMem::default());
            {
                let fut = e.set(&[b"a", b"b"], b"k1", b"v1");
                assert_send(&fut);
                fut.await.unwrap();
            }
            {
                let fut = e.get(&[b"a", b"b"], b"k1");
                assert_send(&fut);
                assert_eq!(fut.await.unwrap(), Some(b"v1".to_vec()));
            }
            assert!(e.exists(&[b"a", b"b"], b"k1").await.unwrap());
            assert!(!e.exists(&[b"a", b"b"], b"missing").await.unwrap());
            assert!(!e.exists(&[b"missing"], b"k1").await.unwrap());
            assert_eq!(e.list_dirs(&[]).await.unwrap(), vec![b"a".to_vec()]);
            assert_eq!(e.list_dirs(&[b"a"]).await.unwrap(), vec![b"b".to_vec()]);

            assert!(e.remove_dir(&[b"a"]).await.unwrap());
            assert!(!e.dir_exists(&[b"a"]).await.unwrap());
            assert!(!e.dir_exists(&[b"a", b"b"]).await.unwrap());
            assert_eq!(e.get(&[b"a", b"b"], b"k1").await.unwrap(), None);
            assert!(ops::validate_async(e.raw()).await.is_ok());
        }

        #[tokio::test]
        async fn async_engine_handles_many_allocations_foreign_and_clear_range() {
            let mut e = AsyncFlatEngine::new(AsyncMem::default());
            for i in 0..130u32 {
                let d = format!("d{i:03}").into_bytes();
                let p = e.allocate_dir(&[d.as_slice()]).await.unwrap();
                assert!((0x0c..=0x1c).contains(&p[0]));
            }
            e.set(&[b"d000"], b"a", b"1").await.unwrap();
            e.set(&[b"d000"], b"b", b"2").await.unwrap();
            e.set(&[b"d000"], b"c", b"3").await.unwrap();
            e.clear_range(&[b"d000"], Bound::Included(b"b"), Bound::Excluded(b"c"))
                .await
                .unwrap();
            let rows = e
                .scan(&[b"d000"], Bound::Unbounded, Bound::Unbounded, false)
                .await
                .unwrap();
            let keys: Vec<Vec<u8>> = rows.into_iter().map(|p| p.key).collect();
            assert_eq!(keys, vec![b"c".to_vec(), b"a".to_vec()]);
            assert!(ops::validate_async(e.raw()).await.is_ok());

            let mut foreign = AsyncFlatEngine::new(AsyncMem::default());
            let mut v = [0u8; 12];
            v[0..4].copy_from_slice(&2u32.to_le_bytes());
            foreign
                .raw_mut()
                .insert(crate::flatdir::layout::VERSION_KEY, &v)
                .await
                .unwrap();
            assert_eq!(foreign.get(&[], b"k").await, Err(FlatError::Foreign));
            assert_eq!(foreign.set(&[], b"k", b"v").await, Err(FlatError::Foreign));
            assert_eq!(
                foreign.remove_dir(&[]).await,
                Err(FlatError::Key(KeyError::RootNotRemovable))
            );
        }

        #[tokio::test]
        async fn sync_and_async_flatdir_ops_produce_byte_identical_raw_maps() {
            use crate::flatdir::hca::Lcg;

            let mut sync_raw = Mem::default();
            let mut async_raw = AsyncMem::default();
            let mut sync_rng = Lcg::new(42);
            let mut async_rng = Lcg::new(42);

            // Build nested directories and cross the first HCA window advance (32).
            let mut paths: Vec<Vec<Vec<u8>>> = vec![
                vec![b"alpha".to_vec(), b"beta".to_vec(), b"gamma".to_vec()],
                vec![b"alpha".to_vec(), b"delta".to_vec()],
                vec![b"nested".to_vec(), b"one".to_vec(), b"two".to_vec()],
            ];
            for i in 0..40u32 {
                paths.push(vec![format!("dir-{i:02}").into_bytes()]);
            }

            let to_layer_path = |segs: &[Vec<u8>]| -> Vec<Vec<u8>> {
                let mut full = Vec::with_capacity(segs.len() + 1);
                full.push(ROOT_PATH_SEGMENT.as_bytes().to_vec());
                full.extend_from_slice(segs);
                full
            };

            for segs in &paths {
                let full = to_layer_path(segs);
                let refs: Vec<&[u8]> = full.iter().map(Vec::as_slice).collect();
                let sync_prefix = ops::create_or_open(&mut sync_raw, &refs, true, &mut sync_rng)
                    .unwrap()
                    .unwrap();
                let async_prefix =
                    ops::create_or_open_async(&mut async_raw, &refs, true, &mut async_rng)
                        .await
                        .unwrap()
                        .unwrap();
                assert_eq!(sync_prefix, async_prefix);

                // Write a data row under each allocated directory.
                let mut data_key = sync_prefix;
                data_key.extend_from_slice(b"payload");
                sync_raw.insert(&data_key, b"value").unwrap();
                async_raw.insert(&data_key, b"value").await.unwrap();
            }

            assert_eq!(
                *sync_raw.map.borrow(),
                *async_raw.map.lock().unwrap(),
                "raw maps must match byte-for-byte after nested creates and HCA window advance"
            );

            // Remove nested and leaf subtrees in the same order.
            for target in [
                vec![b"alpha".to_vec()],
                vec![b"nested".to_vec(), b"one".to_vec()],
                vec![b"dir-15".to_vec()],
                vec![b"missing".to_vec()],
            ] {
                let full = to_layer_path(&target);
                let refs: Vec<&[u8]> = full.iter().map(Vec::as_slice).collect();
                let sync_removed = ops::remove_dir(&mut sync_raw, &refs).unwrap();
                let async_removed = ops::remove_dir_async(&mut async_raw, &refs).await.unwrap();
                assert_eq!(sync_removed, async_removed);
            }

            assert_eq!(
                *sync_raw.map.borrow(),
                *async_raw.map.lock().unwrap(),
                "raw maps must match byte-for-byte after recursive removals"
            );

            // Recreate a removed nested path and verify identical state and validation.
            let recreate = to_layer_path(&[b"alpha".to_vec(), b"beta".to_vec()]);
            let refs: Vec<&[u8]> = recreate.iter().map(Vec::as_slice).collect();
            let sp = ops::create_or_open(&mut sync_raw, &refs, true, &mut sync_rng).unwrap();
            let ap = ops::create_or_open_async(&mut async_raw, &refs, true, &mut async_rng)
                .await
                .unwrap();
            assert_eq!(sp, ap);
            assert_eq!(*sync_raw.map.borrow(), *async_raw.map.lock().unwrap());
            assert_eq!(
                ops::validate(&sync_raw).unwrap(),
                ops::validate_async(&async_raw).await.unwrap()
            );
        }
    }
}