Persistent Data Structures
Keeping every version: path copying, fat nodes and functional lists.
Every Git commit keeps the entire history of a project reachable, yet a new commit stores only what changed: unchanged files and folders are shared with the commits before it. That trick, sharing every part that did not change, works for any linked data structure. Driscoll, Sarnak, Sleator and Tarjan (1989) showed that a pointer structure whose nodes have a bounded number of incoming pointers can keep all its past versions for amortized extra time and space per update.
What you’ll learn
- Distinguish ephemeral, partially, fully and confluently persistent structures by the shape of their version graphs.
- Make lists and search trees persistent by sharing structure and path copying, and count the space each update costs.
- Prove that node copying makes any structure of bounded in-degree partially persistent with amortized overhead, using a potential function.
- Answer "what is the -th smallest value in ?" in time with a persistent segment tree.
- Describe confluent persistence and retroactive data structures, and what remains open about them.
Versions, and the simplest persistent structure
The simplest example is the linked stack. Pushing creates one new node that points to the old top, and popping just returns the second node: neither operation changes an existing node, so every older stack stays intact, and all the versions share their common tails.
def push(stack, x): # O(1): the new version shares the whole old stack
return (x, stack)
def pop(stack): # O(1): the top, and the version without it
x, rest = stack
return x, rest
xs = push(push(push(None, 1), 2), 3) # 3 -> 2 -> 1
ys = push(xs, 4) # 4 -> 3 -> 2 -> 1
zs = push(xs, 5) # 5 -> 3 -> 2 -> 1, sharing the nodes of xs with ys
assert ys[1] is xs and zs[1] is xsTwo branches grown from the same version, as full persistence allows, with no copying at all. Changing the bottom element is another matter: every node above it would have to be copied, , because each of them reaches the changed node.
An editor keeps every state of a document. You may jump back to any earlier state and keep editing from there, which starts a new branch, but you can never merge two branches. Which kind of persistence is this?
- Ephemeral
- Partial persistence
- Full persistence
- Confluent persistence
Show the answer
C. Full persistence
Old versions can be updated, which grows a tree of versions: full persistence. Partial persistence would forbid editing old states, and confluent persistence would also allow merging two branches into one.
Path copying
The stack's lesson generalizes. When an update changes a node, every node from which the change can be reached would see a different structure, so those nodes are copied, and everything else is shared. In a tree, the nodes that can reach a node are exactly its ancestors, so an update copies only the path from the root to the changed node: path copying. Each version is identified by its own root.
def insert(t, key): # t is None or a tuple (left, key, right)
if t is None:
return (None, key, None)
left, k, right = t
if key < k:
return (insert(left, key), k, right) # copy this node; share the right subtree
if key > k:
return (left, k, insert(right, key)) # copy this node; share the left subtree
return t # already present: share everything
versions = [None]
for key in [50, 30, 70, 20, 40, 60, 80, 35]:
versions.append(insert(versions[-1], key)) # every old root still sees its old treeInserting 35 into the tree of 50, 30, 70, 20, 40, 60 and 80 creates exactly 4 nodes: copies of 50, 30 and 40, plus the new 35. All nine versions together use 21 nodes, where storing each version separately would take 36. Tested: every version keeps its own sorted contents.
Path copying is how purely functional languages store their sets, maps and sequences, usually in wide trees: Clojure's persistent vectors and maps branch 32 ways per node, so an update copies about nodes. Git shares unchanged directories between commits the same way, and databases with multi-version concurrency control keep old versions of rows so that readers see a consistent snapshot while writers proceed.
An early landmark was geometric. To locate a query point in a planar subdivision, Sarnak and Tarjan (1986) swept a vertical line across the plane and kept the segments crossing it in a persistent search tree, one version for each slab between consecutive vertices. A query then searches a single version, in time, and with the space-efficient persistence of the next step the whole structure takes only space.
Fat nodes and node copying
Path copying costs space per update even when a single field changes. Two methods do better for partial persistence, where the versions are numbered in order of time.
Fat nodes. Never copy anything: every field keeps a list of (version, value) pairs, extended on each write. An update then costs space, but reading a field in version needs a binary search for the last write at or before , an slowdown on every access after updates. The fat-node method saves space and pays in reading time.
Node copying (Driscoll, Sarnak, Sleator & Tarjan, 1989) caps the fat: each node may hold only a constant number of recorded writes, and is copied when it runs out of room.
The construction. Each node keeps its fields as they were when it was created, room for up to modifications (field, version, new value), and pointers back to the nodes that point to it in the newest version. Reading a field in version scans at most modifications for the last one with version at most : . To write a field in the newest version, record a modification if the node has room. If it is full, make a fresh copy holding the newest values and no modifications, write the field there, and then write into each of the at most nodes that point to the old node, to redirect them to the copy; those writes may copy their nodes in turn. A node created during the current update has no older version to protect, so later writes to it in the same update simply overwrite its fields; each node is thus copied at most once per update, and the recursion ends.
The potential. Let be times the number of modifications stored in the nodes of the newest version, for a constant chosen below; starts at 0 and never goes negative. A write into a node with room has actual cost at most a constant and raises by :
A write into a full node costs a constant for the copy (constant-size nodes, back pointers included), plus the recursive writes. The full node leaves the newest version, taking its modifications with it, and the copy starts with none. Assume, by induction on the recursion, that each of the at most recursive writes has amortized cost at most :
Choose . Then every write of either kind has amortized cost at most , which completes the induction. Since , the total actual cost is at most the total amortized cost; and the space grows only by modification records and copies, each paid for in the same way:
Full persistence needs one more idea, because the versions now form a tree and "the last write before version " is no longer defined by one number. Driscoll et al. lay the version tree out as a list kept in an order-maintenance structure and split full nodes instead of copying them, again with amortized overhead per update for bounded in-degree. Brodal (1996) later removed the amortization for partial persistence: worst-case time per update. The bound on in-degree is essential: a node pointed to by others forces writes every time it is copied.
Persistent segment trees: the k-th smallest in a range
A classic contest problem: given , answer many queries "what is the -th smallest value in ?", with both ends inclusive. Sorting each range costs per query; persistence answers each in .
After coordinate compression the values lie in with . Let version be a segment tree over the values that counts how many of fall into each value range. is plus one occurrence of : a single root-to-leaf path changes, so path copying builds all versions with new nodes each. The counts subtract like prefix sums: in any value range, the number of elements of is the count in minus the count in . So descend and together, going left when the left halves hold at least of the range's elements, and otherwise going right with reduced by that number.
def build_versions(a, V): # values in range(V); versions[i] counts a[0..i-1]
L, R, cnt = [0], [0], [0] # node 0 is the shared empty tree
def insert(node, lo, hi, x): # returns a new node; copies one root-to-leaf path
L.append(L[node]); R.append(R[node]); cnt.append(cnt[node] + 1)
new = len(cnt) - 1
if hi - lo > 1:
mid = (lo + hi) // 2
if x < mid:
L[new] = insert(L[node], lo, mid, x)
else:
R[new] = insert(R[node], mid, hi, x)
return new
versions = [0]
for x in a:
versions.append(insert(versions[-1], 0, V, x))
return versions, L, R, cnt
def kth_smallest(versions, L, R, cnt, V, l, r, k): # k-th smallest (1-based) of a[l..r]
u, v, lo, hi = versions[r + 1], versions[l], 0, V
while hi - lo > 1:
mid = (lo + hi) // 2
left = cnt[L[u]] - cnt[L[v]] # elements of a[l..r] in [lo, mid)
if k <= left:
u, v, hi = L[u], L[v], mid
else:
u, v, lo, k = R[u], R[v], mid, k - left
return lotime and space to build, per query; tested against sorting on random arrays. For with , the five insertions create nodes, and the 2nd smallest value of is 2.
Confluence, retroactivity and the frontier
Confluent persistence lets an operation combine versions, and that changes the game. Concatenating a one-element list with itself 30 times produces a list of elements in 30 operations, so a confluently persistent structure must represent objects exponentially larger than the work spent building them, and copying nodes one by one cannot keep up. Fiat and Kaplan (2001) gave general transformations for confluent persistence, later improved by Collette, Iacono and Langerman (2012), and Demaine, Langerman and Price (2008) built confluently persistent tries as a model of version control with merges.
Retroactive data structures (Demaine, Iacono & Langerman, 2004; journal version 2007) go further: they let you insert or delete an operation in the past and see how the present changes, as when a late transaction must be backdated. A partially retroactive structure answers queries only about the present; a fully retroactive one answers queries about any time. In general, a change made operations in the past can cost time to propagate, so no generic transformation is efficient, but specific structures do far better: a partially retroactive priority queue runs in time per operation.
Key takeaways
- Partial persistence keeps a line of versions, full persistence a tree (old versions can be updated), and confluent persistence a directed acyclic graph (versions can be combined); immutable structures are fully persistent for free.
- Path copying copies only the nodes from which a change can be reached: for a stack push, per update in a balanced tree, with each version identified by its root.
- Fat nodes cost space per update but slow every read by a search; node copying, analyzed with a potential function, gives amortized time and space per update and access for structures of bounded in-degree (Driscoll, Sarnak, Sleator & Tarjan, 1989).
- A persistent segment tree of prefix versions answers "the -th smallest value in " in time by descending and together.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A persistent red-black tree with keys uses path copying. About how many new nodes does one insertion create?
Show the answer
B.
Only the nodes that can reach the change, the ancestors of the new key, must be copied, plus neighbors touched by rotations: nodes, since the tree's height is . Everything else is shared with the previous version.
Why does the node-copying method require the in-degree of every node to be bounded by a constant ?
- Because reading a field must scan all the pointers into its node
- Because copying a full node forces a write into every node that points to it, and free modification slots per node are what pay for those writes
- Because nodes with many incoming pointers cannot be stored in memory
- Because the potential function counts incoming pointers
Show the answer
B. Because copying a full node forces a write into every node that points to it, and free modification slots per node are what pay for those writes
When a node is copied, its predecessors must be redirected to the copy, one write each. The potential stored in the modifications that the old node takes out of the newest version pays for at most such writes at amortized cost each. With unbounded in-degree, one copy could trigger arbitrarily many writes.
Version of a persistent segment tree counts the values of . To find the -th smallest value of (both ends inclusive), which two versions does the query descend together, subtracting their counts?
- and
- and
- and
- and
Show the answer
C. and
counts and counts , so their difference counts exactly , the same convention as prefix sums: .
What is the main drawback of the fat-node method for partial persistence?
- Each update copies the whole path from the root
- It works only for trees
- Old versions eventually become unreadable
- Reading a field requires searching its history of writes, an slowdown on every access after updates
Show the answer
D. Reading a field requires searching its history of writes, an slowdown on every access after updates
A fat node stores every write to every field, so updates cost space, but each read must find the last write at or before the requested version. Node copying caps the history at writes per node, which makes reads .
Further reading
- J. R. Driscoll, N. Sarnak, D. D. Sleator & R. E. Tarjan, "Making data structures persistent," Journal of Computer and System Sciences 38(1) (1989), 86–124.
- N. Sarnak & R. E. Tarjan, "Planar point location using persistent search trees," Communications of the ACM 29(7) (1986), 669–679.
- C. Okasaki, Purely Functional Data Structures (Cambridge University Press, 1998).
- E. D. Demaine, J. Iacono & S. Langerman, "Retroactive data structures," ACM Transactions on Algorithms 3(2) (2007).
- E. D. Demaine, MIT 6.851 Advanced Data Structures, lecture notes on persistent and retroactive data structures (Spring 2012).