Skip to main content

fasm_storage/
flatengine.rs

1//! The flat directory layout engines over [`RawKv`] and [`AsyncRawKv`] views.
2//!
3//! One layout, written and tested once here; the synchronous flat backends
4//! (btreemap, redb) implement [`RawKv`] over their transaction views and
5//! route every operation through [`FlatEngine`], while asynchronous flat
6//! backends (IndexedDB) implement [`AsyncRawKv`] and route through
7//! [`AsyncFlatEngine`]. FDB does not use these — it uses FDB's native
8//! directory layer over the same row layouts (the [`crate::flatdir`] module
9//! documents the shared layouts).
10//!
11//! The engine's layout is a verbatim port of FoundationDB's
12//! `DirectoryLayer` (see [`crate::flatdir`]): a node tree of allocated
13//! prefixes (packed `i64`s from the High Contention Allocator), a version
14//! row, and HCA counter/recent rows, all under the `0xFE` node region.
15//! Data keys are `prefix ‖ key` in the `0x00`–`0xFD` region; `0xFF` is
16//! reserved.
17//!
18//! Stores are opened lazily: a fresh store (no version row) answers
19//! empty on reads, and the first create writes the version row. A store
20//! whose version row this layout does not read fails every operation
21//! with [`FlatError::Foreign`].
22
23use core::ops::Bound;
24use rand::rng as thread_rng;
25
26use crate::flatdir::hca::ThreadRngSource;
27use crate::flatdir::layout::{ROOT_PATH_SEGMENT, data_region};
28use crate::flatdir::ops;
29use crate::key::validate_dir;
30use crate::rawkv::{AsyncRawKv, RawKv};
31use crate::stream::KvPair;
32
33/// Re-exported for the backends' error types (defined with the layout
34/// machinery it guards).
35pub use crate::flatdir::error::FlatError;
36
37/// The flat directory layout over a raw byte view.
38///
39/// Not itself a [`KvStore`](crate::KvStore): it has no async boundary and
40/// no engine error identity. The flat backends wrap it.
41///
42/// Directory paths are the fasm form (`&[&[u8]]`, UTF-8, validated with
43/// [`validate_dir`]); each fasm directory maps to the layer path
44/// `[ROOT_PATH_SEGMENT] ‖ dir`, so the fasm root `[]` is the layer's
45/// anchor directory — a real, allocated node, never the layer root.
46pub struct FlatEngine<R: RawKv> {
47    raw: R,
48}
49
50impl<R: RawKv> FlatEngine<R> {
51    /// Wrap a raw view.
52    pub fn new(raw: R) -> Self {
53        Self { raw }
54    }
55
56    /// The underlying view, for backends that need to reach it directly
57    /// (streaming, raw-handle accessors, the open-time probe).
58    pub fn raw(&self) -> &R {
59        &self.raw
60    }
61
62    /// The mutable underlying view.
63    pub fn raw_mut(&mut self) -> &mut R {
64        &mut self.raw
65    }
66
67    /// The layer path for a fasm directory: the anchor segment plus the
68    /// directory's segments (already UTF-8-validated by the caller).
69    fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
70        let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
71        v.push(ROOT_PATH_SEGMENT.as_bytes());
72        v.extend_from_slice(dir);
73        v
74    }
75
76    // -- directory resolution ---------------------------------------------
77
78    /// Resolve `dir` to its allocated prefix.
79    ///
80    /// `Ok(None)` when the store is fresh or the directory does not
81    /// exist. `Err(FlatError::Foreign)` when the store's version row is
82    /// one this layout does not read; `Err(FlatError::Corrupt)` when a
83    /// node row's value is malformed. Write operations use
84    /// [`allocate_dir`](Self::allocate_dir) instead.
85    pub fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
86        validate_dir(dir).map_err(FlatError::Key)?;
87        ops::check_version_read(&self.raw)?;
88        ops::find(&self.raw, &Self::layer_path(dir))
89    }
90
91    /// Resolve `dir`, allocating every missing directory (and only
92    /// those) along the way — the anchor included, which is what writes
93    /// the version row on a fresh store. Returns the resolved prefix.
94    ///
95    /// Creation is recursive on the *path*: creating `[a, b]` creates
96    /// both `a` and `b` (lazy parent creation, verbatim from the layer).
97    /// Each new node takes a candidate from the HCA; the allocation and
98    /// the node rows land in the same transaction view, so a rolled-back
99    /// creation leaves no trace. Idempotent: an existing directory
100    /// resolves to its prefix without a new allocation.
101    pub fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
102        validate_dir(dir).map_err(FlatError::Key)?;
103        let mut rng = thread_rng();
104        ops::create_or_open(&mut self.raw, &Self::layer_path(dir), true, &mut rng)
105            .map(|p| p.expect("create_or_open with creation returns Some"))
106    }
107
108    // -- data operations ----------------------------------------------------
109
110    /// Get `key` within `dir`. A missing directory yields `Ok(None)`.
111    pub fn get(&self, dir: &[&[u8]], key: &[u8]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
112        let Some(prefix) = self.prefix_of(dir)? else {
113            return Ok(None);
114        };
115        let mut raw_key = prefix;
116        raw_key.extend_from_slice(key);
117        Ok(self.raw.get(&raw_key)?)
118    }
119
120    /// Scan within `dir` between `start` and `end` (bounds over the key
121    /// part), ascending or descending. A missing directory yields no rows.
122    /// The returned keys are the within-directory keys.
123    pub fn scan(
124        &self,
125        dir: &[&[u8]],
126        start: Bound<&[u8]>,
127        end: Bound<&[u8]>,
128        forward: bool,
129    ) -> Result<Vec<KvPair>, FlatError<R::Error>> {
130        let Some(prefix) = self.prefix_of(dir)? else {
131            return Ok(Vec::new());
132        };
133        let owned = map_bounds(&prefix, start, end);
134        if raw_range_empty(&owned.0, &owned.1) {
135            return Ok(Vec::new());
136        }
137        let (rs, re) = bounds_ref(&owned);
138        let rows = self.raw.scan(rs, re, forward)?;
139        let plen = prefix.len();
140        Ok(rows
141            .into_iter()
142            .map(|pair| KvPair {
143                key: pair.key[plen..].to_vec(),
144                value: pair.value,
145            })
146            .collect())
147    }
148
149    /// The raw engine range holding `dir`'s data for `start <= k < end`
150    /// (bounds over the within-directory key part): the resolved prefix
151    /// plus the raw start/end byte bounds, or `Ok(None)` when `dir` does
152    /// not exist or the bound pair names no keys.
153    ///
154    /// The seam for backends that stream a lazy cursor over the engine's
155    /// raw range (one page or one reseek at a time) instead of
156    /// [`scan`](Self::scan)'s materialized merge. The raw range is
157    /// `[start, end)` in the engine's whole keyspace; the keys a cursor
158    /// yields there carry the prefix, which the caller strips
159    /// (`prefix.len()` bytes) to get the within-directory key.
160    pub fn data_bounds(
161        &self,
162        dir: &[&[u8]],
163        start: Bound<&[u8]>,
164        end: Bound<&[u8]>,
165    ) -> Result<Option<DataBounds>, FlatError<R::Error>> {
166        let Some(prefix) = self.prefix_of(dir)? else {
167            return Ok(None);
168        };
169        Ok(map_data_bounds(&prefix, start, end))
170    }
171
172    /// Set `key` within `dir`, allocating `dir` (and any missing
173    /// ancestor, and the anchor) if needed.
174    pub fn set(
175        &mut self,
176        dir: &[&[u8]],
177        key: &[u8],
178        value: &[u8],
179    ) -> Result<(), FlatError<R::Error>> {
180        let prefix = self.allocate_dir(dir)?;
181        let mut raw_key = prefix;
182        raw_key.extend_from_slice(key);
183        self.raw.insert(&raw_key, value)?;
184        Ok(())
185    }
186
187    /// Delete `key` within `dir` (a no-op if the directory or the key
188    /// does not exist).
189    pub fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
190        let Some(prefix) = self.prefix_of(dir)? else {
191            return Ok(());
192        };
193        let mut raw_key = prefix;
194        raw_key.extend_from_slice(key);
195        self.raw.delete(&raw_key)?;
196        Ok(())
197    }
198
199    /// Clear `start <= k < end` within `dir` (a no-op if the directory
200    /// does not exist).
201    pub fn clear_range(
202        &mut self,
203        dir: &[&[u8]],
204        start: Bound<&[u8]>,
205        end: Bound<&[u8]>,
206    ) -> Result<(), FlatError<R::Error>> {
207        let Some(prefix) = self.prefix_of(dir)? else {
208            return Ok(());
209        };
210        let owned = map_bounds(&prefix, start, end);
211        if raw_range_empty(&owned.0, &owned.1) {
212            return Ok(());
213        }
214        let (rs, re) = bounds_ref(&owned);
215        self.raw.clear_range(rs, re)?;
216        Ok(())
217    }
218
219    // -- directory navigation ----------------------------------------------
220
221    /// The immediate child segment names under `dir`, sorted ascending.
222    /// A missing directory yields an empty list.
223    pub fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
224        validate_dir(dir).map_err(FlatError::Key)?;
225        ops::check_version_read(&self.raw)?;
226        let Some(prefix) = ops::find(&self.raw, &Self::layer_path(dir))? else {
227            return Ok(Vec::new());
228        };
229        let names = ops::list_children(&self.raw, &prefix)?;
230        Ok(names.into_iter().map(|s| s.into_bytes()).collect())
231    }
232
233    /// Whether `dir` exists. The fasm root `[]` exists iff its anchor
234    /// node has been created (the store has been written); any other
235    /// directory exists iff its node row is present — a directory with
236    /// zero data keys still exists.
237    pub fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
238        validate_dir(dir).map_err(FlatError::Key)?;
239        ops::check_version_read(&self.raw)?;
240        Ok(ops::find(&self.raw, &Self::layer_path(dir))?.is_some())
241    }
242
243    /// Remove `dir` recursively: its subdirectories (node rows and data)
244    /// and its own key data. `Ok(true)` if it existed, `Ok(false)`
245    /// otherwise. The root is not removable.
246    pub fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
247        validate_dir(dir).map_err(FlatError::Key)?;
248        if dir.is_empty() {
249            // The fasm root maps to the layer's anchor directory — a
250            // real node. Removing it would strand every directory under
251            // it; the layer's own empty-path refusal is a second,
252            // unreachable barrier.
253            return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
254        }
255        ops::check_version_read(&self.raw)?;
256        ops::remove_dir(&mut self.raw, &Self::layer_path(dir))
257    }
258}
259
260/// The flat directory layout over an asynchronous raw byte view.
261///
262/// Mirrors [`FlatEngine`] over [`AsyncRawKv`] so asynchronous backends share
263/// the exact FoundationDB `DirectoryLayer` layout, tuple encoding, HCA window
264/// rules, and error contract without copying the database into memory.
265pub struct AsyncFlatEngine<R: AsyncRawKv> {
266    raw: R,
267}
268
269impl<R: AsyncRawKv> AsyncFlatEngine<R> {
270    /// Wrap an asynchronous raw view.
271    pub fn new(raw: R) -> Self {
272        Self { raw }
273    }
274
275    /// The underlying view.
276    pub fn raw(&self) -> &R {
277        &self.raw
278    }
279
280    /// The mutable underlying view.
281    pub fn raw_mut(&mut self) -> &mut R {
282        &mut self.raw
283    }
284
285    /// Consume the engine and return its underlying view.
286    pub fn into_raw(self) -> R {
287        self.raw
288    }
289
290    fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
291        let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
292        v.push(ROOT_PATH_SEGMENT.as_bytes());
293        v.extend_from_slice(dir);
294        v
295    }
296
297    /// Resolve `dir` to its allocated prefix.
298    ///
299    /// Returns `Ok(None)` when the store is fresh or `dir` does not exist.
300    pub async fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
301        validate_dir(dir).map_err(FlatError::Key)?;
302        ops::check_version_read_async(&self.raw).await?;
303        let path = Self::layer_path(dir);
304        ops::find_async(&self.raw, &path).await
305    }
306
307    /// Resolve `dir`, allocating any missing directories (and the anchor and
308    /// version row on a fresh store) along the path.
309    pub async fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
310        validate_dir(dir).map_err(FlatError::Key)?;
311        let path = Self::layer_path(dir);
312        let mut rng = ThreadRngSource;
313        ops::create_or_open_async(&mut self.raw, &path, true, &mut rng)
314            .await
315            .map(|p| p.expect("create_or_open_async with creation returns Some"))
316    }
317
318    /// Get `key` within `dir`. A missing directory yields `Ok(None)`.
319    pub async fn get(
320        &self,
321        dir: &[&[u8]],
322        key: &[u8],
323    ) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
324        let Some(prefix) = self.prefix_of(dir).await? else {
325            return Ok(None);
326        };
327        let mut raw_key = prefix;
328        raw_key.extend_from_slice(key);
329        Ok(self.raw.get(&raw_key).await?)
330    }
331
332    /// Check whether `key` exists within `dir`. A missing directory yields
333    /// `Ok(false)`.
334    pub async fn exists(&self, dir: &[&[u8]], key: &[u8]) -> Result<bool, FlatError<R::Error>> {
335        let Some(prefix) = self.prefix_of(dir).await? else {
336            return Ok(false);
337        };
338        let mut raw_key = prefix;
339        raw_key.extend_from_slice(key);
340        Ok(self.raw.exists(&raw_key).await?)
341    }
342
343    /// Scan within `dir` between `start` and `end`, ascending or descending.
344    /// A missing directory yields no rows.
345    pub async fn scan(
346        &self,
347        dir: &[&[u8]],
348        start: Bound<&[u8]>,
349        end: Bound<&[u8]>,
350        forward: bool,
351    ) -> Result<Vec<KvPair>, FlatError<R::Error>> {
352        let Some(bounds) = self.data_bounds(dir, start, end).await? else {
353            return Ok(Vec::new());
354        };
355        let owned = (bounds.start, bounds.end);
356        let (rs, re) = bounds_ref(&owned);
357        let rows = self.raw.scan(rs, re, forward, None).await?;
358        let plen = bounds.prefix.len();
359        Ok(rows
360            .into_iter()
361            .map(|pair| KvPair {
362                key: pair.key[plen..].to_vec(),
363                value: pair.value,
364            })
365            .collect())
366    }
367
368    /// Resolve `dir` and map within-directory bounds to raw engine bounds.
369    pub async fn data_bounds(
370        &self,
371        dir: &[&[u8]],
372        start: Bound<&[u8]>,
373        end: Bound<&[u8]>,
374    ) -> Result<Option<DataBounds>, FlatError<R::Error>> {
375        let Some(prefix) = self.prefix_of(dir).await? else {
376            return Ok(None);
377        };
378        Ok(map_data_bounds(&prefix, start, end))
379    }
380
381    /// Set `key` within `dir`, allocating `dir` and any missing ancestors if
382    /// needed.
383    pub async fn set(
384        &mut self,
385        dir: &[&[u8]],
386        key: &[u8],
387        value: &[u8],
388    ) -> Result<(), FlatError<R::Error>> {
389        let prefix = self.allocate_dir(dir).await?;
390        let mut raw_key = prefix;
391        raw_key.extend_from_slice(key);
392        self.raw.insert(&raw_key, value).await?;
393        Ok(())
394    }
395
396    /// Delete `key` within `dir` (a no-op if the directory or key is absent).
397    pub async fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
398        let Some(prefix) = self.prefix_of(dir).await? else {
399            return Ok(());
400        };
401        let mut raw_key = prefix;
402        raw_key.extend_from_slice(key);
403        self.raw.delete(&raw_key).await?;
404        Ok(())
405    }
406
407    /// Clear `start <= k < end` within `dir` (a no-op if `dir` does not exist).
408    pub async fn clear_range(
409        &mut self,
410        dir: &[&[u8]],
411        start: Bound<&[u8]>,
412        end: Bound<&[u8]>,
413    ) -> Result<(), FlatError<R::Error>> {
414        let Some(bounds) = self.data_bounds(dir, start, end).await? else {
415            return Ok(());
416        };
417        let owned = (bounds.start, bounds.end);
418        let (rs, re) = bounds_ref(&owned);
419        self.raw.clear_range(rs, re).await?;
420        Ok(())
421    }
422
423    /// List the immediate child segment names under `dir`, sorted ascending.
424    pub async fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
425        validate_dir(dir).map_err(FlatError::Key)?;
426        ops::check_version_read_async(&self.raw).await?;
427        let path = Self::layer_path(dir);
428        let Some(prefix) = ops::find_async(&self.raw, &path).await? else {
429            return Ok(Vec::new());
430        };
431        let names = ops::list_children_async(&self.raw, &prefix).await?;
432        Ok(names.into_iter().map(|s| s.into_bytes()).collect())
433    }
434
435    /// Whether `dir` exists.
436    pub async fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
437        validate_dir(dir).map_err(FlatError::Key)?;
438        ops::check_version_read_async(&self.raw).await?;
439        let path = Self::layer_path(dir);
440        Ok(ops::find_async(&self.raw, &path).await?.is_some())
441    }
442
443    /// Remove `dir` recursively: its subdirectories and its own key data.
444    pub async fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
445        validate_dir(dir).map_err(FlatError::Key)?;
446        if dir.is_empty() {
447            return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
448        }
449        ops::check_version_read_async(&self.raw).await?;
450        let path = Self::layer_path(dir);
451        ops::remove_dir_async(&mut self.raw, &path).await
452    }
453}
454
455/// Map within-directory key bounds onto the raw engine range under an already
456/// resolved directory `prefix`, returning `None` when the range is empty.
457pub fn map_data_bounds(
458    prefix: &[u8],
459    start: Bound<&[u8]>,
460    end: Bound<&[u8]>,
461) -> Option<DataBounds> {
462    let (rs, re) = map_bounds(prefix, start, end);
463    if raw_range_empty(&rs, &re) {
464        return None;
465    }
466    Some(DataBounds {
467        prefix: prefix.to_vec(),
468        start: rs,
469        end: re,
470    })
471}
472
473/// The raw engine range of one directory's data: the resolved prefix and
474/// the raw byte bounds over the engine's whole keyspace. The start bound
475/// carries its own inclusion (`Included`/`Excluded`); the end bound is
476/// always `Excluded`. Cursor-yielding keys carry the prefix; strip
477/// `prefix.len()` bytes to get the within-directory key.
478pub struct DataBounds {
479    /// The directory's allocated prefix.
480    pub prefix: Vec<u8>,
481    /// Raw start bound.
482    pub start: Bound<Vec<u8>>,
483    /// Raw end bound, exclusive.
484    pub end: Bound<Vec<u8>>,
485}
486
487impl core::fmt::Debug for DataBounds {
488    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
489        // Lengths only: a `Debug` panic line must not dump the raw bound
490        // bytes, which embed the key material of a live directory.
491        f.debug_struct("DataBounds")
492            .field("prefix_len", &self.prefix.len())
493            .field("start", &bound_len(&self.start))
494            .field("end", &bound_len(&self.end))
495            .finish()
496    }
497}
498
499fn bound_len(b: &Bound<Vec<u8>>) -> String {
500    match b {
501        Bound::Unbounded => "unbounded".to_owned(),
502        Bound::Included(v) => format!("incl({} bytes)", v.len()),
503        Bound::Excluded(v) => format!("excl({} bytes)", v.len()),
504    }
505}
506
507/// Borrow the owned bounds of a mapped range as slice bounds, for
508/// [`RawKv::scan`]/[`RawKv::clear_range`].
509fn bounds_ref(b: &(Bound<Vec<u8>>, Bound<Vec<u8>>)) -> (Bound<&[u8]>, Bound<&[u8]>) {
510    (bound_ref(&b.0), bound_ref(&b.1))
511}
512
513fn bound_ref(b: &Bound<Vec<u8>>) -> Bound<&[u8]> {
514    match b {
515        Bound::Unbounded => Bound::Unbounded,
516        Bound::Included(v) => Bound::Included(v.as_slice()),
517        Bound::Excluded(v) => Bound::Excluded(v.as_slice()),
518    }
519}
520
521/// The exclusive raw end of `prefix`'s data region.
522///
523/// [`data_region`] returns a `Bound`; this is its `Excluded` byte vector,
524/// for callers that need the owned form.
525fn data_end_exclusive(prefix: &[u8]) -> Vec<u8> {
526    match data_region(prefix).1 {
527        Bound::Excluded(b) => b,
528        _ => unreachable!("data_region end is always Excluded"),
529    }
530}
531
532/// Map key-part bounds onto the raw range under `prefix`.
533///
534/// Within one directory the mapping `prefix ‖ k` is monotone, so the raw
535/// range stays inside the directory's data region:
536///
537/// - start `Included(k)`  -> raw `Included(prefix ‖ k)`
538/// - start `Excluded(k)`  -> raw `Excluded(prefix ‖ k)`
539/// - start unbounded      -> raw `Included(prefix)` (the region start: the
540///   directory's empty key sits at the prefix itself)
541/// - end `Excluded(k)`    -> raw `Excluded(prefix ‖ k)`
542/// - end `Included(k)`    -> raw `Excluded(prefix ‖ k ‖ [0x00])`:
543///   `prefix ‖ k ‖ [0x00]` is the raw lexicographic immediate successor of
544///   the key's raw form (a byte string's smallest greater byte string is
545///   itself with a `0x00` appended), and it always lies inside the region
546///   because it is an extension of `prefix`
547/// - end unbounded        -> raw `Excluded` of the region end
548///   (`next_prefix(prefix)`)
549///
550/// Note the two successor notions: the end bound uses the raw immediate
551/// successor (`‖ [0x00]`), while region ends use the prefix-block successor
552/// ([`crate::keyspace::next_prefix`]).
553///
554/// The range may name no keys (for example `Excluded(k)` to
555/// `Excluded(k)`); callers check with [`raw_range_empty`].
556fn map_bounds(
557    prefix: &[u8],
558    start: Bound<&[u8]>,
559    end: Bound<&[u8]>,
560) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
561    let mk = |k: &[u8]| {
562        let mut raw = prefix.to_vec();
563        raw.extend_from_slice(k);
564        raw
565    };
566    let rs = match start {
567        Bound::Unbounded => Bound::Included(prefix.to_vec()),
568        Bound::Included(k) => Bound::Included(mk(k)),
569        Bound::Excluded(k) => Bound::Excluded(mk(k)),
570    };
571    let re = match end {
572        Bound::Unbounded => Bound::Excluded(data_end_exclusive(prefix)),
573        Bound::Excluded(k) => Bound::Excluded(mk(k)),
574        Bound::Included(k) => {
575            let mut raw = mk(k);
576            raw.push(0x00);
577            Bound::Excluded(raw)
578        }
579    };
580    (rs, re)
581}
582
583/// Whether a raw `(start, end)` bound pair names no keys at all.
584///
585/// Only `Excluded` end bounds occur (see [`map_bounds`]), so the range is
586/// empty exactly when the start bound reaches or passes the end bound.
587fn raw_range_empty(start: &Bound<Vec<u8>>, end: &Bound<Vec<u8>>) -> bool {
588    match (start, end) {
589        (Bound::Included(a), Bound::Excluded(b)) => a >= b,
590        (Bound::Excluded(a), Bound::Excluded(b)) => a >= b,
591        (Bound::Unbounded, _) => false,
592        (_, Bound::Unbounded) => false,
593        _ => unreachable!("end bounds are always Excluded"),
594    }
595}
596
597// -- test double -----------------------------------------------------------
598
599/// An in-memory [`RawKv`] for testing the layout independently of any
600/// backend. Shared by the flatdir module's test suites.
601#[cfg(test)]
602pub(crate) struct Mem {
603    map: core::cell::RefCell<std::collections::BTreeMap<Vec<u8>, Vec<u8>>>,
604}
605
606#[cfg(test)]
607impl Default for Mem {
608    fn default() -> Self {
609        Self {
610            map: core::cell::RefCell::new(std::collections::BTreeMap::new()),
611        }
612    }
613}
614
615#[cfg(test)]
616impl RawKv for Mem {
617    type Error = std::convert::Infallible;
618
619    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
620        Ok(self.map.borrow().get(key).cloned())
621    }
622
623    fn scan(
624        &self,
625        start: Bound<&[u8]>,
626        end: Bound<&[u8]>,
627        forward: bool,
628    ) -> Result<Vec<KvPair>, Self::Error> {
629        let map = self.map.borrow();
630        let rows: Vec<KvPair> = map
631            .iter()
632            .filter(|(k, _)| {
633                let k = &k[..];
634                let above = match start {
635                    Bound::Unbounded => true,
636                    Bound::Included(s) => k >= s,
637                    Bound::Excluded(s) => k > s,
638                };
639                let below = match end {
640                    Bound::Unbounded => true,
641                    Bound::Excluded(e) => k < e,
642                    Bound::Included(e) => k <= e,
643                };
644                above && below
645            })
646            .map(|(k, v)| KvPair {
647                key: k.clone(),
648                value: v.clone(),
649            })
650            .collect();
651        if forward {
652            Ok(rows)
653        } else {
654            Ok(rows.into_iter().rev().collect())
655        }
656    }
657
658    fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
659        self.map.borrow_mut().insert(key.to_vec(), value.to_vec());
660        Ok(())
661    }
662
663    fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
664        self.map.borrow_mut().remove(key);
665        Ok(())
666    }
667
668    fn clear_range(&mut self, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Result<(), Self::Error> {
669        let mut map = self.map.borrow_mut();
670        let keys: Vec<Vec<u8>> = map
671            .keys()
672            .filter(|k| {
673                let k = &k[..];
674                let above = match start {
675                    Bound::Unbounded => true,
676                    Bound::Included(s) => k >= s,
677                    Bound::Excluded(s) => k > s,
678                };
679                let below = match end {
680                    Bound::Unbounded => true,
681                    Bound::Excluded(e) => k < e,
682                    Bound::Included(e) => k <= e,
683                };
684                above && below
685            })
686            .cloned()
687            .collect();
688        for k in keys {
689            map.remove(&k);
690        }
691        Ok(())
692    }
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698    use crate::key::KeyError;
699
700    fn engine() -> FlatEngine<Mem> {
701        FlatEngine::new(Mem::default())
702    }
703
704    fn ok<T>(r: Result<T, FlatError<std::convert::Infallible>>) -> T {
705        r.unwrap()
706    }
707
708    // -- fresh stores ------------------------------------------------------
709
710    #[test]
711    fn fresh_reads_return_empty_and_first_write_initialises() {
712        let mut e = engine();
713        assert_eq!(ok(e.prefix_of(&[])), None);
714        assert_eq!(ok(e.get(&[], b"k")), None);
715        assert!(ok(e.scan(&[], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
716        assert!(ok(e.list_dirs(&[])).is_empty());
717        assert!(!ok(e.dir_exists(&[])));
718        // Removing from a fresh store is a miss, not an error.
719        assert!(!ok(e.remove_dir(&[b"a"])));
720        // The first write initialises the store lazily (version row,
721        // anchor node).
722        ok(e.set(&[], b"k", b"v"));
723        assert!(ok(e.dir_exists(&[])));
724        assert_eq!(ok(e.get(&[], b"k")), Some(b"v".to_vec()));
725        // The version row is the layout's 12-byte 1.0.0.
726        let version = e
727            .raw()
728            .map
729            .borrow()
730            .get(crate::flatdir::layout::VERSION_KEY)
731            .cloned();
732        assert_eq!(
733            version,
734            Some(crate::flatdir::layout::LAYOUT_VERSION.to_vec())
735        );
736    }
737
738    /// A first write in a one-segment directory produces exactly nine
739    /// raw rows: the version row, the anchor node's child and layer
740    /// rows, the directory node's child and layer rows, the HCA
741    /// counter row, two HCA recent rows, and the data row. The root
742    /// node carries no layer row.
743    #[test]
744    fn a_first_set_produces_exactly_nine_raw_rows() {
745        let mut e = engine();
746        ok(e.set(&[b"a"], b"k", b"v"));
747        let map = e.raw().map.borrow();
748        assert_eq!(map.len(), 9, "unexpected raw rows: {map:?}");
749    }
750
751    // -- foreign stores ------------------------------------------------------
752
753    #[test]
754    fn reads_on_a_foreign_store_fail_closed() {
755        // A version row this layout does not read (major = 2): every
756        // operation fails with `Foreign` rather than answering over
757        // someone else's data.
758        let mut e = engine();
759        let mut v = [0u8; 12];
760        v[0..4].copy_from_slice(&2u32.to_le_bytes());
761        e.raw_mut()
762            .insert(crate::flatdir::layout::VERSION_KEY, &v)
763            .unwrap();
764        assert_eq!(e.prefix_of(&[]), Err(FlatError::Foreign));
765        assert_eq!(e.get(&[], b"k"), Err(FlatError::Foreign));
766        assert_eq!(
767            e.scan(&[], Bound::Unbounded, Bound::Unbounded, true),
768            Err(FlatError::Foreign)
769        );
770        assert!(matches!(
771            e.data_bounds(&[], Bound::Unbounded, Bound::Unbounded),
772            Err(FlatError::Foreign)
773        ));
774        assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
775        assert_eq!(e.list_dirs(&[]), Err(FlatError::Foreign));
776        assert_eq!(e.set(&[], b"k", b"v"), Err(FlatError::Foreign));
777        assert_eq!(e.remove_dir(&[b"a"]), Err(FlatError::Foreign));
778    }
779
780    #[test]
781    fn a_malformed_version_row_fails_closed() {
782        // A short version value is not a version: fail closed.
783        let mut e = engine();
784        e.raw_mut()
785            .insert(crate::flatdir::layout::VERSION_KEY, &[1, 0])
786            .unwrap();
787        assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
788    }
789
790    #[test]
791    fn a_corrupt_node_value_is_corrupt_not_a_panic() {
792        // A healthy store whose anchor child row's value is then flipped
793        // to a non-packing byte string: the node walk reports `Corrupt`
794        // rather than panicking.
795        let mut e = engine();
796        e.set(&[b"dir"], b"k", b"v").unwrap();
797        // The anchor child row sits under the root node and is the only
798        // row there tagged with INT(0) (0x14): the HCA and version rows
799        // are tagged 0x01 (BYTES) and sort before it.
800        let child_tag = crate::flatdir::layout::ROOT_NODE
801            .iter()
802            .copied()
803            .chain(std::iter::once(0x14))
804            .collect::<Vec<u8>>();
805        let row_key = e
806            .raw()
807            .map
808            .borrow()
809            .iter()
810            .find(|(k, _)| k.starts_with(&child_tag))
811            .expect("the anchor child row")
812            .0
813            .clone();
814        e.raw_mut()
815            .map
816            .borrow_mut()
817            .insert(row_key, vec![0x99, 0x00]);
818        assert_eq!(e.get(&[b"dir"], b"k"), Err(FlatError::Corrupt));
819        assert_eq!(
820            e.scan(&[b"dir"], Bound::Unbounded, Bound::Unbounded, true),
821            Err(FlatError::Corrupt)
822        );
823        assert_eq!(e.remove_dir(&[b"dir"]), Err(FlatError::Corrupt));
824    }
825
826    // -- allocation ---------------------------------------------------------
827
828    #[test]
829    fn allocation_is_recursive_and_stable() {
830        let mut e = engine();
831        let p = ok(e.allocate_dir(&[b"a", b"b"]));
832        // Re-resolving finds the same prefix (no new allocation).
833        assert_eq!(ok(e.prefix_of(&[b"a", b"b"])), Some(p.clone()));
834        // Siblings get different prefixes; the ancestor resolves too.
835        let q = ok(e.allocate_dir(&[b"a", b"c"]));
836        assert_ne!(p, q);
837        assert!(ok(e.prefix_of(&[b"a"])).is_some());
838        // Every allocated prefix starts in the packed-i64 band
839        // (0x0c..=0x1c): never the meta (0xFE) or reserved (0xFF) region.
840        let dirs: [[&[u8]; 2]; 2] = [[b"a" as &[u8], b"b"], [b"a" as &[u8], b"c"]];
841        for dir in dirs {
842            let p = ok(e.prefix_of(&dir)).unwrap();
843            assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?}");
844        }
845    }
846
847    #[test]
848    fn many_allocations_stay_in_the_data_region() {
849        // 300 directories (past the first HCA window advance): every
850        // allocated prefix stays in the data region and every data key
851        // lands outside the meta region.
852        let mut e = engine();
853        for i in 0..300u32 {
854            let d = format!("d{i:03}").into_bytes();
855            let d = [d.as_slice()];
856            let p = ok(e.allocate_dir(&d));
857            assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?} at {i}");
858        }
859    }
860
861    #[test]
862    fn resolve_missing_dir_is_none() {
863        let mut e = engine();
864        ok(e.set(&[], b"k", b"v"));
865        assert_eq!(ok(e.prefix_of(&[b"nope"])), None);
866        assert_eq!(ok(e.prefix_of(&[b"nope", b"deeper"])), None);
867    }
868
869    // -- data operations ----------------------------------------------------
870
871    #[test]
872    fn set_get_delete_round_trips_per_dir() {
873        let mut e = engine();
874        ok(e.set(&[b"asset", b"btc"], b"k", b"v"));
875        assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), Some(b"v".to_vec()));
876        // Same key, different directory: isolated.
877        assert_eq!(ok(e.get(&[b"asset"], b"k")), None);
878        assert_eq!(ok(e.get(&[b"btc"], b"k")), None);
879        ok(e.delete(&[b"asset", b"btc"], b"k"));
880        assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), None);
881    }
882
883    #[test]
884    fn scan_orders_within_dir_only() {
885        let mut e = engine();
886        for k in [b"b", b"a", b"c"] {
887            ok(e.set(&[b"d"], k, k));
888            ok(e.set(&[b"other"], k, k));
889        }
890        let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true));
891        let keys: Vec<Vec<u8>> = rows.iter().map(|p| p.key.clone()).collect();
892        assert_eq!(keys, vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]);
893        let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, false));
894        assert_eq!(rows.first().unwrap().key, b"c".to_vec());
895    }
896
897    #[test]
898    fn scan_bound_matrix() {
899        let mut e = engine();
900        for k in [b"a", b"b", b"c", b"\xff"] {
901            ok(e.set(&[b"d"], k, b"v"));
902        }
903        let get = |s: core::ops::Bound<&[u8]>,
904                   en: core::ops::Bound<&[u8]>,
905                   e: &FlatEngine<Mem>|
906         -> Vec<Vec<u8>> {
907            ok(e.scan(&[b"d"], s, en, true))
908                .into_iter()
909                .map(|pair| pair.key)
910                .collect()
911        };
912        assert_eq!(
913            get(Bound::Included(b"b"), Bound::Excluded(b"c"), &e),
914            vec![b"b".to_vec()]
915        );
916        assert_eq!(
917            get(Bound::Excluded(b"b"), Bound::Included(b"c"), &e),
918            vec![b"c".to_vec()]
919        );
920        assert_eq!(
921            get(Bound::Excluded(&[0xFFu8]), Bound::Unbounded, &e),
922            Vec::<Vec<u8>>::new()
923        );
924        assert_eq!(
925            get(Bound::Unbounded, Bound::Included(&[0xFFu8]), &e),
926            vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), vec![0xFF]]
927        );
928        assert_eq!(
929            get(Bound::Included(&[0xFFu8]), Bound::Unbounded, &e),
930            vec![vec![0xFF]]
931        );
932        // An Excluded bound at all-0xFF: the range is empty.
933        assert_eq!(
934            get(Bound::Excluded(&[0xFFu8]), Bound::Excluded(&[0xFFu8]), &e),
935            Vec::<Vec<u8>>::new()
936        );
937    }
938
939    #[test]
940    fn clear_range_clears_within_dir_only() {
941        let mut e = engine();
942        for k in [b"a", b"b", b"c"] {
943            ok(e.set(&[b"d"], k, b"v"));
944            ok(e.set(&[b"e"], k, b"v"));
945        }
946        ok(e.clear_range(&[b"d"], Bound::Included(b"b"), Bound::Excluded(b"c")));
947        assert_eq!(ok(e.get(&[b"d"], b"a")), Some(b"v".to_vec()));
948        assert_eq!(ok(e.get(&[b"d"], b"b")), None);
949        assert_eq!(ok(e.get(&[b"d"], b"c")), Some(b"v".to_vec()));
950        assert_eq!(ok(e.get(&[b"e"], b"b")), Some(b"v".to_vec()));
951        // Whole directory.
952        ok(e.clear_range(&[b"d"], Bound::Unbounded, Bound::Unbounded));
953        assert!(ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
954        // The directory still exists (data-free directories are entities).
955        assert!(ok(e.dir_exists(&[b"d"])));
956    }
957
958    // -- navigation ---------------------------------------------------------
959
960    #[test]
961    fn nav_list_exists_remove() {
962        let mut e = engine();
963        ok(e.set(&[b"a", b"1"], b"k", b"v"));
964        ok(e.set(&[b"a", b"2"], b"k", b"v"));
965        ok(e.set(&[b"b"], b"k", b"v"));
966        assert_eq!(ok(e.list_dirs(&[])), vec![b"a".to_vec(), b"b".to_vec()]);
967        assert_eq!(ok(e.list_dirs(&[b"a"])), vec![b"1".to_vec(), b"2".to_vec()]);
968        assert!(ok(e.dir_exists(&[b"a"])));
969        assert!(ok(e.dir_exists(&[b"a", b"1"])));
970        assert!(!ok(e.dir_exists(&[b"a", b"3"])));
971        // A directory with no data keys still exists.
972        ok(e.allocate_dir(&[b"empty"]));
973        assert!(ok(e.dir_exists(&[b"empty"])));
974        assert!(ok(e.list_dirs(&[b"empty"])).is_empty());
975        // Missing: empty list, not an error.
976        assert!(ok(e.list_dirs(&[b"nope"])).is_empty());
977        assert!(!ok(e.dir_exists(&[b"nope"])));
978    }
979
980    #[test]
981    fn nav_remove_is_recursive() {
982        let mut e = engine();
983        ok(e.set(&[b"a", b"b", b"c"], b"k1", b"v1"));
984        ok(e.set(&[b"a", b"b"], b"k2", b"v2"));
985        ok(e.set(&[b"a", b"d"], b"k3", b"v3"));
986        ok(e.set(&[b"z"], b"k4", b"v4"));
987        // Remove the middle directory: b/c and b go, a/d stays.
988        assert!(ok(e.remove_dir(&[b"a", b"b"])));
989        assert_eq!(ok(e.get(&[b"a", b"b", b"c"], b"k1")), None);
990        assert_eq!(ok(e.get(&[b"a", b"b"], b"k2")), None);
991        assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), Some(b"v3".to_vec()));
992        assert!(ok(e.dir_exists(&[b"a"])));
993        assert!(!ok(e.dir_exists(&[b"a", b"b"])));
994        // Removing a leaf directory removes it and its data.
995        assert!(ok(e.remove_dir(&[b"a", b"d"])));
996        assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), None);
997        // Missing: false.
998        assert!(!ok(e.remove_dir(&[b"a", b"b"])));
999        // Unaffected directories keep their data.
1000        assert_eq!(ok(e.get(&[b"z"], b"k4")), Some(b"v4".to_vec()));
1001    }
1002
1003    #[test]
1004    fn nav_root_is_not_removable() {
1005        let mut e = engine();
1006        ok(e.set(&[], b"k", b"v"));
1007        assert_eq!(
1008            e.remove_dir(&[]),
1009            Err(FlatError::Key(KeyError::RootNotRemovable))
1010        );
1011        // The root survived.
1012        assert!(ok(e.dir_exists(&[])));
1013    }
1014
1015    #[test]
1016    fn nav_rejects_non_utf8() {
1017        let mut e = engine();
1018        let seg: &[u8] = b"\xFF\xFE";
1019        let bad = [seg];
1020        assert_eq!(
1021            e.list_dirs(&bad),
1022            Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
1023        );
1024        assert_eq!(
1025            e.remove_dir(&bad),
1026            Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
1027        );
1028    }
1029
1030    #[test]
1031    fn remove_and_recreate_work() {
1032        // Removal leaves no trace that blocks re-creation: the HCA may
1033        // even re-claim the same candidate value (FDB semantics — the
1034        // allocator tracks windows, not used prefixes); what matters is
1035        // that the recreated directory is fully functional and no stale
1036        // row of the old one is read.
1037        let mut e = engine();
1038        ok(e.set(&[b"x"], b"k", b"v1"));
1039        let p1 = ok(e.prefix_of(&[b"x"])).unwrap();
1040        assert!(ok(e.remove_dir(&[b"x"])));
1041        assert!(!ok(e.dir_exists(&[b"x"])));
1042        assert_eq!(ok(e.get(&[b"x"], b"k")), None);
1043        ok(e.set(&[b"x"], b"k", b"v2"));
1044        let p2 = ok(e.prefix_of(&[b"x"])).unwrap();
1045        assert_eq!(ok(e.get(&[b"x"], b"k")), Some(b"v2".to_vec()));
1046        // If the allocator re-claimed the same prefix, the old data row
1047        // was cleared by the removal (same raw key, new value wins).
1048        if p1 == p2 {
1049            assert_eq!(
1050                ok(e.scan(&[b"x"], Bound::Unbounded, Bound::Unbounded, true)).len(),
1051                1
1052            );
1053        }
1054        // The store still validates as a whole layout.
1055        assert!(ops::validate(e.raw()).is_ok());
1056    }
1057
1058    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1059    mod async_tests {
1060        use std::collections::BTreeMap;
1061        use std::sync::Mutex;
1062
1063        use super::*;
1064
1065        #[derive(Default)]
1066        struct AsyncMem {
1067            map: Mutex<BTreeMap<Vec<u8>, Vec<u8>>>,
1068        }
1069
1070        impl AsyncRawKv for AsyncMem {
1071            type Error = std::convert::Infallible;
1072
1073            async fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
1074                Ok(self.map.lock().unwrap().get(key).cloned())
1075            }
1076
1077            async fn exists(&self, key: &[u8]) -> Result<bool, Self::Error> {
1078                Ok(self.map.lock().unwrap().contains_key(key))
1079            }
1080
1081            async fn scan(
1082                &self,
1083                start: Bound<&[u8]>,
1084                end: Bound<&[u8]>,
1085                forward: bool,
1086                limit: Option<usize>,
1087            ) -> Result<Vec<KvPair>, Self::Error> {
1088                if limit == Some(0) {
1089                    return Ok(Vec::new());
1090                }
1091                let map = self.map.lock().unwrap();
1092                let mut rows: Vec<KvPair> = map
1093                    .iter()
1094                    .filter(|(k, _)| {
1095                        let k = k.as_slice();
1096                        let above = match start {
1097                            Bound::Unbounded => true,
1098                            Bound::Included(s) => k >= s,
1099                            Bound::Excluded(s) => k > s,
1100                        };
1101                        let below = match end {
1102                            Bound::Unbounded => true,
1103                            Bound::Excluded(e) => k < e,
1104                            Bound::Included(e) => k <= e,
1105                        };
1106                        above && below
1107                    })
1108                    .map(|(k, v)| KvPair {
1109                        key: k.clone(),
1110                        value: v.clone(),
1111                    })
1112                    .collect();
1113                if !forward {
1114                    rows.reverse();
1115                }
1116                if let Some(limit) = limit {
1117                    rows.truncate(limit);
1118                }
1119                Ok(rows)
1120            }
1121
1122            async fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
1123                self.map
1124                    .lock()
1125                    .unwrap()
1126                    .insert(key.to_vec(), value.to_vec());
1127                Ok(())
1128            }
1129
1130            async fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
1131                self.map.lock().unwrap().remove(key);
1132                Ok(())
1133            }
1134
1135            async fn clear_range(
1136                &mut self,
1137                start: Bound<&[u8]>,
1138                end: Bound<&[u8]>,
1139            ) -> Result<(), Self::Error> {
1140                let mut map = self.map.lock().unwrap();
1141                let keys: Vec<Vec<u8>> = map
1142                    .keys()
1143                    .filter(|k| {
1144                        let k = k.as_slice();
1145                        let above = match start {
1146                            Bound::Unbounded => true,
1147                            Bound::Included(s) => k >= s,
1148                            Bound::Excluded(s) => k > s,
1149                        };
1150                        let below = match end {
1151                            Bound::Unbounded => true,
1152                            Bound::Excluded(e) => k < e,
1153                            Bound::Included(e) => k <= e,
1154                        };
1155                        above && below
1156                    })
1157                    .cloned()
1158                    .collect();
1159                for k in keys {
1160                    map.remove(&k);
1161                }
1162                Ok(())
1163            }
1164        }
1165
1166        fn assert_send<T: Send>(_: &T) {}
1167
1168        #[tokio::test]
1169        async fn async_engine_futures_are_send_and_round_trip() {
1170            let mut e = AsyncFlatEngine::new(AsyncMem::default());
1171            {
1172                let fut = e.set(&[b"a", b"b"], b"k1", b"v1");
1173                assert_send(&fut);
1174                fut.await.unwrap();
1175            }
1176            {
1177                let fut = e.get(&[b"a", b"b"], b"k1");
1178                assert_send(&fut);
1179                assert_eq!(fut.await.unwrap(), Some(b"v1".to_vec()));
1180            }
1181            assert!(e.exists(&[b"a", b"b"], b"k1").await.unwrap());
1182            assert!(!e.exists(&[b"a", b"b"], b"missing").await.unwrap());
1183            assert!(!e.exists(&[b"missing"], b"k1").await.unwrap());
1184            assert_eq!(e.list_dirs(&[]).await.unwrap(), vec![b"a".to_vec()]);
1185            assert_eq!(e.list_dirs(&[b"a"]).await.unwrap(), vec![b"b".to_vec()]);
1186
1187            assert!(e.remove_dir(&[b"a"]).await.unwrap());
1188            assert!(!e.dir_exists(&[b"a"]).await.unwrap());
1189            assert!(!e.dir_exists(&[b"a", b"b"]).await.unwrap());
1190            assert_eq!(e.get(&[b"a", b"b"], b"k1").await.unwrap(), None);
1191            assert!(ops::validate_async(e.raw()).await.is_ok());
1192        }
1193
1194        #[tokio::test]
1195        async fn async_engine_handles_many_allocations_foreign_and_clear_range() {
1196            let mut e = AsyncFlatEngine::new(AsyncMem::default());
1197            for i in 0..130u32 {
1198                let d = format!("d{i:03}").into_bytes();
1199                let p = e.allocate_dir(&[d.as_slice()]).await.unwrap();
1200                assert!((0x0c..=0x1c).contains(&p[0]));
1201            }
1202            e.set(&[b"d000"], b"a", b"1").await.unwrap();
1203            e.set(&[b"d000"], b"b", b"2").await.unwrap();
1204            e.set(&[b"d000"], b"c", b"3").await.unwrap();
1205            e.clear_range(&[b"d000"], Bound::Included(b"b"), Bound::Excluded(b"c"))
1206                .await
1207                .unwrap();
1208            let rows = e
1209                .scan(&[b"d000"], Bound::Unbounded, Bound::Unbounded, false)
1210                .await
1211                .unwrap();
1212            let keys: Vec<Vec<u8>> = rows.into_iter().map(|p| p.key).collect();
1213            assert_eq!(keys, vec![b"c".to_vec(), b"a".to_vec()]);
1214            assert!(ops::validate_async(e.raw()).await.is_ok());
1215
1216            let mut foreign = AsyncFlatEngine::new(AsyncMem::default());
1217            let mut v = [0u8; 12];
1218            v[0..4].copy_from_slice(&2u32.to_le_bytes());
1219            foreign
1220                .raw_mut()
1221                .insert(crate::flatdir::layout::VERSION_KEY, &v)
1222                .await
1223                .unwrap();
1224            assert_eq!(foreign.get(&[], b"k").await, Err(FlatError::Foreign));
1225            assert_eq!(foreign.set(&[], b"k", b"v").await, Err(FlatError::Foreign));
1226            assert_eq!(
1227                foreign.remove_dir(&[]).await,
1228                Err(FlatError::Key(KeyError::RootNotRemovable))
1229            );
1230        }
1231
1232        #[tokio::test]
1233        async fn sync_and_async_flatdir_ops_produce_byte_identical_raw_maps() {
1234            use crate::flatdir::hca::Lcg;
1235
1236            let mut sync_raw = Mem::default();
1237            let mut async_raw = AsyncMem::default();
1238            let mut sync_rng = Lcg::new(42);
1239            let mut async_rng = Lcg::new(42);
1240
1241            // Build nested directories and cross the first HCA window advance (32).
1242            let mut paths: Vec<Vec<Vec<u8>>> = vec![
1243                vec![b"alpha".to_vec(), b"beta".to_vec(), b"gamma".to_vec()],
1244                vec![b"alpha".to_vec(), b"delta".to_vec()],
1245                vec![b"nested".to_vec(), b"one".to_vec(), b"two".to_vec()],
1246            ];
1247            for i in 0..40u32 {
1248                paths.push(vec![format!("dir-{i:02}").into_bytes()]);
1249            }
1250
1251            let to_layer_path = |segs: &[Vec<u8>]| -> Vec<Vec<u8>> {
1252                let mut full = Vec::with_capacity(segs.len() + 1);
1253                full.push(ROOT_PATH_SEGMENT.as_bytes().to_vec());
1254                full.extend_from_slice(segs);
1255                full
1256            };
1257
1258            for segs in &paths {
1259                let full = to_layer_path(segs);
1260                let refs: Vec<&[u8]> = full.iter().map(Vec::as_slice).collect();
1261                let sync_prefix = ops::create_or_open(&mut sync_raw, &refs, true, &mut sync_rng)
1262                    .unwrap()
1263                    .unwrap();
1264                let async_prefix =
1265                    ops::create_or_open_async(&mut async_raw, &refs, true, &mut async_rng)
1266                        .await
1267                        .unwrap()
1268                        .unwrap();
1269                assert_eq!(sync_prefix, async_prefix);
1270
1271                // Write a data row under each allocated directory.
1272                let mut data_key = sync_prefix;
1273                data_key.extend_from_slice(b"payload");
1274                sync_raw.insert(&data_key, b"value").unwrap();
1275                async_raw.insert(&data_key, b"value").await.unwrap();
1276            }
1277
1278            assert_eq!(
1279                *sync_raw.map.borrow(),
1280                *async_raw.map.lock().unwrap(),
1281                "raw maps must match byte-for-byte after nested creates and HCA window advance"
1282            );
1283
1284            // Remove nested and leaf subtrees in the same order.
1285            for target in [
1286                vec![b"alpha".to_vec()],
1287                vec![b"nested".to_vec(), b"one".to_vec()],
1288                vec![b"dir-15".to_vec()],
1289                vec![b"missing".to_vec()],
1290            ] {
1291                let full = to_layer_path(&target);
1292                let refs: Vec<&[u8]> = full.iter().map(Vec::as_slice).collect();
1293                let sync_removed = ops::remove_dir(&mut sync_raw, &refs).unwrap();
1294                let async_removed = ops::remove_dir_async(&mut async_raw, &refs).await.unwrap();
1295                assert_eq!(sync_removed, async_removed);
1296            }
1297
1298            assert_eq!(
1299                *sync_raw.map.borrow(),
1300                *async_raw.map.lock().unwrap(),
1301                "raw maps must match byte-for-byte after recursive removals"
1302            );
1303
1304            // Recreate a removed nested path and verify identical state and validation.
1305            let recreate = to_layer_path(&[b"alpha".to_vec(), b"beta".to_vec()]);
1306            let refs: Vec<&[u8]> = recreate.iter().map(Vec::as_slice).collect();
1307            let sp = ops::create_or_open(&mut sync_raw, &refs, true, &mut sync_rng).unwrap();
1308            let ap = ops::create_or_open_async(&mut async_raw, &refs, true, &mut async_rng)
1309                .await
1310                .unwrap();
1311            assert_eq!(sp, ap);
1312            assert_eq!(*sync_raw.map.borrow(), *async_raw.map.lock().unwrap());
1313            assert_eq!(
1314                ops::validate(&sync_raw).unwrap(),
1315                ops::validate_async(&async_raw).await.unwrap()
1316            );
1317        }
1318    }
1319}