TExcelTAD
Home › Advanced & Succinct Data Structures › Partial, Full and Confluent Persistence

Partial, Full and Confluent Persistence

An ordinary data structure is ephemeral: an update destroys the old state. A persistent structure keeps every version. Persistence turns up wherever history matters: undo, version control, functional programming languages (where values never change), databases that answer queries "as of" a past time, and in geometry, where a sweep line's successive states become one searchable structure. Driscoll, Sarnak, Sleator and Tarjan (1989) gave the general techniques; this section follows their framework.

Four levels of persistence

Number the versions 0,1,2,…0, 1, 2, \ldots in the order they are created. The levels differ in which versions an operation may use.

Level Queries on Updates on Shape of the versions
ephemeral the current version the current version one version
partial any version the newest version only a line: 0→1→2→⋯0 \to 1 \to 2 \to \cdots
full any version any version (creating a new one) a tree: a version branches from the one it updated
confluent any version any version, and operations may combine two versions (e.g. concatenate two lists) a DAG

A functional (purely functional) structure never modifies a node after creating it; it is automatically fully persistent, and with combining operations confluently persistent. Most of this section works in the pointer machine model (Models of Computation): a structure is a graph of nodes with a constant number of fields, and an operation reads and writes fields.

Fat nodes

The most direct method: never overwrite a field. Every field becomes a list of (version, value) pairs, appended to when the field is written. To read a field in version vv, find the pair with the largest version ≤v\le v.

  • Partial persistence. Versions form a line, so each list is sorted by version, and reading is a binary search: O(lg⁡m)O(\lg m) time per field access after mm updates, instead of O(1)O(1). Writing appends in O(1)O(1). Space is O(1)O(1) per field write, which is optimal.
  • Full persistence. Versions form a tree, and "the largest version ≤v\le v" must mean "the nearest ancestor of vv in the version tree that wrote this field". The trick is to keep the versions in an order-maintenance structure (Dietz and Sleator, 1987), which compares two versions' positions in a preorder of the version tree in O(1)O(1) worst case; each field's list is then searched by preorder position. Driscoll et al. give the details; the access cost is again a logarithmic factor.

The program builds a partially persistent array with fat nodes, makes 1000 random writes, and reads old versions, counting the comparisons of the binary searches.

python · try it yourself
import bisect, random

class FatArray:
    """Partially persistent array: cell i holds parallel lists of versions and values."""
    def __init__(self, n, init=0):
        self.vers = [[0] for _ in range(n)]
        self.vals = [[init] for _ in range(n)]
        self.version = 0
        self.comparisons = 0
    def write(self, i, x):                     # creates a new version, O(1)
        self.version += 1
        self.vers[i].append(self.version)
        self.vals[i].append(x)
        return self.version
    def read(self, i, v):                      # value of cell i in version v, O(lg m)
        lo, hi, vs = 0, len(self.vers[i]), self.vers[i]
        while lo < hi:                         # first position with version > v
            mid = (lo + hi) // 2
            self.comparisons += 1
            if vs[mid] <= v: lo = mid + 1
            else: hi = mid
        return self.vals[i][lo - 1]

rng = random.Random(1989)
a = FatArray(8)
history = [[0] * 8]                            # ephemeral copies, for checking only
for _ in range(1000):
    i, x = rng.randrange(8), rng.randrange(100)
    a.write(i, x)
    row = history[-1][:]
    row[i] = x
    history.append(row)
for v in [0, 1, 10, 500, 1000]:
    got = [a.read(i, v) for i in range(8)]
    assert got == history[v]
    print(f"version {v:4}: {got}")
a.comparisons = 0
for _ in range(1000):
    v, i = rng.randrange(1001), rng.randrange(8)
    assert a.read(i, v) == history[v][i]
print(f"1000 random reads of old versions: {a.comparisons / 1000:.1f} comparisons each "
      f"(cells have about {1000 // 8} versions, lg = {(1000 // 8).bit_length() - 1})")
print("space: one pair per write,", sum(len(v) for v in a.vers), "pairs in total")
version    0: [0, 0, 0, 0, 0, 0, 0, 0]
version    1: [0, 0, 32, 0, 0, 0, 0, 0]
version   10: [0, 55, 43, 0, 18, 0, 0, 0]
version  500: [95, 70, 88, 49, 83, 47, 87, 12]
version 1000: [71, 81, 38, 65, 9, 66, 53, 34]
1000 random reads of old versions: 7.0 comparisons each (cells have about 125 versions, lg = 6)
space: one pair per write, 1008 pairs in total

The logarithmic slowdown is the weakness of fat nodes. The node-copying method removes it for partial persistence: O(1)O(1) amortized time and space overhead per operation, for any pointer structure with bounded in-degree. Path copying, the functional approach, is simpler and gives full persistence, but copies O(lg⁡n)O(\lg n) nodes per update of a balanced tree.

In C++

A partially persistent array with fat cells, std::upper_bound doing the binary search on versions.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <utility>
#include <vector>

class FatArray {
    std::vector<std::vector<std::pair<int, int>>> cell;  // per cell: (version, value), versions increasing
    int version = 0;
public:
    FatArray(int n, int init) : cell(n, {{0, init}}) {}
    int write(int i, int x) { cell[i].push_back({++version, x}); return version; }
    int read(int i, int v) const {
        const auto& c = cell[i];
        auto it = std::upper_bound(c.begin(), c.end(), std::pair<int, int>{v, 1 << 30});
        return std::prev(it)->second;
    }
};

