Mini Project: A Persistent Key-Value Store
Version-control systems, databases with "time travel" queries and configuration stores all need the same thing: a map from keys to values in which every committed version stays readable, cheaply. In this project you build one on a persistent balanced search tree with path copying: each commit copies only the nodes on the changed paths and shares everything else with the previous version.
The store supports:
commit(message, puts, deletes, base): apply a batch of changes to the latest version (or to an old versionbase, which makes a branch) and return the new version number;get(key, version)andsize(version)on any version;- ordered range queries and rank queries on old versions (step 2);
- a diff between two versions that skips shared subtrees, so it costs time proportional to the change, not to the size (step 3);
- branches and the space accounting behind garbage collection (step 4).
The tree is a treap whose priorities are a fixed hash of the key (FNV-1a), so the program is deterministic and, importantly for step 3, the shape of the tree depends only on the set of keys. Each step is a complete program that repeats the core; run any of them on its own.
Step 1: The core and the first versions
split and merge are the functional treap primitives from the lesson; replace changes the value of an existing key by copying its path; delete copies the path to a key and merges its two subtrees. A Store keeps the list of version roots. The demo makes three commits and then counts the distinct nodes reachable from all versions.
def prio(key): # deterministic priority: FNV-1a hash of the key's text
h = 0xCBF29CE484222325
for byte in str(key).encode():
h = ((h ^ byte) * 0x100000001B3) % (1 << 64)
return h
class Node:
__slots__ = ("key", "value", "left", "right", "size")
def __init__(self, key, value, left, right):
self.key, self.value, self.left, self.right = key, value, left, right
self.size = 1 + (left.size if left else 0) + (right.size if right else 0)
def split(t, k): # (keys < k, keys >= k), copying one path
if t is None: return None, None
if t.key < k:
a, b = split(t.right, k)
return Node(t.key, t.value, t.left, a), b
a, b = split(t.left, k)
return a, Node(t.key, t.value, b, t.right)
def merge(a, b): # every key of a < every key of b
if a is None or b is None: return a or b
if prio(a.key) > prio(b.key):
return Node(a.key, a.value, a.left, merge(a.right, b))
return Node(b.key, b.value, merge(a, b.left), b.right)
def find(t, k):
while t is not None and t.key != k:
t = t.left if k < t.key else t.right
return t
def replace(t, k, v): # k is present: copy the path, change one value
if k == t.key: return Node(k, v, t.left, t.right)
if k < t.key: return Node(t.key, t.value, replace(t.left, k, v), t.right)
return Node(t.key, t.value, t.left, replace(t.right, k, v))
def put(t, k, v):
if find(t, k) is not None: return replace(t, k, v)
a, b = split(t, k)
return merge(merge(a, Node(k, v, None, None)), b)
def delete(t, k): # copy the path to k, merge k's two subtrees
if t is None: return None
if k == t.key: return merge(t.left, t.right)
if k < t.key: return Node(t.key, t.value, delete(t.left, k), t.right)
return Node(t.key, t.value, t.left, delete(t.right, k))
class Store:
"""A versioned key-value store: every commit creates a new version; old versions never change."""
def __init__(self):
self.roots, self.messages = [None], ["empty"]
def commit(self, message, puts=None, deletes=(), base=None):
t = self.roots[-1 if base is None else base]
for k, v in (puts or {}).items(): t = put(t, k, v)
for k in deletes: t = delete(t, k)
self.roots.append(t); self.messages.append(message)
return len(self.roots) - 1
def get(self, key, version=-1, default=None):
n = find(self.roots[version], key)
return default if n is None else n.value
def size(self, version=-1):
t = self.roots[version]
return t.size if t else 0
s = Store()
v1 = s.commit("initial prices", puts={"apple": 3, "bread": 2, "milk": 1, "tea": 5})
v2 = s.commit("price change", puts={"milk": 2, "cocoa": 7})
v3 = s.commit("drop tea", deletes=["tea"])
for v in range(len(s.roots)):
print(f"v{v} ({s.messages[v]}): size {s.size(v)}, milk = {s.get('milk', v)}, tea = {s.get('tea', v)}")
# Structure sharing: count the distinct nodes reachable from all versions.
def nodes(t, seen):
if t is not None and id(t) not in seen:
seen.add(id(t)); nodes(t.left, seen); nodes(t.right, seen)
seen = set()
for r in s.roots: nodes(r, seen)
print("distinct nodes over all versions:", len(seen), "| sum of version sizes:", sum(s.size(v) for v in range(4)))v0 (empty): size 0, milk = None, tea = None
v1 (initial prices): size 4, milk = 1, tea = 5
v2 (price change): size 5, milk = 2, tea = 5
v3 (drop tea): size 4, milk = 2, tea = None
distinct nodes over all versions: 10 | sum of version sizes: 13
Four versions with 13 keys in total share 10 nodes. With more keys per version the sharing grows: each commit adds only nodes per changed key.
Step 2: Range and rank queries on old versions
Because every version is a complete search tree, ordered queries work on any of them: list the keys in with pruning, for results, and count them with subtree sizes, (order statistics). The program simulates 300 days of small changes, keeps a full dictionary snapshot per day only to check the answers, and compares 500 random range queries on random old versions.
def prio(key): # deterministic priority: FNV-1a hash of the key's text
h = 0xCBF29CE484222325
for byte in str(key).encode():
h = ((h ^ byte) * 0x100000001B3) % (1 << 64)
return h
class Node:
__slots__ = ("key", "value", "left", "right", "size")
def __init__(self, key, value, left, right):
self.key, self.value, self.left, self.right = key, value, left, right
self.size = 1 + (left.size if left else 0) + (right.size if right else 0)
def split(t, k): # (keys < k, keys >= k), copying one path
if t is None: return None, None
if t.key < k:
a, b = split(t.right, k)
return Node(t.key, t.value, t.left, a), b
a, b = split(t.left, k)
return a, Node(t.key, t.value, b, t.right)
def merge(a, b): # every key of a < every key of b
if a is None or b is None: return a or b
if prio(a.key) > prio(b.key):
return Node(a.key, a.value, a.left, merge(a.right, b))
return Node(b.key, b.value, merge(a, b.left), b.right)
def find(t, k):
while t is not None and t.key != k:
t = t.left if k < t.key else t.right
return t
def replace(t, k, v): # k is present: copy the path, change one value
if k == t.key: return Node(k, v, t.left, t.right)
if k < t.key: return Node(t.key, t.value, replace(t.left, k, v), t.right)
return Node(t.key, t.value, t.left, replace(t.right, k, v))
def put(t, k, v):
if find(t, k) is not None: return replace(t, k, v)
a, b = split(t, k)
return merge(merge(a, Node(k, v, None, None)), b)
def delete(t, k): # copy the path to k, merge k's two subtrees
if t is None: return None
if k == t.key: return merge(t.left, t.right)
if k < t.key: return Node(t.key, t.value, delete(t.left, k), t.right)
return Node(t.key, t.value, t.left, delete(t.right, k))
class Store:
"""A versioned key-value store: every commit creates a new version; old versions never change."""
def __init__(self):
self.roots, self.messages = [None], ["empty"]
def commit(self, message, puts=None, deletes=(), base=None):
t = self.roots[-1 if base is None else base]
for k, v in (puts or {}).items(): t = put(t, k, v)
for k in deletes: t = delete(t, k)
self.roots.append(t); self.messages.append(message)
return len(self.roots) - 1
def get(self, key, version=-1, default=None):
n = find(self.roots[version], key)
return default if n is None else n.value
def size(self, version=-1):
t = self.roots[version]
return t.size if t else 0
import random
def items(t, lo, hi, out): # keys in [lo, hi), in order, pruning subtrees
if t is None: return out
if lo < t.key: items(t.left, lo, hi, out)
if lo <= t.key < hi: out.append((t.key, t.value))
if t.key < hi: items(t.right, lo, hi, out)
return out
def rank(t, k): # number of keys < k, O(depth) with subtree sizes
r = 0
while t is not None:
if k <= t.key: t = t.left
else:
r += 1 + (t.left.size if t.left else 0); t = t.right
return r
rng = random.Random(2026)
s, snapshots = Store(), [{}]
for day in range(1, 301): # 300 commits of a few random changes each
current = dict(snapshots[-1])
puts = {f"item{rng.randrange(400):03}": rng.randrange(1, 100) for _ in range(3)}
deletes = [k for k in sorted(current) if rng.random() < 0.01]
s.commit(f"day {day}", puts, deletes)
current.update(puts)
for k in deletes: current.pop(k, None)
snapshots.append(current)
for _ in range(500): # random checks of old versions
v = rng.randrange(len(s.roots))
lo, hi = sorted(f"item{rng.randrange(400):03}" for _ in range(2))
want = sorted((k, x) for k, x in snapshots[v].items() if lo <= k < hi)
assert items(s.roots[v], lo, hi, []) == want
assert rank(s.roots[v], hi) - rank(s.roots[v], lo) == len(want)
print(f"{len(s.roots) - 1} versions; 500 random range queries on old versions agree with full snapshots")
for v in [10, 150, 300]:
print(f"v{v}: {s.size(v)} keys; keys in [item100, item110):", [k for k, _ in items(s.roots[v], "item100", "item110", [])])300 versions; 500 random range queries on old versions agree with full snapshots
v10: 28 keys; keys in [item100, item110): ['item107']
v150: 168 keys; keys in [item100, item110): ['item100', 'item101', 'item102', 'item105', 'item108', 'item109']
v300: 153 keys; keys in [item100, item110): ['item100', 'item101', 'item102', 'item104', 'item109']
Step 3: Diffs that skip shared structure
To compare two versions, walk both trees at once. If the two subtrees are the same object, nothing below has changed: skip it without looking inside. Otherwise, because treap shapes depend only on keys, the root with the higher priority decides: if both roots have the same key, compare the values and recurse on the children; if one root has a higher priority, its key does not exist in the other tree, so it was removed (or added), and the other tree is split at that key to recurse on matching halves. A split copies only one path, so the identity of everything else is preserved. The program also prints the history of one key across all versions.
def prio(key): # deterministic priority: FNV-1a hash of the key's text
h = 0xCBF29CE484222325
for byte in str(key).encode():
h = ((h ^ byte) * 0x100000001B3) % (1 << 64)
return h
class Node:
__slots__ = ("key", "value", "left", "right", "size")
def __init__(self, key, value, left, right):
self.key, self.value, self.left, self.right = key, value, left, right
self.size = 1 + (left.size if left else 0) + (right.size if right else 0)
def split(t, k): # (keys < k, keys >= k), copying one path
if t is None: return None, None
if t.key < k:
a, b = split(t.right, k)
return Node(t.key, t.value, t.left, a), b
a, b = split(t.left, k)
return a, Node(t.key, t.value, b, t.right)
def merge(a, b): # every key of a < every key of b
if a is None or b is None: return a or b
if prio(a.key) > prio(b.key):
return Node(a.key, a.value, a.left, merge(a.right, b))
return Node(b.key, b.value, merge(a, b.left), b.right)
def find(t, k):
while t is not None and t.key != k:
t = t.left if k < t.key else t.right
return t
def replace(t, k, v): # k is present: copy the path, change one value
if k == t.key: return Node(k, v, t.left, t.right)
if k < t.key: return Node(t.key, t.value, replace(t.left, k, v), t.right)
return Node(t.key, t.value, t.left, replace(t.right, k, v))
def put(t, k, v):
if find(t, k) is not None: return replace(t, k, v)
a, b = split(t, k)
return merge(merge(a, Node(k, v, None, None)), b)
def delete(t, k): # copy the path to k, merge k's two subtrees
if t is None: return None
if k == t.key: return merge(t.left, t.right)
if k < t.key: return Node(t.key, t.value, delete(t.left, k), t.right)
return Node(t.key, t.value, t.left, delete(t.right, k))
class Store:
"""A versioned key-value store: every commit creates a new version; old versions never change."""
def __init__(self):
self.roots, self.messages = [None], ["empty"]
def commit(self, message, puts=None, deletes=(), base=None):
t = self.roots[-1 if base is None else base]
for k, v in (puts or {}).items(): t = put(t, k, v)
for k in deletes: t = delete(t, k)
self.roots.append(t); self.messages.append(message)
return len(self.roots) - 1
def get(self, key, version=-1, default=None):
n = find(self.roots[version], key)
return default if n is None else n.value
def size(self, version=-1):
t = self.roots[version]
return t.size if t else 0
import random
visited = 0
def walk(t, out, tag):
global visited
if t is None: return
visited += 1
walk(t.left, out, tag); out.append((t.key, tag, t.value)); walk(t.right, out, tag)
def diff(a, b, out):
"""Changes from tree a to tree b. Shared subtrees (the same object) are skipped without looking
inside. Treap shapes depend only on the keys, so the higher-priority root of a and b decides."""
global visited
if a is b: return out # shared: no differences inside
if a is None: walk(b, out, "added"); return out
if b is None: walk(a, out, "removed"); return out
visited += 1
if a.key == b.key:
diff(a.left, b.left, out)
if a.value != b.value: out.append((a.key, "changed", (a.value, b.value)))
diff(a.right, b.right, out)
elif prio(a.key) > prio(b.key): # a's root key is not in b at all
bl, br = split(b, a.key)
diff(a.left, bl, out); out.append((a.key, "removed", a.value)); diff(a.right, br, out)
else: # b's root key is new
al, ar = split(a, b.key)
diff(al, b.left, out); out.append((b.key, "added", b.value)); diff(ar, b.right, out)
return out
rng = random.Random(7)
s = Store()
s.commit("load", puts={f"user{i:04}": rng.randrange(1000) for i in range(2000)})
v1 = len(s.roots) - 1
s.commit("edits", puts={"user0042": -1, "user1999": 5, "user2500": 9}, deletes=["user0007"])
v2 = len(s.roots) - 1
for v_old, v_new in [(v1, v2), (v2, v1)]:
visited = 0
changes = diff(s.roots[v_old], s.roots[v_new], [])
print(f"diff v{v_old} -> v{v_new}: {changes}")
print(f" nodes looked at: {visited} of {s.size(v_old)} + {s.size(v_new)}")
def history(store, key): # the value of key in every version, changes only
out, last = [], object()
for v in range(len(store.roots)):
x = store.get(key, v)
if x != last: out.append((v, x)); last = x
return out
s.commit("more edits", puts={"user0042": 17})
print("history of user0042:", history(s, "user0042"))diff v1 -> v2: [('user0007', 'removed', 840), ('user0042', 'changed', (47, -1)), ('user1999', 'changed', (514, 5)), ('user2500', 'added', 9)]
nodes looked at: 77 of 2000 + 2000
diff v2 -> v1: [('user0007', 'added', 840), ('user0042', 'changed', (-1, 47)), ('user1999', 'changed', (5, 514)), ('user2500', 'removed', 9)]
nodes looked at: 77 of 2000 + 2000
history of user0042: [(0, None), (1, 47), (2, -1), (3, 17)]
The diff found the four changes between two versions of 2000 keys each while looking at 77 nodes: the changed paths and their neighbours. A naive diff would compare all 4000. The cost is for changes, the same reason git diff between nearby commits is fast: unchanged subtrees (directories, in git) are shared objects with equal identity.
Step 4: Branches and garbage
With path copying any version can be the base of a commit, which creates a branch in the version tree (full persistence). Space is reclaimed by dropping old roots: nodes reachable from no kept version are garbage. The program commits 200 days of changes, branches from day 50, and counts the nodes that must stay alive for different retention policies.
def prio(key): # deterministic priority: FNV-1a hash of the key's text
h = 0xCBF29CE484222325
for byte in str(key).encode():
h = ((h ^ byte) * 0x100000001B3) % (1 << 64)
return h
class Node:
__slots__ = ("key", "value", "left", "right", "size")
def __init__(self, key, value, left, right):
self.key, self.value, self.left, self.right = key, value, left, right
self.size = 1 + (left.size if left else 0) + (right.size if right else 0)
def split(t, k): # (keys < k, keys >= k), copying one path
if t is None: return None, None
if t.key < k:
a, b = split(t.right, k)
return Node(t.key, t.value, t.left, a), b
a, b = split(t.left, k)
return a, Node(t.key, t.value, b, t.right)
def merge(a, b): # every key of a < every key of b
if a is None or b is None: return a or b
if prio(a.key) > prio(b.key):
return Node(a.key, a.value, a.left, merge(a.right, b))
return Node(b.key, b.value, merge(a, b.left), b.right)
def find(t, k):
while t is not None and t.key != k:
t = t.left if k < t.key else t.right
return t
def replace(t, k, v): # k is present: copy the path, change one value
if k == t.key: return Node(k, v, t.left, t.right)
if k < t.key: return Node(t.key, t.value, replace(t.left, k, v), t.right)
return Node(t.key, t.value, t.left, replace(t.right, k, v))
def put(t, k, v):
if find(t, k) is not None: return replace(t, k, v)
a, b = split(t, k)
return merge(merge(a, Node(k, v, None, None)), b)
def delete(t, k): # copy the path to k, merge k's two subtrees
if t is None: return None
if k == t.key: return merge(t.left, t.right)
if k < t.key: return Node(t.key, t.value, delete(t.left, k), t.right)
return Node(t.key, t.value, t.left, delete(t.right, k))
class Store:
"""A versioned key-value store: every commit creates a new version; old versions never change."""
def __init__(self):
self.roots, self.messages = [None], ["empty"]
def commit(self, message, puts=None, deletes=(), base=None):
t = self.roots[-1 if base is None else base]
for k, v in (puts or {}).items(): t = put(t, k, v)
for k in deletes: t = delete(t, k)
self.roots.append(t); self.messages.append(message)
return len(self.roots) - 1
def get(self, key, version=-1, default=None):
n = find(self.roots[version], key)
return default if n is None else n.value
def size(self, version=-1):
t = self.roots[version]
return t.size if t else 0
import random
def reachable(roots): # distinct nodes kept alive by these versions
seen, stack = set(), [r for r in roots if r is not None]
while stack:
t = stack.pop()
if id(t) in seen: continue
seen.add(id(t))
stack.extend(c for c in (t.left, t.right) if c is not None)
return len(seen)
rng = random.Random(11)
s = Store()
s.commit("load", puts={f"k{i:04}": i for i in range(1000)})
for day in range(200): # 200 days of small changes
s.commit(f"day {day}", puts={f"k{rng.randrange(1000):04}": rng.randrange(10 ** 6) for _ in range(5)})
main_head = len(s.roots) - 1
# Full persistence: branch from an old version (day 50) without touching the main line.
branch = s.commit("what-if from day 50", puts={"k0001": -1, "zzz": 0}, base=51)
print(f"main head v{main_head}: k0001 = {s.get('k0001', main_head)}, zzz = {s.get('zzz', main_head)}")
print(f"branch v{branch} (based on v51): k0001 = {s.get('k0001', branch)}, zzz = {s.get('zzz', branch)}")
print(f"v51 itself is unchanged: k0001 = {s.get('k0001', 51)}, size {s.size(51)}")
all_versions = reachable(s.roots)
last10 = reachable(s.roots[-10:])
print(f"nodes alive for all {len(s.roots)} versions: {all_versions} (one full copy each would be {sum(s.size(v) for v in range(len(s.roots)))})")
print(f"keeping only the last 10 versions: {last10} nodes; the other {all_versions - last10} can be garbage collected")main head v201: k0001 = 1, zzz = None
branch v202 (based on v51): k0001 = -1, zzz = 0
v51 itself is unchanged: k0001 = 1, size 1000
nodes alive for all 203 versions: 25349 (one full copy each would be 202001)
keeping only the last 10 versions: 2810 nodes; the other 22539 can be garbage collected
All 203 versions fit in about an eighth of the space of 203 full copies, and keeping only the last 10 frees 89% of the nodes. In a real system, reference counting (as in the C++ version below) or a tracing garbage collector does this automatically.
Step 5: The core in C++
The same persistent treap with std::shared_ptr<const Node>: nodes are immutable, versions share subtrees, and a node is freed when the last version using it disappears. The demo replays step 1 in C++, with a branch, and counts the keys in a range on each version.
#include <cstdint>
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
#include <vector>
// A versioned key-value store on a persistent treap with path copying.
class PersistentMap {
struct Node;
using P = std::shared_ptr<const Node>;
struct Node {
std::string key;
int value;
P left, right;
int size;
};
static int sz(const P& t) { return t ? t->size : 0; }
static P make(const std::string& k, int v, P l, P r) {
int s = 1 + sz(l) + sz(r);
return std::make_shared<const Node>(Node{k, v, std::move(l), std::move(r), s});
}
static std::uint64_t prio(const std::string& k) { // FNV-1a, as in the Python version
std::uint64_t h = 0xCBF29CE484222325ULL;
for (unsigned char c : k) h = (h ^ c) * 0x100000001B3ULL;
return h;
}
static std::pair<P, P> split(const P& t, const std::string& k) {
if (!t) return {nullptr, nullptr};
if (t->key < k) { auto [a, b] = split(t->right, k); return {make(t->key, t->value, t->left, a), b}; }
auto [a, b] = split(t->left, k);
return {a, make(t->key, t->value, b, t->right)};
}
static P merge(const P& a, const P& b) {
if (!a || !b) return a ? a : b;
if (prio(a->key) > prio(b->key)) return make(a->key, a->value, a->left, merge(a->right, b));
return make(b->key, b->value, merge(a, b->left), b->right);
}
static const Node* find(const P& t, const std::string& k) {
const Node* x = t.get();
while (x && x->key != k) x = k < x->key ? x->left.get() : x->right.get();
return x;
}
static P replace(const P& t, const std::string& k, int v) {
if (k == t->key) return make(k, v, t->left, t->right);
if (k < t->key) return make(t->key, t->value, replace(t->left, k, v), t->right);
return make(t->key, t->value, t->left, replace(t->right, k, v));
}
static P erase(const P& t, const std::string& k) {
if (!t) return t;
if (k == t->key) return merge(t->left, t->right);
if (k < t->key) return make(t->key, t->value, erase(t->left, k), t->right);
return make(t->key, t->value, t->left, erase(t->right, k));
}
static int rank(const P& t, const std::string& k) { // keys < k
int r = 0;
for (const Node* x = t.get(); x;) {
if (k <= x->key) x = x->left.get();
else { r += 1 + sz(x->left); x = x->right.get(); }
}
return r;
}
std::vector<P> roots{nullptr};
public:
int put(const std::string& k, int v, int base = -1) {
const P& t = roots[base < 0 ? roots.size() - 1 : base];
P next;
if (find(t, k)) next = replace(t, k, v);
else { auto [a, b] = split(t, k); next = merge(merge(a, make(k, v, nullptr, nullptr)), b); }
roots.push_back(next);
return static_cast<int>(roots.size()) - 1;
}
int erase(const std::string& k) { roots.push_back(erase(roots.back(), k)); return static_cast<int>(roots.size()) - 1; }
const int* get(const std::string& k, int version) const { auto* n = find(roots[version], k); return n ? &n->value : nullptr; }
int size(int version) const { return sz(roots[version]); }
int count_range(const std::string& lo, const std::string& hi, int version) const {
return rank(roots[version], hi) - rank(roots[version], lo);
}
};
int main() {
PersistentMap m;
m.put("apple", 3); m.put("bread", 2); m.put("milk", 1);
int with_tea = m.put("tea", 5);
int milk_up = m.put("milk", 2);
int no_tea = m.erase("tea");
int branch = m.put("cocoa", 7, with_tea); // a branch from the version that added tea
for (int v : {with_tea, milk_up, no_tea, branch}) {
const int* milk = m.get("milk", v);
const int* tea = m.get("tea", v);
std::printf("v%d: size %d, milk %s, tea %s, keys in [b, n): %d\n", v, m.size(v),
milk ? std::to_string(*milk).c_str() : "-", tea ? std::to_string(*tea).c_str() : "-",
m.count_range("b", "n", v));
}
}v4: size 4, milk 1, tea 5, keys in [b, n): 2
v5: size 4, milk 2, tea 5, keys in [b, n): 2
v6: size 3, milk 2, tea -, keys in [b, n): 2
v7: size 5, milk 1, tea 5, keys in [b, n): 3
Ideas to extend the store
- Durability: write each commit's new nodes to an append-only file, with the root's file offset as the version id. That is the copy-on-write B-tree design of LMDB, where readers of old versions never block the writer.
- B-tree nodes: with keys per node, path copying writes blocks per commit (B-Trees Revisited).
- Merges of branches: a three-way merge (base, ours, theirs) can use the diff of step 3 twice and apply non-conflicting changes.
- Partial persistence with space per change: replace path copying by node copying on a red-black tree, giving up branches.
Test yourself
Why does the diff in step 3 skip a pair of subtrees when they are the same object?
- Because they are empty
- Because path copying never modifies a node, so a shared node has identical contents in both versions, down to its leaves
- Because they have the same root key
- Because the diff is approximate
Why does the diff rely on the priorities being a fixed function of the key?
- To make the program faster
- So that the treap's shape depends only on the set of keys: when roots differ, the one with higher priority must be a key missing from the other tree
- Because random numbers are not allowed
- To balance the tree
How many new nodes does a commit that changes keys create in a store of keys?
- expected: one copied path per changed key