~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
638 lines · 22.4 KB Raw History
//! The Merkle Search Tree changed in place: a commit reads only the nodes on
//! the paths to the keys it writes, found by CID, and makes new nodes only
//! for those it changes. The tree it leaves is the one `mst::build_tree`
//! builds of the same keys: each node holds the keys of its level, `depth`,
//! between those of the level above, with a node of no keys but a left
//! subtree for each level a subtree of keys only below skips, and the root at
//! the level of the deepest key.
//!
//! A key put at its level splits the subtree its place is in, at it; a key
//! taken out merges the subtrees beside it; keys of lower levels go down
//! into the subtree between the keys of this one that they fall between.

use crate::data::{V, cid_of, decode, encode};
use crate::mst::depth;
use std::collections::HashMap;
use std::sync::Arc;

/// A subtree: a node the store holds, by CID, or one made by this edit.
pub enum Tree {
    Stored(Vec<u8>),
    Built(Box<Node>),
}

/// A node: the subtree left of its first entry, and its entries, each a
/// key, its value's CID and the subtree right of it.
#[derive(Default)]
pub struct Node {
    pub left: Option<Tree>,
    pub entries: Vec<(Vec<u8>, Vec<u8>, Option<Tree>)>,
}

/// Find a block by CID.
pub type Fetch<'a> = &'a dyn Fn(&[u8]) -> Option<Arc<[u8]>>;

/// What `Edit::apply` answers: the new root's CID, and the nodes made, by CID.
pub type Applied = (Vec<u8>, HashMap<Vec<u8>, Vec<u8>>);

/// A node: its CID and its block.
pub type NodeBlock = (Vec<u8>, Arc<[u8]>);

/// A key and its record's CID.
pub type KeyCid = (Vec<u8>, Vec<u8>);

/// The bytes of the empty tree's one node.
pub fn empty_node() -> Vec<u8> {
    encode(&V::Map(vec![
        ("e".into(), V::Arr(vec![])),
        ("l".into(), V::Null),
    ]))
}

/// A node's block parsed: Err for one that is not a tree node.
pub fn parse(bytes: &[u8]) -> Result<Node, String> {
    let V::Map(m) = decode(bytes)? else {
        return Err("a tree node that is not a map".into());
    };
    let get = |k: &str| m.iter().find(|(n, _)| n == k).map(|(_, v)| v);
    let link = |v: Option<&V>| match v {
        Some(V::Null) => Ok(None),
        Some(V::Link(l)) => Ok(Some(Tree::Stored(l.clone()))),
        _ => Err("a subtree that is no link or null".to_string()),
    };
    if m.len() != 2 {
        return Err("a tree node not exactly l and e".into());
    }
    let left = link(get("l"))?;
    let Some(V::Arr(es)) = get("e") else {
        return Err("a tree node with no list e".into());
    };
    let mut entries = Vec::with_capacity(es.len());
    let mut prev: Vec<u8> = Vec::new();
    for e in es {
        let V::Map(e) = e else {
            return Err("an entry not a map".into());
        };
        let f = |k: &str| e.iter().find(|(n, _)| n == k).map(|(_, v)| v);
        let (Some(V::Int(p)), Some(V::Bytes(k)), Some(V::Link(v)), 4) =
            (f("p"), f("k"), f("v"), e.len())
        else {
            return Err("an entry not exactly p, k, v and t".into());
        };
        let p = usize::try_from(*p)
            .ok()
            .filter(|p| *p <= prev.len())
            .ok_or("a prefix longer than the key before")?;
        let mut key = prev[..p].to_vec();
        key.extend_from_slice(k);
        if entries
            .last()
            .is_some_and(|(last, _, _): &(Vec<u8>, Vec<u8>, Option<Tree>)| *last >= key)
        {
            return Err("keys out of order".into());
        }
        prev.clone_from(&key);
        entries.push((key, v.clone(), link(f("t"))?));
    }
    Ok(Node { left, entries })
}

/// An entry of a node being encoded: its key, its record's CID, and the CID
/// of the subtree after it.
type EntryRef<'a> = (&'a [u8], &'a [u8], Option<&'a [u8]>);

/// A node's block, as `build_tree` makes it.
fn encode_node(left: Option<&[u8]>, entries: &[EntryRef]) -> Vec<u8> {
    let mut list = Vec::with_capacity(entries.len());
    let mut prev: &[u8] = &[];
    for (key, v, t) in entries {
        let p = prev
            .iter()
            .zip(key.iter())
            .take_while(|(a, b)| a == b)
            .count();
        list.push(V::Map(vec![
            ("p".into(), V::Int(p as i64)),
            ("k".into(), V::Bytes(key[p..].to_vec())),
            ("v".into(), V::Link(v.to_vec())),
            ("t".into(), t.map_or(V::Null, |t| V::Link(t.to_vec()))),
        ]));
        prev = key;
    }
    encode(&V::Map(vec![
        ("l".into(), left.map_or(V::Null, |l| V::Link(l.to_vec()))),
        ("e".into(), V::Arr(list)),
    ]))
}

