mssmt

A high-performance Merkle-Sum Sparse Merkle Tree.
git clone git://git.jtobin.io/mssmt.git
Log | Files | Refs | README | LICENSE | git.jtobin.io

commit 123b0ba085342d371ad8ef9fefca5b8309a169e4
parent 4c756409e03f4112a352eccb33c3aca0189a343c
Author: Jared Tobin <jared@jtobin.io>
Date:   Wed,  4 Nov 2026 22:26:11 +0400

lib: batch insert

insert_many applies a batch of puts and deletions in one pass down
the tree, splitting the batch by path bit at each level and rehashing
each changed node once. Where a key appears more than once, its last
appearance wins; an empty value with zero sum deletes. It returns
Nothing only if the resulting tree's sum would overflow, not if some
intermediate one would.

Tests check, under both schemes, that a batch agrees with successive
inserts, and that it fails iff the resulting sum overflows. Benchmarks
compare batched and one-at-a-time insertion; batching inserts 64
leaves into the 1024-leaf tree about 10% faster.

Diffstat:
Mbench/Main.hs | 18++++++++++++++++--
Mlib/Data/MSSMT/Aggregate.hs | 10++++++++++
Mlib/Data/MSSMT/Internal.hs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mlib/Data/MSSMT/Split.hs | 10++++++++++
Mtest/Main.hs | 38+++++++++++++++++++++++++++++++++++---
5 files changed, 156 insertions(+), 5 deletions(-)

