Path Copying: a Persistent BST
The simplest way to make a tree persistent: never change a node; copy it. To update a node, make a copy with the new field values, then copy its parent so that the parent points to the copy, and so on up to the root. The new root is the new version; the old root still describes the old version, untouched. Every node off the copied path is shared by both versions. This is path copying, the technique behind the immutable maps and sets of functional languages (Clojure, Scala, Haskell's Data.Map), and it gives full persistence for free: any version can be updated, since nothing is ever modified.
The cost
An update that changes the nodes on one root-to-node path creates as many new nodes as the path is long. In a balanced BST of keys that is time and space per update, against amortized space for an ephemeral tree. Rebalancing must also be done by copying: every rotation touches nodes on or next to the search path, so it adds only copies per rotation. A query on any version is an ordinary search from that version's root, , with no slowdown at all.
Path copying requires that nodes have no parent pointers (a parent pointer would force copying the whole tree, since every child would have to point to the new parent). Algorithms that need parents keep them on a stack during the descent.
A small example
The program inserts keys into an unbalanced BST by path copying and keeps every version. It then prints each version and the identity of every node, showing which nodes are shared between versions.
class Node:
__slots__ = ("key", "left", "right", "id")
count = 0
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right = key, left, right
Node.count += 1
self.id = Node.count # creation number, to see sharing
def insert(t, key): # returns a new root; t is not modified
if t is None:
return Node(key)
if key < t.key:
return Node(t.key, insert(t.left, key), t.right) # copy t, share t.right
if key > t.key:
return Node(t.key, t.left, insert(t.right, key)) # copy t, share t.left
return t # already present: share everything
def show(t):
return "." if t is None else f"({show(t.left)} {t.key}#{t.id} {show(t.right)})"
versions = [None]
for k in [50, 30, 70, 20, 40, 60, 45]:
versions.append(insert(versions[-1], k))
for v in [3, 6, 7]:
print(f"version {v}: {show(versions[v])}")
print("nodes created:", Node.count, " (an ephemeral tree has 7; copying all versions fully would need",
sum(range(1, 8)), ")")version 3: ((. 30#2 .) 50#5 (. 70#4 .))
version 6: (((. 20#6 .) 30#10 (. 40#9 .)) 50#14 ((. 60#12 .) 70#13 .))
version 7: (((. 20#6 .) 30#17 (. 40#16 (. 45#15 .))) 50#18 ((. 60#12 .) 70#13 .))
nodes created: 18 (an ephemeral tree has 7; copying all versions fully would need 28 )
Versions 6 and 7 share the nodes 20#6, 60#12 and 70#13: the insertion of 45 copied only the path 50, 30, 40 and added the new leaf.
A balanced persistent set
Path copying works with any balanced BST whose rebalancing is local. A treap is the easiest to write functionally: each key gets a priority, the tree is a BST by key and a heap by priority, and the shape is then determined by the keys and priorities alone. Insertion and deletion are written with two functional primitives, SPLIT (by key) and MERGE, each of which copies one path. Here the priority is a fixed hash of the key, so the program is deterministic; with random priorities the expected depth is (The Expected Height of a Random BST is the same analysis).
SPLIT(t, k) // returns (keys < k, keys >= k); copies one path
1 if t == NIL return (NIL, NIL)
2 if t.key < k
3 (a, b) = SPLIT(t.right, k)
4 return (copy of t with right = a, b)
5 else
6 (a, b) = SPLIT(t.left, k)
7 return (a, copy of t with left = b)
INSERT(t, k) = let (a, b) = SPLIT(t, k) in MERGE(MERGE(a, new node k), b) // if k not in timport bisect, random
def prio(k): # a fixed pseudo-random priority per key
return (k * 2654435761 + 12345) % 4294967296
class T:
__slots__ = ("key", "left", "right", "size")
made = 0
def __init__(self, key, left, right):
self.key, self.left, self.right = key, left, right
self.size = 1 + (left.size if left else 0) + (right.size if right else 0)
T.made += 1
def split(t, k): # (< k, >= k)
if t is None: return None, None
if t.key < k:
a, b = split(t.right, k)
return T(t.key, t.left, a), b
a, b = split(t.left, k)
return a, T(t.key, b, t.right)
def merge(a, b): # all keys of a < all keys of b
if a is None or b is None: return a or b
if prio(a.key) > prio(b.key):
return T(a.key, a.left, merge(a.right, b))
return T(b.key, merge(a, b.left), b.right)
def contains(t, k):
while t is not None and t.key != k:
t = t.left if k < t.key else t.right
return t is not None
def insert(t, k):
if contains(t, k): return t
a, b = split(t, k)
return merge(merge(a, T(k, None, None)), b)
def delete(t, k):
if not contains(t, k): return t
a, b = split(t, k)
_, c = split(b, k + 1) # drop the single node with key k
return merge(a, c)
def keys(t):
return keys(t.left) + [t.key] + keys(t.right) if t else []
rng = random.Random(1986)
versions, ref = [None], [[]]
for step in range(3000):
t, r = versions[-1], ref[-1]
if r and rng.random() < 0.3:
k = rng.choice(r); t2 = delete(t, k); r2 = [x for x in r if x != k]
else:
k = rng.randrange(10 ** 6); t2 = insert(t, k); r2 = sorted(set(r + [k]))
versions.append(t2); ref.append(r2)
for v in rng.sample(range(len(versions)), 200): # any old version is still intact
assert keys(versions[v]) == ref[v]
n = versions[-1].size
print(f"3000 updates, final size {n}; all 200 sampled old versions intact")
print(f"nodes created: {T.made}, {T.made / 3000:.1f} per update; lg n = {n.bit_length() - 1}")
print(f"storing every version separately would take {sum(len(r) for r in ref)} nodes")3000 updates, final size 1219; all 200 sampled old versions intact
nodes created: 79042, 26.3 per update; lg n = 10
storing every version separately would take 1902127 nodes
About 26 new nodes per update, a small multiple of (insertion copies the split path and the merge path; deletion copies two split paths and a merge path), against 1.9 million for full copies.
In C++
The same persistent treap with std::shared_ptr<const Node>: nodes are immutable, sharing is automatic, and an old version stays alive as long as some root refers to it. The program builds versions, branches from an old one (full persistence) and queries all of them.
#include <cstdint>
#include <cstdio>
#include <memory>
#include <utility>
#include <vector>
struct Node;
using P = std::shared_ptr<const Node>;
struct Node {
int key;
P left, right;
};
long made = 0;
P make(int key, P l, P r) { ++made; return std::make_shared<const Node>(Node{key, std::move(l), std::move(r)}); }
std::uint32_t prio(int k) { return static_cast<std::uint32_t>(k * 2654435761u + 12345u); }
std::pair<P, P> split(const P& t, int k) { // (< k, >= k)
if (!t) return {nullptr, nullptr};
if (t->key < k) { auto [a, b] = split(t->right, k); return {make(t->key, t->left, a), b}; }
auto [a, b] = split(t->left, k);
return {a, make(t->key, b, t->right)};
}
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->left, merge(a->right, b));
return make(b->key, merge(a, b->left), b->right);
}
bool contains(P t, int k) {
while (t && t->key != k) t = k < t->key ? t->left : t->right;
return t != nullptr;
}
P insert(const P& t, int k) {
if (contains(t, k)) return t;
auto [a, b] = split(t, k);
return merge(merge(a, make(k, nullptr, nullptr)), b);
}
P erase(const P& t, int k) {
if (!contains(t, k)) return t;
auto [a, b] = split(t, k);
return merge(a, split(b, k + 1).second);
}
void print(const char* name, const P& t) {
std::printf("%s:", name);
std::vector<const Node*> stack;
for (const Node* x = t.get(); x || !stack.empty();) { // in-order walk with an explicit stack
while (x) { stack.push_back(x); x = x->left.get(); }
x = stack.back(); stack.pop_back();
std::printf(" %d", x->key);
x = x->right.get();
}
std::printf("\n");
}
int main() {
P v0;
P v1 = insert(insert(insert(v0, 50), 20), 80);
P v2 = insert(v1, 60);
P v3 = erase(v2, 20);
P v4 = insert(v1, 10); // branch from version 1
print("v1", v1); print("v2", v2); print("v3", v3); print("v4", v4);
std::printf("60 in v1? %d in v2? %d 20 in v3? %d in v4? %d\n",
contains(v1, 60), contains(v2, 60), contains(v3, 20), contains(v4, 20));
std::printf("nodes created: %ld\n", made);
}v1: 20 50 80
v2: 20 50 60 80
v3: 50 60 80
v4: 10 20 50 80
60 in v1? 0 in v2? 1 20 in v3? 0 in v4? 1
nodes created: 22
When path copying is the right choice
| Need | Method |
|---|---|
| full persistence, simple code, immutable values shared between threads | path copying, space per update |
| partial persistence with extra space per update | node copying |
| only "undo the last operations" | an ephemeral structure with an undo log, per change |
Because old versions are never touched, path-copied structures are also safe to read concurrently while a writer builds the next version, which is why databases (copy-on-write B-trees in LMDB and in Btrfs) and functional languages use them. Garbage collection or reference counting reclaims versions nobody refers to.
Common mistakes
- Mutating a "copy". In languages with mutable objects it is easy to copy a node and then modify one of its children in place, which silently changes every version that shares that child. Every write must go to a node created in the current update. Making nodes immutable (
constin C++,__slots__without setters, frozen dataclasses) turns the mistake into an error. - Rebalancing in place. Rotations of a red-black or AVL tree change three or four pointers; done destructively, they corrupt old versions. Write each rotation as "build the rotated nodes from the old ones", which copies nodes per rotation.
- Counting only time. Path copying is time per update, like the ephemeral tree, but also space. A system that keeps every version of a structure with updates needs nodes, so long histories need a retention policy (the mini project measures one).
- Amortized structures. Persistence and amortization do not mix: an operation that is expensive only once in a while can be replayed from the same old version again and again, as the introduction showed with a dynamic array. Path copying needs worst-case bounds, so splay trees are a poor base, and red-black trees, AVL trees or treaps (expected bounds over their random priorities) are good ones.
Test yourself
How many new nodes does inserting into a balanced BST of keys create with path copying?
- : one copy for each node on the search path, plus per rotation
Why are parent pointers incompatible with path copying?
- They waste space
- Copying a node would require changing the parent pointers of its children, and then copying them too, which spreads to the whole tree
- They make search slower
- They are not allowed on a pointer machine
Which kind of persistence does path copying give?
- Partial only
- Full: any version can be updated, since no node is ever modified
- Confluent in all cases
- None; it is an undo log