/// An edit of a tree: the nodes it read from the store, which those it
/// makes replace.
pub struct Edit<'a> {
    fetch: Fetch<'a>,
    /// The CIDs of the stored nodes it opened.
    pub opened: Vec<Vec<u8>>,
}

impl<'a> Edit<'a> {
    pub fn new(fetch: Fetch<'a>) -> Edit<'a> {
        Edit {
            fetch,
            opened: Vec::new(),
        }
    }

    /// A subtree's node, to change: one stored is read and parsed.
    fn open(&mut self, t: Tree) -> Result<Node, String> {
        match t {
            Tree::Built(n) => Ok(*n),
            Tree::Stored(cid) => {
                let bytes = (self.fetch)(&cid).ok_or_else(|| {
                    format!("tree node {} missing", crate::data::cid_string(&cid))
                })?;
                let n = parse(&bytes)
                    .map_err(|e| format!("tree node {}: {e}", crate::data::cid_string(&cid)))?;
                self.opened.push(cid);
                Ok(n)
            }
        }
    }

    /// The level of the tree rooted at `root`: that of its keys; None for the
    /// empty tree.
    fn level_of(&mut self, root: &[u8]) -> Result<(Option<usize>, Node), String> {
        let n = self.open(Tree::Stored(root.to_vec()))?;
        Ok((n.entries.first().map(|(k, _, _)| depth(k)), n))
    }

    /// Make `changes`, sorted by key, each a key and its value's CID, or
    /// None to take it out, in the tree rooted at `root`. Answers the new
    /// root's CID and the nodes made, by CID.
    pub fn apply(
        &mut self,
        root: &[u8],
        changes: &[(Vec<u8>, Option<Vec<u8>>)],
    ) -> Result<Applied, String> {
        let (level, node) = self.level_of(root)?;
        let top = changes
            .iter()
            .filter(|(_, v)| v.is_some())
            .map(|(k, _)| depth(k))
            .max();
        // The empty tree's node has no keys: as no tree.
        let mut tree = level.map(|_| Tree::Built(Box::new(node)));
        let at = level.unwrap_or(0).max(top.unwrap_or(0));
        for _ in level.unwrap_or(at)..at {
            tree = Some(Tree::Built(Box::new(Node {
                left: tree,
                entries: vec![],
            })));
        }
        let mut tree = self.modify(at, tree, changes)?;
        // No node of no keys at the root.
        loop {
            match tree {
                None => break,
                Some(t) => {
                    let n = self.open(t)?;
                    if n.entries.is_empty() {
                        tree = n.left;
                    } else {
                        tree = Some(Tree::Built(Box::new(n)));
                        break;
                    }
                }
            }
        }
        let mut made = HashMap::new();
        let root = match tree {
            None => {
                let bytes = empty_node();
                let cid = cid_of(0x71, &bytes);
                made.insert(cid.clone(), bytes);
                cid
            }
            Some(t) => finish(t, &mut made),
        };
        Ok((root, made))
    }

    fn modify(
        &mut self,
        level: usize,
        tree: Option<Tree>,
        changes: &[(Vec<u8>, Option<Vec<u8>>)],
    ) -> Result<Option<Tree>, String> {
        if changes.is_empty() {
            return Ok(tree);
        }
        let mut n = match tree {
            None => Node::default(),
            Some(t) => self.open(t)?,
        };
        for (k, v) in changes.iter().filter(|(k, _)| depth(k) == level) {
            match n.entries.binary_search_by(|e| e.0.as_slice().cmp(k)) {
                Ok(i) => match v {
                    Some(v) => n.entries[i].1.clone_from(v),
                    None => {
                        let (_, _, right) = n.entries.remove(i);
                        let left = gap(&mut n, i).take();
                        let merged = self.merge(level.wrapping_sub(1), left, right)?;
                        *gap(&mut n, i) = merged;
                    }
                },
                Err(i) => {
                    if let Some(v) = v {
                        let g = gap(&mut n, i).take();
                        let (a, b) = self.split(level.wrapping_sub(1), g, k)?;
                        *gap(&mut n, i) = a;
                        n.entries.insert(i, (k.clone(), v.clone(), b));
                    }
                }
            }
        }
        let lower: Vec<&(Vec<u8>, Option<Vec<u8>>)> =
            changes.iter().filter(|(k, _)| depth(k) < level).collect();
        if !lower.is_empty() {
            let mut from = 0;
            for i in 0..=n.entries.len() {
                let end = match n.entries.get(i) {
                    Some((key, _, _)) => from + lower[from..].partition_point(|(k, _)| k < key),
                    None => lower.len(),
                };
                if end > from {
                    let sub: Vec<(Vec<u8>, Option<Vec<u8>>)> =
                        lower[from..end].iter().map(|c| (*c).clone()).collect();
                    let g = gap(&mut n, i).take();
                    *gap(&mut n, i) = self.modify(level - 1, g, &sub)?;
                }
                from = end;
            }
        }
        Ok(some(n))
    }

    /// Split a subtree at `key`, which it does not hold: those before it, and those after.
    fn split(
        &mut self,
        level: usize,
        tree: Option<Tree>,
        key: &[u8],
    ) -> Result<(Option<Tree>, Option<Tree>), String> {
        let Some(t) = tree else {
            return Ok((None, None));
        };
        let mut n = self.open(t)?;
        let i = n.entries.partition_point(|e| e.0.as_slice() < key);
        let g = gap(&mut n, i).take();
        let (a, b) = self.split(level.wrapping_sub(1), g, key)?;
        let right_entries = n.entries.split_off(i);
        *gap(&mut n, i) = a;
        let right = Node {
            left: b,
            entries: right_entries,
        };
        Ok((some(n), some(right)))
    }

    /// One subtree of the keys of two, all of `a`'s before all of `b`'s.
    fn merge(
        &mut self,
        level: usize,
        a: Option<Tree>,
        b: Option<Tree>,
    ) -> Result<Option<Tree>, String> {
        let (a, b) = match (a, b) {
            (None, x) | (x, None) => return Ok(x),
            (Some(a), Some(b)) => (a, b),
        };
        let mut na = self.open(a)?;
        let mut nb = self.open(b)?;
        let last = na.entries.len();
        let middle = self.merge(
            level.wrapping_sub(1),
            gap(&mut na, last).take(),
            nb.left.take(),
        )?;
        *gap(&mut na, last) = middle;
        na.entries.append(&mut nb.entries);
        Ok(some(na))
    }
}

/// A node, or none if it holds nothing.
fn some(n: Node) -> Option<Tree> {
    if n.entries.is_empty() && n.left.is_none() {
        None
    } else {
        Some(Tree::Built(Box::new(n)))
    }
}

/// The subtree in gap `i`: before entry 0 for `i == 0`, else after entry `i - 1`.
fn gap(n: &mut Node, i: usize) -> &mut Option<Tree> {
    if i == 0 {
        &mut n.left
    } else {
        &mut n.entries[i - 1].2
    }
}

/// A subtree's CID, its nodes made encoded into `made`, children first.
fn finish(t: Tree, made: &mut HashMap<Vec<u8>, Vec<u8>>) -> Vec<u8> {
    match t {
        Tree::Stored(cid) => cid,
        Tree::Built(n) => {
            let n = *n;
            let left = n.left.map(|l| finish(l, made));
            let entries: Vec<_> = n
                .entries
                .into_iter()
                .map(|(k, v, t)| (k, v, t.map(|t| finish(t, made))))
                .collect();
            let refs: Vec<EntryRef> = entries
                .iter()
                .map(|(k, v, t)| (k.as_slice(), v.as_slice(), t.as_deref()))
                .collect();
            let bytes = encode_node(left.as_deref(), &refs);
            let cid = cid_of(0x71, &bytes);
            made.insert(cid.clone(), bytes);
            cid
        }
    }
}

/// The nodes a search for `key` passes through from `root`, by CID, found
/// by `fetch`: in each it ends at the entry whose key it is, or else goes on
/// into the subtree before the first entry after it, and ends where there
/// is none. They prove the key's value, or its absence.
pub fn path(fetch: Fetch, root: &[u8], key: &[u8]) -> Result<Vec<NodeBlock>, String> {
    let mut out = Vec::new();
    let mut at = Some(root.to_vec());
    while let Some(cid) = at {
        let bytes = fetch(&cid).ok_or("a tree node missing")?;
        let n = parse(&bytes)?;
        out.push((cid, bytes));
        let i = n.entries.partition_point(|e| e.0.as_slice() < key);
        if n.entries.get(i).is_some_and(|e| e.0 == key) {
            break;
        }
        at = node_gap(n, i);
    }
    Ok(out)
}

fn node_gap(mut n: Node, i: usize) -> Option<Vec<u8>> {
    match gap(&mut n, i).take() {
        Some(Tree::Stored(c)) => Some(c),
        _ => None,
    }
}

/// The value's CID of `key` in the tree rooted at `root`, if it holds it.
pub fn get(fetch: Fetch, root: &[u8], key: &[u8]) -> Result<Option<Vec<u8>>, String> {
    let p = path(fetch, root, key)?;
    let Some((_, last)) = p.last() else {
        return Ok(None);
    };
    let n = parse(last)?;
    Ok(n.entries.into_iter().find(|e| e.0 == key).map(|e| e.1))
}

/// The nodes that undoing a change at `key` in the tree rooted at `root`
/// may need, by CID: those on the way to the key's position, and the edges
/// of the subtrees beside it (as `mst::Node::context`).
pub fn context(
    fetch: Fetch,
    root: &[u8],
    key: &[u8],
    out: &mut Vec<(Vec<u8>, Arc<[u8]>)>,
) -> Result<(), String> {
    let mut at = Some(root.to_vec());
    while let Some(cid) = at {
        let bytes = fetch(&cid).ok_or("a tree node missing")?;
        let n = parse(&bytes)?;
        out.push((cid, bytes));
        let i = n.entries.partition_point(|e| e.0.as_slice() < key);
        let found = n.entries.get(i).is_some_and(|e| e.0 == key);
        let (lo, hi) = (
            i.saturating_sub(1),
            (i + if found { 2 } else { 1 }).min(n.entries.len()),
        );
        let gaps: Vec<Option<Vec<u8>>> = (0..=n.entries.len())
            .map(|g| stored(if g == 0 { &n.left } else { &n.entries[g - 1].2 }))
            .collect();
        for s in gaps[lo..=hi].iter().flatten() {
            spine(fetch, s, true, out)?;
            spine(fetch, s, false, out)?;
        }
        if found {
            return Ok(());
        }
        at = gaps[i].clone();
    }
    Ok(())
}

fn stored(t: &Option<Tree>) -> Option<Vec<u8>> {
    match t {
        Some(Tree::Stored(c)) => Some(c.clone()),
        _ => None,
    }
}

/// A node and the chain of nodes down its right (or left) edge.
fn spine(
    fetch: Fetch,
    cid: &[u8],
    right: bool,
    out: &mut Vec<(Vec<u8>, Arc<[u8]>)>,
) -> Result<(), String> {
    let mut at = Some(cid.to_vec());
    while let Some(c) = at {
        let bytes = fetch(&c).ok_or("a tree node missing")?;
        let n = parse(&bytes)?;
        out.push((c, bytes));
        at = if right {
            n.entries.last().and_then(|e| stored(&e.2)).or_else(|| {
                if n.entries.is_empty() {
                    stored(&n.left)
                } else {
                    None
                }
            })
        } else {
            stored(&n.left)
        };
    }
    Ok(())
}

/// The entries of the tree rooted at `root` in key order, from the first
/// at or after `from`, at most `limit`, each its key and value's CID.
pub fn range(fetch: Fetch, root: &[u8], from: &[u8], limit: usize) -> Result<Vec<KeyCid>, String> {
    let mut out = Vec::new();
    walk(fetch, root, from, limit, &mut out)?;
    Ok(out)
}

fn walk(
    fetch: Fetch,
    cid: &[u8],
    from: &[u8],
    limit: usize,
    out: &mut Vec<(Vec<u8>, Vec<u8>)>,
) -> Result<(), String> {
    let bytes = fetch(cid).ok_or("a tree node missing")?;
    let n = parse(&bytes)?;
    let i = n.entries.partition_point(|e| e.0.as_slice() < from);
    let gaps: Vec<Option<Vec<u8>>> = (0..=n.entries.len())
        .map(|g| stored(if g == 0 { &n.left } else { &n.entries[g - 1].2 }))
        .collect();
    if let Some(g) = &gaps[i] {
        walk(fetch, g, from, limit, out)?;
    }
    for (j, (k, v, _)) in n.entries.iter().enumerate().skip(i) {
        if out.len() >= limit {
            return Ok(());
        }
        out.push((k.clone(), v.clone()));
        if let Some(g) = &gaps[j + 1] {
            walk(fetch, g, from, limit, out)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mst::{build_tree, event_nodes};
    use std::collections::{BTreeMap, HashSet};

    /// A deterministic sequence of numbers, for the tests' random draws.
    struct Rng(u64);
    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0
        }
        fn below(&mut self, n: u64) -> u64 {
            self.next() % n
        }
    }

    fn value(n: u64) -> Vec<u8> {
        cid_of(0x71, &n.to_le_bytes())
    }

    /// Changed in place over random batches of puts and deletes, the tree is
    /// at every step the one `build_tree` builds of the same keys, node for
    /// node; the nodes it opened and made are exactly those the commit
    /// replaced; and a commit's event carries the nodes it would with a
    /// tree built whole.
    #[test]
    fn edits_build_the_same_tree() {
        for seed in 1..=24u64 {
            let mut rng = Rng(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15));
            let mut store: HashMap<Vec<u8>, Arc<[u8]>> = HashMap::new();
            let mut keys: BTreeMap<Vec<u8>, Vec<u8>> = BTreeMap::new();
            let empty = build_tree(&[]);
            store.insert(empty.cid.clone(), empty.bytes.clone().into());
            let mut root = empty.cid.clone();
            let pool = 20 + rng.below(400);
            for _ in 0..40 {
                let before = build_tree(
                    &keys
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect::<Vec<_>>(),
                );
                let mut changes: BTreeMap<Vec<u8>, Option<Vec<u8>>> = BTreeMap::new();
                let most = if rng.below(4) == 0 { 60 } else { 6 };
                for _ in 0..1 + rng.below(most) {
                    let k = format!("com.example.c{}/{:05}", rng.below(3), rng.below(pool))
                        .into_bytes();
                    if keys.contains_key(&k) && rng.below(2) == 0 {
                        changes.insert(k, None);
                    } else {
                        changes.insert(k, Some(value(rng.next())));
                    }
                }
                for (k, v) in &changes {
                    match v {
                        Some(v) => keys.insert(k.clone(), v.clone()),
                        None => keys.remove(k),
                    };
                }
                let list: Vec<(Vec<u8>, Option<Vec<u8>>)> = changes.into_iter().collect();
                let fetch = |c: &[u8]| store.get(c).cloned();
                let mut e = Edit::new(&fetch);
                let (new_root, made) = e.apply(&root, &list).unwrap();
                let whole = build_tree(
                    &keys
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect::<Vec<_>>(),
                );
                assert_eq!(new_root, whole.cid, "seed {seed}");
                let after: HashSet<Vec<u8>> = whole.nodes().iter().map(|n| n.cid.clone()).collect();
                let old: HashSet<Vec<u8>> = before.nodes().iter().map(|n| n.cid.clone()).collect();
                let new: HashSet<Vec<u8>> = after.difference(&old).cloned().collect();
                let made_set: HashSet<Vec<u8>> =
                    made.keys().filter(|c| !old.contains(*c)).cloned().collect();
                assert_eq!(made_set, new, "seed {seed}: the nodes made");
                let opened: HashSet<Vec<u8>> = e.opened.iter().cloned().collect();
                let gone: HashSet<Vec<u8>> = old.difference(&after).cloned().collect();
                let replaced: HashSet<Vec<u8>> = opened
                    .iter()
                    .filter(|c| !made.contains_key(*c))
                    .cloned()
                    .collect();
                assert_eq!(replaced, gone, "seed {seed}: the nodes replaced");
                for (c, b) in made {
                    store.insert(c, b.into());
                }
                // The event's nodes: new ones and each key's context.
                let fetch = |c: &[u8]| store.get(c).cloned();
                let mut carried: Vec<Vec<u8>> = new.iter().cloned().collect();
                for (k, _) in &list {
                    let mut out = Vec::new();
                    context(&fetch, &new_root, k, &mut out).unwrap();
                    carried.extend(out.into_iter().map(|(c, _)| c));
                }
                carried.sort();
                carried.dedup();
                let want: Vec<Vec<u8>> = event_nodes(
                    Some(&before),
                    &whole,
                    list.iter().map(|(k, _)| k.as_slice()),
                )
                .iter()
                .map(|n| n.cid.clone())
                .collect();
                assert_eq!(carried, want, "seed {seed}: the event's nodes");
                // Reads of the tree in place.
                let all = range(&fetch, &new_root, b"", usize::MAX).unwrap();
                assert_eq!(
                    all,
                    keys.iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect::<Vec<_>>()
                );
                for (k, _) in list.iter().take(3) {
                    assert_eq!(get(&fetch, &new_root, k).unwrap(), keys.get(k).cloned());
                    let p: Vec<Vec<u8>> = path(&fetch, &new_root, k)
                        .unwrap()
                        .into_iter()
                        .map(|(c, _)| c)
                        .collect();
                    let q: Vec<Vec<u8>> = whole.path(k).iter().map(|n| n.cid.clone()).collect();
                    assert_eq!(p, q);
                }
                root = new_root;
            }
        }
    }
}