diff --git a/bench/Main.hs b/bench/Main.hs @@ -3,6 +3,7 @@ module Main where +import Control.Monad (foldM) import Criterion.Main import Data.MSSMT import Fixtures @@ -17,6 +18,7 @@ main = defaultMain [ , bench_prove f , bench_verify f , bench_build + , bench_insert_many f ] ] @@ -56,5 +58,17 @@ bench_verify ~Fixtures {..} = bgroup "verify" [ ] bench_build :: Benchmark -bench_build = env (pure (leaves 64)) $ \ls -> - bench "build (64 leaves)" $ nf build ls +bench_build = env (pure (leaves 64)) $ \ls -> bgroup "build (64 leaves)" [ + bench "one at a time" $ nf build ls + , bench "batched" $ nf (insert_many ls) empty + ] + +bench_insert_many :: Fixtures -> Benchmark +bench_insert_many ~Fixtures {..} = + env (pure (drop 1024 (leaves 1088))) $ \ls -> + bgroup "insert 64 leaves into 1024" [ + bench "one at a time" $ nf (\t -> foldM ins t ls) f_tree + , bench "batched" $ nf (insert_many ls) f_tree + ] + where + ins t (k, v, s) = insert k v s t diff --git a/lib/Data/MSSMT/Aggregate.hs b/lib/Data/MSSMT/Aggregate.hs @@ -32,6 +32,7 @@ module Data.MSSMT.Aggregate ( , Tree , empty , insert + , insert_many , delete , lookup , root @@ -67,6 +68,15 @@ empty = Tree I.empty insert :: Key -> BS.ByteString -> Word64 -> Tree -> Maybe Tree insert k v s (Tree t) = coerce (I.insert_with Aggregate k v s t) +-- | Insert many values and sums, as if one at a time, but rehashing +-- each changed node once. +-- +-- Where a key appears more than once, its last appearance wins, and +-- an empty value with zero sum deletes whatever is at its key. +-- Returns 'Nothing' if the resulting tree's sum would overflow. +insert_many :: [(Key, BS.ByteString, Word64)] -> Tree -> Maybe Tree +insert_many kvs (Tree t) = coerce (I.insert_many_with Aggregate kvs t) + -- | Delete the leaf at a key. delete :: Key -> Tree -> Tree delete k (Tree t) = Tree (I.delete_with Aggregate k t) diff --git a/lib/Data/MSSMT/Internal.hs b/lib/Data/MSSMT/Internal.hs @@ -39,6 +39,7 @@ module Data.MSSMT.Internal ( , Tree(..) , empty , insert_with + , insert_many_with , delete_with , lookup , root_with @@ -55,7 +56,9 @@ import Data.Bits (testBit) import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BU import Data.MSSMT.Hash +import Data.List (partition, sortBy) import qualified Data.Primitive.PrimArray as PA +import Data.Ord (comparing) import Data.Word (Word64) import qualified GHC.Exts as Exts import GHC.Exts (State#) @@ -260,6 +263,53 @@ insert_leaf sc k v s t0 = with_scratch $ \st bk s00 -> (# s1, l' #) -> node# sc st bk d l' r s1 in go 0 t0 s01 } +-- a leaf in a subtree being rebuilt in a batch: one being put, one +-- being deleted, or an existing one, kept with its hash +data Item = + Put !Key !BS.ByteString {-# UNPACK #-} !Word64 + | Del !Key + | Kept !Key {-# UNPACK #-} !Hash {-# UNPACK #-} !Word64 !BS.ByteString + +item_key :: Item -> Key +item_key (Put k _ _) = k +item_key (Del k) = k +item_key (Kept k _ _ _) = k + +-- apply a batch of puts and deletions, at distinct keys, rehashing each +-- changed node once over one pair of state and block arrays. callers +-- rule out sum overflow +batch :: Scheme -> [Item] -> Tree -> Tree +batch sc items0 t0 = with_scratch $ \st bk -> + let -- the subtree at a depth holding the given items, which agree on + -- their paths above it + go !d t items s0 = case t of + Empty -> build d items s0 + Leaf (Commitment _ s') lh' k' v' + | any ((== k') . item_key) items -> build d items s0 + | otherwise -> build d (Kept k' lh' s' v' : items) s0 + Node l _ r -> + let (ls, rs) = partition (\i -> not (bit (item_key i) d)) items + in case if null ls then (# s0, l #) else go (d + 1) l ls s0 of + (# s1, l' #) -> + case if null rs then (# s1, r #) else go (d + 1) r rs s1 of + (# s2, r' #) -> node# sc st bk d l' r' s2 + + -- the subtree at a depth holding exactly the given items' leaves + build !d items s0 = case filter live items of + [] -> (# s0, Empty #) + [Put k v s] -> case hash_leaf# sc st bk k v s s0 of + (# s1, lh #) -> leaf# sc st bk d k lh s v s1 + [Kept k lh s v] -> leaf# sc st bk d k lh s v s0 + is -> + let (ls, rs) = partition (\i -> not (bit (item_key i) d)) is + in case build (d + 1) ls s0 of + (# s1, l #) -> case build (d + 1) rs s1 of + (# s2, r #) -> node# sc st bk d l r s2 + + live (Del _) = False + live _ = True + in go 0 t0 items0 + -- tree ----------------------------------------------------------------------- -- | The empty tree. @@ -280,6 +330,41 @@ insert_with sc k v s t where rest = total t - with_leaf k t 0 const +-- | Insert many values and sums under a scheme, as if one at a time, +-- but rehashing each changed node once. +-- +-- Where a key appears more than once, its last appearance wins, and +-- an empty value with zero sum deletes whatever is at its key. +-- Returns 'Nothing' if the resulting tree's sum would overflow. +insert_many_with + :: Scheme -> [(Key, BS.ByteString, Word64)] -> Tree -> Maybe Tree +insert_many_with sc kvs t + | null items = Just t + | after > toInteger (maxBound :: Word64) = Nothing + | otherwise = Just (batch sc items t) + where + -- the last item at each key + items = last_each (sortBy (comparing (\(k, _, _) -> k)) kvs) + last_each ((k, v, s) : rest@((k', _, _) : _)) + | k == k' = last_each rest + | otherwise = item k v s : last_each rest + last_each [(k, v, s)] = [item k v s] + last_each [] = [] + + item k v s + | BS.null v && s == 0 = Del k + | otherwise = Put k v s + + -- the resulting tree's sum + after = toInteger (total t) + sum (fmap change items) + change i = + let k = item_key i + was = toInteger (with_leaf k t 0 const) + in case i of + Put _ _ s -> toInteger s - was + Del _ -> negate was + Kept {} -> 0 + -- | Delete the leaf at a key under a scheme. delete_with :: Scheme -> Key -> Tree -> Tree delete_with sc k t0 = with_leaf k t0 t0 $ \_ _ -> with_scratch $ \st bk -> diff --git a/lib/Data/MSSMT/Split.hs b/lib/Data/MSSMT/Split.hs @@ -34,6 +34,7 @@ module Data.MSSMT.Split ( , Tree , empty , insert + , insert_many , delete , lookup , root @@ -70,6 +71,15 @@ empty = Tree I.empty insert :: Key -> BS.ByteString -> Word64 -> Tree -> Maybe Tree insert k v s (Tree t) = coerce (I.insert_with Split k v s t) +-- | Insert many values and sums, as if one at a time, but rehashing +-- each changed node once. +-- +-- Where a key appears more than once, its last appearance wins, and +-- an empty value with zero sum deletes whatever is at its key. +-- Returns 'Nothing' if the resulting tree's sum would overflow. +insert_many :: [(Key, BS.ByteString, Word64)] -> Tree -> Maybe Tree +insert_many kvs (Tree t) = coerce (I.insert_many_with Split kvs t) + -- | Delete the leaf at a key. delete :: Key -> Tree -> Tree delete k (Tree t) = Tree (I.delete_with Split k t) diff --git a/test/Main.hs b/test/Main.hs @@ -163,6 +163,7 @@ instance Q.Arbitrary Es where data Ops t p = Ops { o_empty :: t , o_insert :: Key -> BS.ByteString -> Word64 -> t -> Maybe t + , o_insert_many :: [(Key, BS.ByteString, Word64)] -> t -> Maybe t , o_delete :: Key -> t -> t , o_lookup :: Key -> t -> Maybe (BS.ByteString, Word64) , o_root :: t -> Commitment @@ -172,12 +173,12 @@ data Ops t p = Ops { } split_ops :: Ops Tree Proof -split_ops = Ops empty insert delete lookup root prove verify R.root +split_ops = Ops empty insert insert_many delete lookup root prove verify R.root aggregate_ops :: Ops Agg.Tree Agg.Proof aggregate_ops = Ops - Agg.empty Agg.insert Agg.delete Agg.lookup Agg.root Agg.prove Agg.verify - R.root_aggregate + Agg.empty Agg.insert Agg.insert_many Agg.delete Agg.lookup Agg.root + Agg.prove Agg.verify R.root_aggregate build :: Ops t p -> [E] -> Maybe t build Ops {..} = foldM (\t (E k v s) -> o_insert k v s t) o_empty @@ -192,6 +193,20 @@ pick (Es pre es) = Q.oneof (gen_key pre : [Q.elements ks | not (null ks)]) where ks = [k | E k _ _ <- es] +-- a batch of puts and deletions, at keys from the leaves or fresh ones +-- under their prefix, with sums from the given generator +gen_batch :: Q.Gen Word64 -> Es -> Q.Gen [(Key, BS.ByteString, Word64)] +gen_batch sums x = Q.listOf $ do + k <- pick x + Q.frequency [ + (3, (,,) k <$> fmap BS.pack (Q.listOf1 Q.arbitrary) <*> sums) + , (1, pure (k, mempty, 0)) + ] + +-- a sum small enough that batches of them don't overflow +small :: Q.Gen Word64 +small = fromIntegral <$> (Q.arbitrary :: Q.Gen Word32) + -- a sum, often near maxBound big :: Q.Gen Word64 big = Q.oneof [ @@ -297,6 +312,23 @@ properties name o@Ops {..} = testGroup ("properties (" <> name <> ")") [ && not (o_verify k mempty 0 (o_prove k t) r)) (M.toList (model es)) + , Q.testProperty "insert_many agrees with successive inserts" $ + \x@(Es _ es) -> Q.forAll (gen_batch small x) $ \b -> + with_tree o es $ \t -> + o_insert_many b t + Q.=== foldM (\u (k, v, s) -> o_insert k v s u) t b + + , Q.testProperty "insert_many fails iff the root sum would overflow" $ + \x@(Es _ es) -> Q.forAll (gen_batch (Q.oneof [small, big]) x) $ \b -> + with_tree o es $ \t -> + let apply m (k, v, s) + | BS.null v && s == 0 = M.delete k m + | otherwise = M.insert k (v, s) m + final = foldl apply (model es) b + fits = sum (fmap (toInteger . snd) final) + <= toInteger (maxBound :: Word64) + in Q.classify fits "fits" $ isJust (o_insert_many b t) Q.=== fits + , Q.testProperty "insert fails iff the root sum would overflow" $ \x@(Es _ es) -> Q.forAll (pick x) $ \k -> Q.forAll big $ \s -> with_tree o es $ \t ->