Skip to main content

fasm_storage/
flatengine.rs

1//! The flat directory layout engine over a [`RawKv`] view.
2//!
3//! One layout, written and tested once here; the flat backends
4//! (btreemap, redb) implement [`RawKv`] over their transaction views and
5//! route every operation through [`FlatEngine`]. FDB does not use this —
6//! it uses FDB's native directory layer over the same row layouts (the
7//! [`crate::flatdir`] module documents the shared layouts).
8//!
9//! The engine's layout is a verbatim port of FoundationDB's
10//! `DirectoryLayer` (see [`crate::flatdir`]): a node tree of allocated
11//! prefixes (packed `i64`s from the High Contention Allocator), a version
12//! row, and HCA counter/recent rows, all under the `0xFE` node region.
13//! Data keys are `prefix ‖ key` in the `0x00`–`0xFD` region; `0xFF` is
14//! reserved.
15//!
16//! Stores are opened lazily: a fresh store (no version row) answers
17//! empty on reads, and the first create writes the version row. A store
18//! whose version row this layout does not read fails every operation
19//! with [`FlatError::Foreign`].
20
21use core::ops::Bound;
22use rand::rng as thread_rng;
23
24use crate::flatdir::layout::{ROOT_PATH_SEGMENT, data_region};
25use crate::flatdir::ops;
26use crate::key::validate_dir;
27use crate::rawkv::RawKv;
28use crate::stream::KvPair;
29
30/// Re-exported for the backends' error types (defined with the layout
31/// machinery it guards).
32pub use crate::flatdir::error::FlatError;
33
34/// The flat directory layout over a raw byte view.
35///
36/// Not itself a [`KvStore`](crate::KvStore): it has no async boundary and
37/// no engine error identity. The flat backends wrap it.
38///
39/// Directory paths are the fasm form (`&[&[u8]]`, UTF-8, validated with
40/// [`validate_dir`]); each fasm directory maps to the layer path
41/// `[ROOT_PATH_SEGMENT] ‖ dir`, so the fasm root `[]` is the layer's
42/// anchor directory — a real, allocated node, never the layer root.
43pub struct FlatEngine<R: RawKv> {
44    raw: R,
45}
46
47impl<R: RawKv> FlatEngine<R> {
48    /// Wrap a raw view.
49    pub fn new(raw: R) -> Self {
50        Self { raw }
51    }
52
53    /// The underlying view, for backends that need to reach it directly
54    /// (streaming, raw-handle accessors, the open-time probe).
55    pub fn raw(&self) -> &R {
56        &self.raw
57    }
58
59    /// The mutable underlying view.
60    pub fn raw_mut(&mut self) -> &mut R {
61        &mut self.raw
62    }
63
64    /// The layer path for a fasm directory: the anchor segment plus the
65    /// directory's segments (already UTF-8-validated by the caller).
66    fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
67        let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
68        v.push(ROOT_PATH_SEGMENT.as_bytes());
69        v.extend_from_slice(dir);
70        v
71    }
72
73    // -- directory resolution ---------------------------------------------
74
75    /// Resolve `dir` to its allocated prefix.
76    ///
77    /// `Ok(None)` when the store is fresh or the directory does not
78    /// exist. `Err(FlatError::Foreign)` when the store's version row is
79    /// one this layout does not read; `Err(FlatError::Corrupt)` when a
80    /// node row's value is malformed. Write operations use
81    /// [`allocate_dir`](Self::allocate_dir) instead.
82    pub fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
83        validate_dir(dir).map_err(FlatError::Key)?;
84        ops::check_version_read(&self.raw)?;
85        ops::find(&self.raw, &Self::layer_path(dir))
86    }
87
88    /// Resolve `dir`, allocating every missing directory (and only
89    /// those) along the way — the anchor included, which is what writes
90    /// the version row on a fresh store. Returns the resolved prefix.
91    ///
92    /// Creation is recursive on the *path*: creating `[a, b]` creates
93    /// both `a` and `b` (lazy parent creation, verbatim from the layer).
94    /// Each new node takes a candidate from the HCA; the allocation and
95    /// the node rows land in the same transaction view, so a rolled-back
96    /// creation leaves no trace. Idempotent: an existing directory
97    /// resolves to its prefix without a new allocation.
98    pub fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
99        validate_dir(dir).map_err(FlatError::Key)?;
100        let mut rng = thread_rng();
101        ops::create_or_open(&mut self.raw, &Self::layer_path(dir), true, &mut rng)
102            .map(|p| p.expect("create_or_open with creation returns Some"))
103    }
104
105    // -- data operations ----------------------------------------------------
106
107    /// Get `key` within `dir`. A missing directory yields `Ok(None)`.
108    pub fn get(&self, dir: &[&[u8]], key: &[u8]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
109        let Some(prefix) = self.prefix_of(dir)? else {
110            return Ok(None);
111        };
112        let mut raw_key = prefix;
113        raw_key.extend_from_slice(key);
114        Ok(self.raw.get(&raw_key)?)
115    }
116
117    /// Scan within `dir` between `start` and `end` (bounds over the key
118    /// part), ascending or descending. A missing directory yields no rows.
119    /// The returned keys are the within-directory keys.
120    pub fn scan(
121        &self,
122        dir: &[&[u8]],
123        start: Bound<&[u8]>,
124        end: Bound<&[u8]>,
125        forward: bool,
126    ) -> Result<Vec<KvPair>, FlatError<R::Error>> {
127        let Some(prefix) = self.prefix_of(dir)? else {
128            return Ok(Vec::new());
129        };
130        let owned = map_bounds(&prefix, start, end);
131        if raw_range_empty(&owned.0, &owned.1) {
132            return Ok(Vec::new());
133        }
134        let (rs, re) = bounds_ref(&owned);
135        let rows = self.raw.scan(rs, re, forward)?;
136        let plen = prefix.len();
137        Ok(rows
138            .into_iter()
139            .map(|pair| KvPair {
140                key: pair.key[plen..].to_vec(),
141                value: pair.value,
142            })
143            .collect())
144    }
145
146    /// The raw engine range holding `dir`'s data for `start <= k < end`
147    /// (bounds over the within-directory key part): the resolved prefix
148    /// plus the raw start/end byte bounds, or `Ok(None)` when `dir` does
149    /// not exist or the bound pair names no keys.
150    ///
151    /// The seam for backends that stream a lazy cursor over the engine's
152    /// raw range (one page or one reseek at a time) instead of
153    /// [`scan`](Self::scan)'s materialized merge. The raw range is
154    /// `[start, end)` in the engine's whole keyspace; the keys a cursor
155    /// yields there carry the prefix, which the caller strips
156    /// (`prefix.len()` bytes) to get the within-directory key.
157    pub fn data_bounds(
158        &self,
159        dir: &[&[u8]],
160        start: Bound<&[u8]>,
161        end: Bound<&[u8]>,
162    ) -> Result<Option<DataBounds>, FlatError<R::Error>> {
163        let Some(prefix) = self.prefix_of(dir)? else {
164            return Ok(None);
165        };
166        let (rs, re) = map_bounds(&prefix, start, end);
167        if raw_range_empty(&rs, &re) {
168            return Ok(None);
169        }
170        Ok(Some(DataBounds {
171            prefix,
172            start: rs,
173            end: re,
174        }))
175    }
176
177    /// Set `key` within `dir`, allocating `dir` (and any missing
178    /// ancestor, and the anchor) if needed.
179    pub fn set(
180        &mut self,
181        dir: &[&[u8]],
182        key: &[u8],
183        value: &[u8],
184    ) -> Result<(), FlatError<R::Error>> {
185        let prefix = self.allocate_dir(dir)?;
186        let mut raw_key = prefix;
187        raw_key.extend_from_slice(key);
188        self.raw.insert(&raw_key, value)?;
189        Ok(())
190    }
191
192    /// Delete `key` within `dir` (a no-op if the directory or the key
193    /// does not exist).
194    pub fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
195        let Some(prefix) = self.prefix_of(dir)? else {
196            return Ok(());
197        };
198        let mut raw_key = prefix;
199        raw_key.extend_from_slice(key);
200        self.raw.delete(&raw_key)?;
201        Ok(())
202    }
203
204    /// Clear `start <= k < end` within `dir` (a no-op if the directory
205    /// does not exist).
206    pub fn clear_range(
207        &mut self,
208        dir: &[&[u8]],
209        start: Bound<&[u8]>,
210        end: Bound<&[u8]>,
211    ) -> Result<(), FlatError<R::Error>> {
212        let Some(prefix) = self.prefix_of(dir)? else {
213            return Ok(());
214        };
215        let owned = map_bounds(&prefix, start, end);
216        if raw_range_empty(&owned.0, &owned.1) {
217            return Ok(());
218        }
219        let (rs, re) = bounds_ref(&owned);
220        self.raw.clear_range(rs, re)?;
221        Ok(())
222    }
223
224    // -- directory navigation ----------------------------------------------
225
226    /// The immediate child segment names under `dir`, sorted ascending.
227    /// A missing directory yields an empty list.
228    pub fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
229        validate_dir(dir).map_err(FlatError::Key)?;
230        ops::check_version_read(&self.raw)?;
231        let Some(prefix) = ops::find(&self.raw, &Self::layer_path(dir))? else {
232            return Ok(Vec::new());
233        };
234        let names = ops::list_children(&self.raw, &prefix)?;
235        Ok(names.into_iter().map(|s| s.into_bytes()).collect())
236    }
237
238    /// Whether `dir` exists. The fasm root `[]` exists iff its anchor
239    /// node has been created (the store has been written); any other
240    /// directory exists iff its node row is present — a directory with
241    /// zero data keys still exists.
242    pub fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
243        validate_dir(dir).map_err(FlatError::Key)?;
244        ops::check_version_read(&self.raw)?;
245        Ok(ops::find(&self.raw, &Self::layer_path(dir))?.is_some())
246    }
247
248    /// Remove `dir` recursively: its subdirectories (node rows and data)
249    /// and its own key data. `Ok(true)` if it existed, `Ok(false)`
250    /// otherwise. The root is not removable.
251    pub fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
252        validate_dir(dir).map_err(FlatError::Key)?;
253        if dir.is_empty() {
254            // The fasm root maps to the layer's anchor directory — a
255            // real node. Removing it would strand every directory under
256            // it; the layer's own empty-path refusal is a second,
257            // unreachable barrier.
258            return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
259        }
260        ops::check_version_read(&self.raw)?;
261        ops::remove_dir(&mut self.raw, &Self::layer_path(dir))
262    }
263}
264
265/// The raw engine range of one directory's data: the resolved prefix and
266/// the raw byte bounds over the engine's whole keyspace. The start bound
267/// carries its own inclusion (`Included`/`Excluded`); the end bound is
268/// always `Excluded`. Cursor-yielding keys carry the prefix; strip
269/// `prefix.len()` bytes to get the within-directory key.
270pub struct DataBounds {
271    /// The directory's allocated prefix.
272    pub prefix: Vec<u8>,
273    /// Raw start bound.
274    pub start: Bound<Vec<u8>>,
275    /// Raw end bound, exclusive.
276    pub end: Bound<Vec<u8>>,
277}
278
279impl core::fmt::Debug for DataBounds {
280    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
281        // Lengths only: a `Debug` panic line must not dump the raw bound
282        // bytes, which embed the key material of a live directory.
283        f.debug_struct("DataBounds")
284            .field("prefix_len", &self.prefix.len())
285            .field("start", &bound_len(&self.start))
286            .field("end", &bound_len(&self.end))
287            .finish()
288    }
289}
290
291fn bound_len(b: &Bound<Vec<u8>>) -> String {
292    match b {
293        Bound::Unbounded => "unbounded".to_owned(),
294        Bound::Included(v) => format!("incl({} bytes)", v.len()),
295        Bound::Excluded(v) => format!("excl({} bytes)", v.len()),
296    }
297}
298
299/// Borrow the owned bounds of a mapped range as slice bounds, for
300/// [`RawKv::scan`]/[`RawKv::clear_range`].
301fn bounds_ref(b: &(Bound<Vec<u8>>, Bound<Vec<u8>>)) -> (Bound<&[u8]>, Bound<&[u8]>) {
302    (bound_ref(&b.0), bound_ref(&b.1))
303}
304
305fn bound_ref(b: &Bound<Vec<u8>>) -> Bound<&[u8]> {
306    match b {
307        Bound::Unbounded => Bound::Unbounded,
308        Bound::Included(v) => Bound::Included(v.as_slice()),
309        Bound::Excluded(v) => Bound::Excluded(v.as_slice()),
310    }
311}
312
313/// The exclusive raw end of `prefix`'s data region.
314///
315/// [`data_region`] returns a `Bound`; this is its `Excluded` byte vector,
316/// for callers that need the owned form.
317fn data_end_exclusive(prefix: &[u8]) -> Vec<u8> {
318    match data_region(prefix).1 {
319        Bound::Excluded(b) => b,
320        _ => unreachable!("data_region end is always Excluded"),
321    }
322}
323
324/// Map key-part bounds onto the raw range under `prefix`.
325///
326/// Within one directory the mapping `prefix ‖ k` is monotone, so the raw
327/// range stays inside the directory's data region:
328///
329/// - start `Included(k)`  -> raw `Included(prefix ‖ k)`
330/// - start `Excluded(k)`  -> raw `Excluded(prefix ‖ k)`
331/// - start unbounded      -> raw `Included(prefix)` (the region start: the
332///   directory's empty key sits at the prefix itself)
333/// - end `Excluded(k)`    -> raw `Excluded(prefix ‖ k)`
334/// - end `Included(k)`    -> raw `Excluded(prefix ‖ k ‖ [0x00])`:
335///   `prefix ‖ k ‖ [0x00]` is the raw lexicographic immediate successor of
336///   the key's raw form (a byte string's smallest greater byte string is
337///   itself with a `0x00` appended), and it always lies inside the region
338///   because it is an extension of `prefix`
339/// - end unbounded        -> raw `Excluded` of the region end
340///   (`next_prefix(prefix)`)
341///
342/// Note the two successor notions: the end bound uses the raw immediate
343/// successor (`‖ [0x00]`), while region ends use the prefix-block successor
344/// ([`crate::keyspace::next_prefix`]).
345///
346/// The range may name no keys (for example `Excluded(k)` to
347/// `Excluded(k)`); callers check with [`raw_range_empty`].
348fn map_bounds(
349    prefix: &[u8],
350    start: Bound<&[u8]>,
351    end: Bound<&[u8]>,
352) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
353    let mk = |k: &[u8]| {
354        let mut raw = prefix.to_vec();
355        raw.extend_from_slice(k);
356        raw
357    };
358    let rs = match start {
359        Bound::Unbounded => Bound::Included(prefix.to_vec()),
360        Bound::Included(k) => Bound::Included(mk(k)),
361        Bound::Excluded(k) => Bound::Excluded(mk(k)),
362    };
363    let re = match end {
364        Bound::Unbounded => Bound::Excluded(data_end_exclusive(prefix)),
365        Bound::Excluded(k) => Bound::Excluded(mk(k)),
366        Bound::Included(k) => {
367            let mut raw = mk(k);
368            raw.push(0x00);
369            Bound::Excluded(raw)
370        }
371    };
372    (rs, re)
373}
374
375/// Whether a raw `(start, end)` bound pair names no keys at all.
376///
377/// Only `Excluded` end bounds occur (see [`map_bounds`]), so the range is
378/// empty exactly when the start bound reaches or passes the end bound.
379fn raw_range_empty(start: &Bound<Vec<u8>>, end: &Bound<Vec<u8>>) -> bool {
380    match (start, end) {
381        (Bound::Included(a), Bound::Excluded(b)) => a >= b,
382        (Bound::Excluded(a), Bound::Excluded(b)) => a >= b,
383        (Bound::Unbounded, _) => false,
384        (_, Bound::Unbounded) => false,
385        _ => unreachable!("end bounds are always Excluded"),
386    }
387}
388
389// -- test double -----------------------------------------------------------
390
391/// An in-memory [`RawKv`] for testing the layout independently of any
392/// backend. Shared by the flatdir module's test suites.
393#[cfg(test)]
394pub(crate) struct Mem {
395    map: core::cell::RefCell<std::collections::BTreeMap<Vec<u8>, Vec<u8>>>,
396}
397
398#[cfg(test)]
399impl Default for Mem {
400    fn default() -> Self {
401        Self {
402            map: core::cell::RefCell::new(std::collections::BTreeMap::new()),
403        }
404    }
405}
406
407#[cfg(test)]
408impl RawKv for Mem {
409    type Error = std::convert::Infallible;
410
411    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
412        Ok(self.map.borrow().get(key).cloned())
413    }
414
415    fn scan(
416        &self,
417        start: Bound<&[u8]>,
418        end: Bound<&[u8]>,
419        forward: bool,
420    ) -> Result<Vec<KvPair>, Self::Error> {
421        let map = self.map.borrow();
422        let rows: Vec<KvPair> = map
423            .iter()
424            .filter(|(k, _)| {
425                let k = &k[..];
426                let above = match start {
427                    Bound::Unbounded => true,
428                    Bound::Included(s) => k >= s,
429                    Bound::Excluded(s) => k > s,
430                };
431                let below = match end {
432                    Bound::Unbounded => true,
433                    Bound::Excluded(e) => k < e,
434                    Bound::Included(e) => k <= e,
435                };
436                above && below
437            })
438            .map(|(k, v)| KvPair {
439                key: k.clone(),
440                value: v.clone(),
441            })
442            .collect();
443        if forward {
444            Ok(rows)
445        } else {
446            Ok(rows.into_iter().rev().collect())
447        }
448    }
449
450    fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
451        self.map.borrow_mut().insert(key.to_vec(), value.to_vec());
452        Ok(())
453    }
454
455    fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
456        self.map.borrow_mut().remove(key);
457        Ok(())
458    }
459
460    fn clear_range(&mut self, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Result<(), Self::Error> {
461        let mut map = self.map.borrow_mut();
462        let keys: Vec<Vec<u8>> = map
463            .keys()
464            .filter(|k| {
465                let k = &k[..];
466                let above = match start {
467                    Bound::Unbounded => true,
468                    Bound::Included(s) => k >= s,
469                    Bound::Excluded(s) => k > s,
470                };
471                let below = match end {
472                    Bound::Unbounded => true,
473                    Bound::Excluded(e) => k < e,
474                    Bound::Included(e) => k <= e,
475                };
476                above && below
477            })
478            .cloned()
479            .collect();
480        for k in keys {
481            map.remove(&k);
482        }
483        Ok(())
484    }
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490    use crate::key::KeyError;
491
492    fn engine() -> FlatEngine<Mem> {
493        FlatEngine::new(Mem::default())
494    }
495
496    fn ok<T>(r: Result<T, FlatError<std::convert::Infallible>>) -> T {
497        r.unwrap()
498    }
499
500    // -- fresh stores ------------------------------------------------------
501
502    #[test]
503    fn fresh_reads_return_empty_and_first_write_initialises() {
504        let mut e = engine();
505        assert_eq!(ok(e.prefix_of(&[])), None);
506        assert_eq!(ok(e.get(&[], b"k")), None);
507        assert!(ok(e.scan(&[], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
508        assert!(ok(e.list_dirs(&[])).is_empty());
509        assert!(!ok(e.dir_exists(&[])));
510        // Removing from a fresh store is a miss, not an error.
511        assert!(!ok(e.remove_dir(&[b"a"])));
512        // The first write initialises the store lazily (version row,
513        // anchor node).
514        ok(e.set(&[], b"k", b"v"));
515        assert!(ok(e.dir_exists(&[])));
516        assert_eq!(ok(e.get(&[], b"k")), Some(b"v".to_vec()));
517        // The version row is the layout's 12-byte 1.0.0.
518        let version = e
519            .raw()
520            .map
521            .borrow()
522            .get(crate::flatdir::layout::VERSION_KEY)
523            .cloned();
524        assert_eq!(
525            version,
526            Some(crate::flatdir::layout::LAYOUT_VERSION.to_vec())
527        );
528    }
529
530    /// A first write in a one-segment directory produces exactly nine
531    /// raw rows: the version row, the anchor node's child and layer
532    /// rows, the directory node's child and layer rows, the HCA
533    /// counter row, two HCA recent rows, and the data row. The root
534    /// node carries no layer row.
535    #[test]
536    fn a_first_set_produces_exactly_nine_raw_rows() {
537        let mut e = engine();
538        ok(e.set(&[b"a"], b"k", b"v"));
539        let map = e.raw().map.borrow();
540        assert_eq!(map.len(), 9, "unexpected raw rows: {map:?}");
541    }
542
543    // -- foreign stores ------------------------------------------------------
544
545    #[test]
546    fn reads_on_a_foreign_store_fail_closed() {
547        // A version row this layout does not read (major = 2): every
548        // operation fails with `Foreign` rather than answering over
549        // someone else's data.
550        let mut e = engine();
551        let mut v = [0u8; 12];
552        v[0..4].copy_from_slice(&2u32.to_le_bytes());
553        e.raw_mut()
554            .insert(crate::flatdir::layout::VERSION_KEY, &v)
555            .unwrap();
556        assert_eq!(e.prefix_of(&[]), Err(FlatError::Foreign));
557        assert_eq!(e.get(&[], b"k"), Err(FlatError::Foreign));
558        assert_eq!(
559            e.scan(&[], Bound::Unbounded, Bound::Unbounded, true),
560            Err(FlatError::Foreign)
561        );
562        assert!(matches!(
563            e.data_bounds(&[], Bound::Unbounded, Bound::Unbounded),
564            Err(FlatError::Foreign)
565        ));
566        assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
567        assert_eq!(e.list_dirs(&[]), Err(FlatError::Foreign));
568        assert_eq!(e.set(&[], b"k", b"v"), Err(FlatError::Foreign));
569        assert_eq!(e.remove_dir(&[b"a"]), Err(FlatError::Foreign));
570    }
571
572    #[test]
573    fn a_malformed_version_row_fails_closed() {
574        // A short version value is not a version: fail closed.
575        let mut e = engine();
576        e.raw_mut()
577            .insert(crate::flatdir::layout::VERSION_KEY, &[1, 0])
578            .unwrap();
579        assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
580    }
581
582    #[test]
583    fn a_corrupt_node_value_is_corrupt_not_a_panic() {
584        // A healthy store whose anchor child row's value is then flipped
585        // to a non-packing byte string: the node walk reports `Corrupt`
586        // rather than panicking.
587        let mut e = engine();
588        e.set(&[b"dir"], b"k", b"v").unwrap();
589        // The anchor child row sits under the root node and is the only
590        // row there tagged with INT(0) (0x14): the HCA and version rows
591        // are tagged 0x01 (BYTES) and sort before it.
592        let child_tag = crate::flatdir::layout::ROOT_NODE
593            .iter()
594            .copied()
595            .chain(std::iter::once(0x14))
596            .collect::<Vec<u8>>();
597        let row_key = e
598            .raw()
599            .map
600            .borrow()
601            .iter()
602            .find(|(k, _)| k.starts_with(&child_tag))
603            .expect("the anchor child row")
604            .0
605            .clone();
606        e.raw_mut()
607            .map
608            .borrow_mut()
609            .insert(row_key, vec![0x99, 0x00]);
610        assert_eq!(e.get(&[b"dir"], b"k"), Err(FlatError::Corrupt));
611        assert_eq!(
612            e.scan(&[b"dir"], Bound::Unbounded, Bound::Unbounded, true),
613            Err(FlatError::Corrupt)
614        );
615        assert_eq!(e.remove_dir(&[b"dir"]), Err(FlatError::Corrupt));
616    }
617
618    // -- allocation ---------------------------------------------------------
619
620    #[test]
621    fn allocation_is_recursive_and_stable() {
622        let mut e = engine();
623        let p = ok(e.allocate_dir(&[b"a", b"b"]));
624        // Re-resolving finds the same prefix (no new allocation).
625        assert_eq!(ok(e.prefix_of(&[b"a", b"b"])), Some(p.clone()));
626        // Siblings get different prefixes; the ancestor resolves too.
627        let q = ok(e.allocate_dir(&[b"a", b"c"]));
628        assert_ne!(p, q);
629        assert!(ok(e.prefix_of(&[b"a"])).is_some());
630        // Every allocated prefix starts in the packed-i64 band
631        // (0x0c..=0x1c): never the meta (0xFE) or reserved (0xFF) region.
632        let dirs: [[&[u8]; 2]; 2] = [[b"a" as &[u8], b"b"], [b"a" as &[u8], b"c"]];
633        for dir in dirs {
634            let p = ok(e.prefix_of(&dir)).unwrap();
635            assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?}");
636        }
637    }
638
639    #[test]
640    fn many_allocations_stay_in_the_data_region() {
641        // 300 directories (past the first HCA window advance): every
642        // allocated prefix stays in the data region and every data key
643        // lands outside the meta region.
644        let mut e = engine();
645        for i in 0..300u32 {
646            let d = format!("d{i:03}").into_bytes();
647            let d = [d.as_slice()];
648            let p = ok(e.allocate_dir(&d));
649            assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?} at {i}");
650        }
651    }
652
653    #[test]
654    fn resolve_missing_dir_is_none() {
655        let mut e = engine();
656        ok(e.set(&[], b"k", b"v"));
657        assert_eq!(ok(e.prefix_of(&[b"nope"])), None);
658        assert_eq!(ok(e.prefix_of(&[b"nope", b"deeper"])), None);
659    }
660
661    // -- data operations ----------------------------------------------------
662
663    #[test]
664    fn set_get_delete_round_trips_per_dir() {
665        let mut e = engine();
666        ok(e.set(&[b"asset", b"btc"], b"k", b"v"));
667        assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), Some(b"v".to_vec()));
668        // Same key, different directory: isolated.
669        assert_eq!(ok(e.get(&[b"asset"], b"k")), None);
670        assert_eq!(ok(e.get(&[b"btc"], b"k")), None);
671        ok(e.delete(&[b"asset", b"btc"], b"k"));
672        assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), None);
673    }
674
675    #[test]
676    fn scan_orders_within_dir_only() {
677        let mut e = engine();
678        for k in [b"b", b"a", b"c"] {
679            ok(e.set(&[b"d"], k, k));
680            ok(e.set(&[b"other"], k, k));
681        }
682        let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true));
683        let keys: Vec<Vec<u8>> = rows.iter().map(|p| p.key.clone()).collect();
684        assert_eq!(keys, vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]);
685        let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, false));
686        assert_eq!(rows.first().unwrap().key, b"c".to_vec());
687    }
688
689    #[test]
690    fn scan_bound_matrix() {
691        let mut e = engine();
692        for k in [b"a", b"b", b"c", b"\xff"] {
693            ok(e.set(&[b"d"], k, b"v"));
694        }
695        let get = |s: core::ops::Bound<&[u8]>,
696                   en: core::ops::Bound<&[u8]>,
697                   e: &FlatEngine<Mem>|
698         -> Vec<Vec<u8>> {
699            ok(e.scan(&[b"d"], s, en, true))
700                .into_iter()
701                .map(|pair| pair.key)
702                .collect()
703        };
704        assert_eq!(
705            get(Bound::Included(b"b"), Bound::Excluded(b"c"), &e),
706            vec![b"b".to_vec()]
707        );
708        assert_eq!(
709            get(Bound::Excluded(b"b"), Bound::Included(b"c"), &e),
710            vec![b"c".to_vec()]
711        );
712        assert_eq!(
713            get(Bound::Excluded(&[0xFFu8]), Bound::Unbounded, &e),
714            Vec::<Vec<u8>>::new()
715        );
716        assert_eq!(
717            get(Bound::Unbounded, Bound::Included(&[0xFFu8]), &e),
718            vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), vec![0xFF]]
719        );
720        assert_eq!(
721            get(Bound::Included(&[0xFFu8]), Bound::Unbounded, &e),
722            vec![vec![0xFF]]
723        );
724        // An Excluded bound at all-0xFF: the range is empty.
725        assert_eq!(
726            get(Bound::Excluded(&[0xFFu8]), Bound::Excluded(&[0xFFu8]), &e),
727            Vec::<Vec<u8>>::new()
728        );
729    }
730
731    #[test]
732    fn clear_range_clears_within_dir_only() {
733        let mut e = engine();
734        for k in [b"a", b"b", b"c"] {
735            ok(e.set(&[b"d"], k, b"v"));
736            ok(e.set(&[b"e"], k, b"v"));
737        }
738        ok(e.clear_range(&[b"d"], Bound::Included(b"b"), Bound::Excluded(b"c")));
739        assert_eq!(ok(e.get(&[b"d"], b"a")), Some(b"v".to_vec()));
740        assert_eq!(ok(e.get(&[b"d"], b"b")), None);
741        assert_eq!(ok(e.get(&[b"d"], b"c")), Some(b"v".to_vec()));
742        assert_eq!(ok(e.get(&[b"e"], b"b")), Some(b"v".to_vec()));
743        // Whole directory.
744        ok(e.clear_range(&[b"d"], Bound::Unbounded, Bound::Unbounded));
745        assert!(ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
746        // The directory still exists (data-free directories are entities).
747        assert!(ok(e.dir_exists(&[b"d"])));
748    }
749
750    // -- navigation ---------------------------------------------------------
751
752    #[test]
753    fn nav_list_exists_remove() {
754        let mut e = engine();
755        ok(e.set(&[b"a", b"1"], b"k", b"v"));
756        ok(e.set(&[b"a", b"2"], b"k", b"v"));
757        ok(e.set(&[b"b"], b"k", b"v"));
758        assert_eq!(ok(e.list_dirs(&[])), vec![b"a".to_vec(), b"b".to_vec()]);
759        assert_eq!(ok(e.list_dirs(&[b"a"])), vec![b"1".to_vec(), b"2".to_vec()]);
760        assert!(ok(e.dir_exists(&[b"a"])));
761        assert!(ok(e.dir_exists(&[b"a", b"1"])));
762        assert!(!ok(e.dir_exists(&[b"a", b"3"])));
763        // A directory with no data keys still exists.
764        ok(e.allocate_dir(&[b"empty"]));
765        assert!(ok(e.dir_exists(&[b"empty"])));
766        assert!(ok(e.list_dirs(&[b"empty"])).is_empty());
767        // Missing: empty list, not an error.
768        assert!(ok(e.list_dirs(&[b"nope"])).is_empty());
769        assert!(!ok(e.dir_exists(&[b"nope"])));
770    }
771
772    #[test]
773    fn nav_remove_is_recursive() {
774        let mut e = engine();
775        ok(e.set(&[b"a", b"b", b"c"], b"k1", b"v1"));
776        ok(e.set(&[b"a", b"b"], b"k2", b"v2"));
777        ok(e.set(&[b"a", b"d"], b"k3", b"v3"));
778        ok(e.set(&[b"z"], b"k4", b"v4"));
779        // Remove the middle directory: b/c and b go, a/d stays.
780        assert!(ok(e.remove_dir(&[b"a", b"b"])));
781        assert_eq!(ok(e.get(&[b"a", b"b", b"c"], b"k1")), None);
782        assert_eq!(ok(e.get(&[b"a", b"b"], b"k2")), None);
783        assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), Some(b"v3".to_vec()));
784        assert!(ok(e.dir_exists(&[b"a"])));
785        assert!(!ok(e.dir_exists(&[b"a", b"b"])));
786        // Removing a leaf directory removes it and its data.
787        assert!(ok(e.remove_dir(&[b"a", b"d"])));
788        assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), None);
789        // Missing: false.
790        assert!(!ok(e.remove_dir(&[b"a", b"b"])));
791        // Unaffected directories keep their data.
792        assert_eq!(ok(e.get(&[b"z"], b"k4")), Some(b"v4".to_vec()));
793    }
794
795    #[test]
796    fn nav_root_is_not_removable() {
797        let mut e = engine();
798        ok(e.set(&[], b"k", b"v"));
799        assert_eq!(
800            e.remove_dir(&[]),
801            Err(FlatError::Key(KeyError::RootNotRemovable))
802        );
803        // The root survived.
804        assert!(ok(e.dir_exists(&[])));
805    }
806
807    #[test]
808    fn nav_rejects_non_utf8() {
809        let mut e = engine();
810        let seg: &[u8] = b"\xFF\xFE";
811        let bad = [seg];
812        assert_eq!(
813            e.list_dirs(&bad),
814            Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
815        );
816        assert_eq!(
817            e.remove_dir(&bad),
818            Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
819        );
820    }
821
822    #[test]
823    fn remove_and_recreate_work() {
824        // Removal leaves no trace that blocks re-creation: the HCA may
825        // even re-claim the same candidate value (FDB semantics — the
826        // allocator tracks windows, not used prefixes); what matters is
827        // that the recreated directory is fully functional and no stale
828        // row of the old one is read.
829        let mut e = engine();
830        ok(e.set(&[b"x"], b"k", b"v1"));
831        let p1 = ok(e.prefix_of(&[b"x"])).unwrap();
832        assert!(ok(e.remove_dir(&[b"x"])));
833        assert!(!ok(e.dir_exists(&[b"x"])));
834        assert_eq!(ok(e.get(&[b"x"], b"k")), None);
835        ok(e.set(&[b"x"], b"k", b"v2"));
836        let p2 = ok(e.prefix_of(&[b"x"])).unwrap();
837        assert_eq!(ok(e.get(&[b"x"], b"k")), Some(b"v2".to_vec()));
838        // If the allocator re-claimed the same prefix, the old data row
839        // was cleared by the removal (same raw key, new value wins).
840        if p1 == p2 {
841            assert_eq!(
842                ok(e.scan(&[b"x"], Bound::Unbounded, Bound::Unbounded, true)).len(),
843                1
844            );
845        }
846        // The store still validates as a whole layout.
847        assert!(ops::validate(e.raw()).is_ok());
848    }
849}