Node Copying in O(1) Amortized Overhead
Fat nodes make every field read a binary search; path copying makes every update copy a whole path. The node-copying method of Driscoll, Sarnak, Sleator and Tarjan (1989) combines the two ideas and gets the best of both for partial persistence:
Theorem (DSST 1989). Any pointer-machine data structure in which every node has in-degree at most a constant can be made partially persistent so that each update costs amortized extra time and amortized extra space per field change, and each field read in any version costs worst-case time.
So a red-black tree, whose rebalancing changes amortized fields per insertion, becomes a partially persistent search tree with amortized space per update and query time in every version. Sarnak and Tarjan (1986) used exactly this to solve planar point location in query time and space.
The construction
Each node has its ordinary fields, frozen at the version when the node was created, plus
- modification slots, each holding
(version, field, new value); - back pointers to the nodes that currently point to it (at most , since in-degree is at most ).
Reading field of node in version : start with the frozen value and apply the modifications of with version at most , in order. At most slots, so .
Writing field of node (always in the newest version):
- If has a free modification slot, record
(now, f, value)there. Done. - Otherwise is full. Create a copy whose frozen fields are the latest values of (with the new value of ), and empty slots. Fix the back pointers of the nodes points to. Then every node that points to in the newest version must now point to : for each back pointer, write that parent's pointer field, recursively, which may fill and copy the parent, and so on. If was a root of the structure, record as the root of the new version.
Old versions still reach the old through their old pointers, and old is never modified again, so they are unaffected.
Why the overhead is amortized
A write may cascade, copying a chain of nodes, so the worst case is not constant. Use the potential
Let one unit of actual work cost at most (a slot write, or copying one node of fields).
- A write into a free slot costs and raises by : amortized .
- Copying a full node costs for the copy, and the old stops being "latest", so its used slots leave the potential: drops by . The copy then causes at most writes to parents.
Look at one top-level write as a tree of recursive writes: internal nodes are copies, each with at most children, and leaves are slot writes. With copies there are at most leaves, so the amortized cost is at most
With the bracket is at most , so every write costs at most amortized, however long its cascade. The slots per node are exactly what pays for the parents each copy has to update. Space follows the same argument, since each unit of work creates storage.
A partially persistent linked list
The program applies node copying to a sorted singly linked list (in-degree , so 2 modification slots per node), with a head sentinel whose copies are recorded in a table of roots. It makes 600 insertions, a third of them at the front so that the same nodes are written again and again, and reads back every one of the 601 versions.
import bisect, random
MODS = 2 # 2p modification slots, p = 1 (in-degree of a list node)
class PNode:
__slots__ = ("fields", "mods", "back")
def __init__(self, fields):
self.fields = dict(fields) # values at the time the node was created
self.mods = [] # (version, field, value), at most MODS
self.back = set() # (latest parent node, its field) pointing here
class NodeCopyingList:
"""Partially persistent sorted linked list by node copying (Driscoll, Sarnak, Sleator, Tarjan)."""
def __init__(self):
self.version = 0
self.roots = [(0, PNode({"key": None, "next": None}))] # head sentinel per version
self.copies = self.mod_writes = 0
def read(self, node, field, v): # O(MODS) per field read
val = node.fields[field]
for ver, f, x in node.mods:
if f == field and ver <= v: val = x
return val
def _latest(self, node, field):
return self.read(node, field, self.version)
def _write(self, node, field, value):
old = self._latest(node, field)
if len(node.mods) < MODS: # a free slot: record the change in place
node.mods.append((self.version, field, value)); self.mod_writes += 1
if field == "next":
if old is not None: old.back.discard((node, "next"))
if value is not None: value.back.add((node, "next"))
return
# Full: copy the node with its latest values, then point its parents at the copy.
self.copies += 1
latest = {f: self._latest(node, f) for f in node.fields}
latest[field] = value
copy = PNode(latest)
copy.back = set(node.back)
if field == "next" and old is not None: old.back.discard((node, "next"))
nxt = latest["next"]
if nxt is not None:
nxt.back.discard((node, "next")); nxt.back.add((copy, "next"))
if self.roots[-1][1] is node: # the head sentinel: a new root for this version
self.roots.append((self.version, copy))
for parent, f in list(copy.back): # at most p = 1 parent in a list
self._write(parent, f, copy) # may cascade upwards
def head(self, v):
i = bisect.bisect_right([ver for ver, _ in self.roots], v) - 1
return self.roots[i][1]
def insert(self, key): # new version: insert key in sorted position
self.version += 1
prev = self.head(self.version)
nxt = self._latest(prev, "next")
while nxt is not None and self._latest(nxt, "key") < key:
prev, nxt = nxt, self._latest(nxt, "next")
node = PNode({"key": key, "next": nxt})
if nxt is not None: nxt.back.add((node, "next"))
self._write(prev, "next", node)
def items(self, v):
out, x = [], self.read(self.head(v), "next", v)
while x is not None:
out.append(self.read(x, "key", v)); x = self.read(x, "next", v)
return out
rng = random.Random(1989)
lst, ref = NodeCopyingList(), [[]]
worst = 0
for i in range(600):
k = rng.randrange(100) if i % 3 else 0 # many inserts at the front: repeated writes to the same nodes
before = lst.copies
lst.insert(k)
worst = max(worst, lst.copies - before)
ref.append(sorted(ref[-1] + [k]))
assert all(lst.items(v) == ref[v] for v in range(601))
print("all 601 versions read back correctly; version 5:", lst.items(5))
print(f"600 updates: {lst.mod_writes} mod writes, {lst.copies} node copies, "
f"{(lst.mod_writes + lst.copies) / 600:.2f} new pieces of storage per update")
print(f"most copies caused by a single update: {worst}")
all 601 versions read back correctly; version 5: [0, 0, 21, 32, 72]
600 updates: 532 mod writes, 182 node copies, 1.19 new pieces of storage per update
most copies caused by a single update: 2
The total new storage per update stays near one piece (a slot or a copy), and no single update copied more than two nodes. For comparison, path copying would have copied every node on the path from the head to the insertion point, about half the list on average.
In C++
The same method in C++, with the single back pointer of a list node stored in the node. Ten inserts produce ten versions, and the old ones are printed from their own head sentinels.
#include <cstdio>
#include <memory>
#include <vector>
// Node copying for a partially persistent sorted singly linked list (in-degree p = 1, 2p = 2 mod slots).
struct Node {
int key;
Node* next; // value of "next" when the node was created
struct Mod { int version; Node* next; };
Mod mods[2];
int nmods = 0;
Node* parent = nullptr; // back pointer: the latest node whose next is this one
};
class PersistentList {
std::vector<std::unique_ptr<Node>> pool;
std::vector<std::pair<int, Node*>> roots; // (first version, head sentinel)
int version = 0;
Node* make(int key, Node* next) {
pool.push_back(std::make_unique<Node>(Node{key, next, {}, 0, nullptr}));
return pool.back().get();
}
static Node* next_at(const Node* x, int v) {
Node* r = x->next;
for (int i = 0; i < x->nmods; ++i) if (x->mods[i].version <= v) r = x->mods[i].next;
return r;
}
void set_next(Node* x, Node* value) { // in the newest version
if (x->nmods < 2) {
x->mods[x->nmods++] = {version, value};
if (value) value->parent = x;
return;
}
++copies;
Node* c = make(x->key, value); // copy with the latest field values
c->parent = x->parent;
if (value) value->parent = c;
if (roots.back().second == x) roots.push_back({version, c});
else set_next(c->parent, c); // the parent now points to the copy (may cascade)
}
public:
long copies = 0;
PersistentList() { roots.push_back({0, make(-1, nullptr)}); }
Node* head(int v) const {
Node* h = roots[0].second;
for (auto [ver, node] : roots) if (ver <= v) h = node;
return h;
}
void insert(int key) {
++version;
Node* prev = head(version);
Node* nxt = next_at(prev, version);
while (nxt && nxt->key < key) { prev = nxt; nxt = next_at(nxt, version); }
Node* x = make(key, nxt);
if (nxt) nxt->parent = x;
x->parent = prev;
set_next(prev, x);
}
void print(int v) const {
std::printf("version %2d:", v);
for (Node* x = next_at(head(v), v); x; x = next_at(x, v)) std::printf(" %d", x->key);
std::printf("\n");
}
int versions() const { return version; }
std::size_t nodes() const { return pool.size(); }
};
int main() {
PersistentList l;
for (int k : {50, 10, 40, 10, 30, 20, 60, 10, 45, 5}) l.insert(k);
for (int v : {0, 1, 3, 6, 10}) l.print(v);
std::printf("%d versions, %zu nodes allocated (%zu list nodes + head + %ld copies)\n",
l.versions(), l.nodes(), static_cast<std::size_t>(l.versions()), l.copies);
}version 0:
version 1: 50
version 3: 10 40 50
version 6: 10 10 20 30 40 50
version 10: 5 10 10 10 20 30 40 45 50 60
10 versions, 13 nodes allocated (10 list nodes + head + 2 copies)
Comparing the three methods
For the same 600 insertions, the program counts the storage each method creates. Path copying has to copy every node before the insertion point, since a singly linked list is one long path, while fat nodes and node copying add per insertion.
import bisect, random
# The same 600 insertions as above, measured for three persistence methods on a sorted linked list.
rng = random.Random(1989)
keys, fat_pairs, path_nodes, reads_fat = [], 0, 0, 0
for i in range(600):
k = rng.randrange(100) if i % 3 else 0
pos = bisect.bisect_right(keys, k) # insertion point
keys.insert(pos, k)
fat_pairs += 2 # fat nodes: the new node, plus one (version, value) pair
path_nodes += pos + 1 # path copying: copy every node before the insertion point
print("storage created by 600 insertions into a persistent sorted list:")
print(f" fat nodes: {fat_pairs:6} pieces, but every later read of a field is a binary search")
print(f" path copying: {path_nodes:6} nodes ({path_nodes / 600:.1f} per insertion: the whole prefix of the list)")
print(f" node copying: {532 + 182 + 600:6} pieces (600 new nodes + 532 slots + 182 copies, from the run above)")storage created by 600 insertions into a persistent sorted list:
fat nodes: 1200 pieces, but every later read of a field is a binary search
path copying: 102411 nodes (170.7 per insertion: the whole prefix of the list)
node copying: 1314 pieces (600 new nodes + 532 slots + 182 copies, from the run above)
Fat nodes are as small as node copying, but they pay with a binary search on every field read, while node copying reads any field in .
Beyond partial persistence
| Result | Overhead | Notes |
|---|---|---|
| node copying (DSST 1989) | amortized time and space per change; worst-case reads | partial persistence, in-degree |
| Brodal (1996) | worst case per change | partial persistence, in-degree |
| node splitting (DSST 1989) | amortized time and space per change | full persistence, in-degree ; versions kept in an order-maintenance structure |
| fat nodes | per read, space per change | any structure, partial or full |
| path copying | copies per update | any tree without parent pointers, full persistence |
Full persistence needs a different trick because a node's modifications may come from different branches of the version tree. In node splitting, a full node is split into two nodes, each holding the modifications of a part of the version tree, and versions are compared by their position in a linear order of the version tree maintained with the order-maintenance structure of Dietz and Sleator (1987).
The in-degree condition matters. A structure with unbounded in-degree, such as a node pointed to by many others, would need a copy to update all of its parents. Arrays are not pointer-machine structures at all. Dietz (1989) showed how to make an array fully persistent with time per access using van Emde Boas-style search over versions, and a reduction from predecessor search together with the Pătrașcu-Thorup lower bounds indicates that this cannot be improved in general.
Test yourself
What happens when node copying writes to a node whose modification slots are all used?
- The oldest modification is overwritten
- The node is copied with its latest values, and every node pointing to it in the newest version is updated to point to the copy, recursively
- The write is stored in a fat-node list
- The whole structure is copied
In the potential argument, why are modification slots enough?
- Because each node has at most fields
- Because copying a full node releases units of potential, which pays for the at most parent writes it causes
- Because there are at most versions
- Because reads must stay
Which structures does the DSST node-copying theorem apply to?
- Any data structure
- Pointer-machine structures whose nodes have in-degree at most a constant
- Only arrays
- Only balanced binary search trees