int main() {
    FatArray a(4, 0);
    int v1 = a.write(0, 10);
    int v2 = a.write(1, 20);
    int v3 = a.write(0, 30);
    a.write(2, 40);
    for (int v : {0, v1, v2, v3, 4}) {
        std::printf("version %d:", v);
        for (int i = 0; i < 4; ++i) std::printf(" %d", a.read(i, v));
        std::printf("\n");
    }
}
version 0: 0 0 0 0
version 1: 10 0 0 0
version 2: 10 20 0 0
version 3: 30 20 0 0
version 4: 30 20 40 0

Full persistence: a version tree

With full persistence an update names the version it starts from, and versions branch. Editors with undo trees and version-control systems work this way. The program below gives the same fat-node array a parent for each version and reads a field by walking from the version towards the root of the version tree until a write to that cell is found. That walk is the naive method; the order-maintenance trick replaces it by a binary search.

python · try it yourself
class FullFatArray:
    def __init__(self, n, init=0):
        self.parent = [None]                   # version 0 is the root of the version tree
        self.writes = [{i: init for i in range(n)}]   # writes[v]: cells written by version v
    def write(self, v, i, x):                  # new version branching off version v
        self.parent.append(v)
        self.writes.append({i: x})
        return len(self.parent) - 1
    def read(self, v, i):
        steps = 0
        while i not in self.writes[v]:
            v, steps = self.parent[v], steps + 1
        return self.writes[v][i], steps
    def snapshot(self, v, n):
        return [self.read(v, i)[0] for i in range(n)]

a = FullFatArray(3)
v1 = a.write(0, 0, 5)          # 0 -> 1
v2 = a.write(v1, 1, 7)         # 1 -> 2
v3 = a.write(v1, 2, 9)         # 1 -> 3: a branch beside version 2
v4 = a.write(v2, 0, 6)         # 2 -> 4
for v in range(5):
    print(f"version {v} (parent {a.parent[v]}): {a.snapshot(v, 3)}")
print("reading cell 2 in version 4 walks", a.read(v4, 2)[1], "steps up the version tree")
version 0 (parent None): [0, 0, 0]
version 1 (parent 0): [5, 0, 0]
version 2 (parent 1): [5, 7, 0]
version 3 (parent 1): [5, 0, 9]
version 4 (parent 2): [6, 7, 0]
reading cell 2 in version 4 walks 3 steps up the version tree

Version 3 does not see version 2's write to cell 1 and version 4 does not see version 3's write to cell 2: each version sees exactly the writes on its path to the root.

Confluent persistence

If an operation may combine two versions, say concatenating two persistent lists, versions form a DAG, and a version can contain the same old data many times. Concatenating a list with itself kk times produces a list of length 2k2^k after kk operations, represented in O(k)O(k) space by sharing. This is why confluent persistence is harder: positions inside a version can need Θ(k)\Theta(k) bits to describe, and the general transformations pay for it. Fiat and Kaplan (2003) gave general methods for confluently persistent pointer structures; Collette, Iacono and Langerman (2012) improved the general transformation, and some specific structures have efficient purely functional versions with catenation, such as the real-time catenable deques of Kaplan and Tarjan (1999).

python · try it yourself
class Cat:                                     # an immutable list as a binary tree of shared pieces
    __slots__ = ("left", "right", "length")
    def __init__(self, left, right):
        self.left, self.right = left, right
        self.length = (left.length if isinstance(left, Cat) else 1) + (right.length if isinstance(right, Cat) else 1)

def nodes(x, seen=None):                       # count distinct stored nodes (shared ones once)
    seen = set() if seen is None else seen
    if isinstance(x, Cat) and id(x) not in seen:
        seen.add(id(x)); nodes(x.left, seen); nodes(x.right, seen)
    return len(seen)

v = Cat("a", "b")
for k in range(1, 41):
    v = Cat(v, v)                               # combine a version with itself
    if k in (1, 2, 10, 20, 40):
        print(f"after {k:2} self-concatenations: length {v.length:>14}, stored nodes {nodes(v)}")
after  1 self-concatenations: length              4, stored nodes 2
after  2 self-concatenations: length              8, stored nodes 3
after 10 self-concatenations: length           2048, stored nodes 11
after 20 self-concatenations: length        2097152, stored nodes 21
after 40 self-concatenations: length  2199023255552, stored nodes 41

Test yourself

In a **partially** persistent structure, which operations are allowed?

  1. Queries and updates on any version
  2. Queries on any version, updates only on the newest one
  3. Only queries on the newest version
  4. Combining two old versions

What does the fat-node method cost per field access after mm updates (partial persistence)?

  1. O(1)O(1)
  2. O(lg⁡m)O(\lg m) for a binary search over the field's versions
  3. O(m)O(m)
  4. O(m)O(\sqrt{m})

Why is confluent persistence harder than full persistence?

  1. Versions form a tree
  2. Combining versions can duplicate old data exponentially often, so a version may be exponentially larger than its stored representation
  3. It needs more hash tables
  4. It does not allow queries on old versions