Algorithm Search⌘K

Data structureadvanced

Prefix B-tree

Also called simple prefix B-tree, suffix truncation.

A B+ tree on string keys whose separators are shortest separators, chosen inside a split interval, and whose nodes store keys without the prefix that their fences share.

Time
O(L log n) worst · average · best
Space
O(n L) extra
Counts
io O(log_f n) worst · average · best
Where
L = the length of the longest key in characters; d = the half width of the split interval; f = the number of separators that fit in an inner page; n = the number of keys
Properties
deterministicexactexternalnot in placeonlineiterative
Origin
Rudolf Bayer, Karl Unterauer, 1977

A prefix B-tree is a B+ tree on string keys that stores less of each key in its inner nodes and in its leaves. Two ideas from Bayer and Unterauer (1977) make it work: a separator in an inner node only has to tell two neighboring subtrees apart, so the shortest string that does this is enough; and all keys between two separators share the prefix of those separators, so a node does not need to store it. Shorter entries give more entries per page, a larger fan-out and a lower tree. Front coding also removes shared prefixes, but it does so in a sorted list that must be decoded from the start of a block, while the prefix B-tree gets the prefix of a node from its two bounding separators during the search.

In plain words

Think of the guide words at the top of a phone book page. The page holds names from "Smart" to "Smith". To send a reader to the right page you do not need the full names. "Smi" is enough to tell "Smart" apart from "Smith", because any name that comes after "Smart" and starts with "Smi" or later belongs to the next page.

Inside a page, every name between the guide words starts with "Sm". So the page can store "art" and "it" and add "Sm" back when it needs the whole name.

The tree does both. Its signposts are as short as they can be, and when a page splits, it looks at a few split points near the middle and takes the one with the shortest signpost.

The abstract type

An ordered set of strings under the usual lexicographic order, with:

  • contains(T, k): is kk in TT?
  • insert(T, k): add kk.
  • range(T, lo, hi): the keys kk with lo≤k≤hilo \le k \le hi, in order.

Deletes work as in a B+ tree. A separator does not need to change when a key is deleted, because it still separates the two subtrees.

Representation

The tree is a B+ tree: all keys are in the leaves, and every leaf is at the same depth. An inner node with children c0,…,cmc_0, \ldots, c_m holds separators s1<⋯<sms_1 < \cdots < s_m. This page uses the convention that every key in ci−1c_{i-1} is less than sis_i and every key in cic_i is at least sis_i.

  • Fences. Each node vv has two fences, low(v)low(v) and high(v)high(v): the separators to the left and to the right of its pointer in its parent, or the fences of the parent at the ends. The root has the open interval. The invariant is that every key kk in the subtree of vv satisfies low(v)≤k<high(v)low(v) \le k < high(v).
  • Shortest separators. When a leaf splits between its keys a<ba < b, the separator is the shortest string ss with a<s≤ba < s \le b. Bayer and Unterauer call a tree with only this change a simple prefix B-tree.
  • Split interval. A split may take any split point within dd positions of the middle. The node takes the point whose separator is shortest. With d=0d = 0 the split is the usual one at the middle.
  • Stored prefix. Let p(v)p(v) be the longest common prefix of low(v)low(v) and high(v)high(v) (empty if a fence is open). Every key in the subtree of vv starts with p(v)p(v), so vv stores each key or separator without it. The paper calls the full design, with these prefixes rebuilt during the search, a prefix B-tree.

The capacity of a page is counted in bytes in a real system. The code on this page counts entries to keep the logic short; the savings show up as fewer characters stored.

Operations

  1. SHORTEST-SEPARATOR(a, b) ▷ a < b; the shortest s with a < s ≤ b
  2. 1i ← 0
  3. 2while i < |a| and a[i] = b[i] do i ← i + 1
  4. 3return the first i + 1 characters of b
  5. SEARCH(T, k)
  6. 4v ← the root of T
  7. 5while v is not a leaf do
  8. 6j ← the number of stored separators of v that are ≤ k without p(v)
  9. 7v ← child j of v
  10. 8return whether k without p(v) is a stored key of v
  11. SPLIT-LEAF(v) ▷ v has keys k_0 < ... < k_(n-1), one too many
  12. 9c ← ⌊(n + 1) / 2⌋
  13. 10j ← the index in [c - d, c + d] with the shortest SHORTEST-SEPARATOR(k_(j-1), k_j), ties to the one nearest c
  14. 11s ← SHORTEST-SEPARATOR(k_(j-1), k_j)
  15. 12left ← k_0 .. k_(j-1); right ← k_j .. k_(n-1)
  16. 13insert s and a pointer to right into the parent of v, just after the pointer to v
  17. 14store the keys of left and right without the prefixes of their new fences

Line L3 is well defined. If aa is a prefix of bb, the loop stops at i=∣a∣<∣b∣i = |a| < |b|. Otherwise it stops at the first position where aa and bb differ, and there a[i]<b[i]a[i] < b[i].

Line L6 strips p(v)p(v) from kk. This is safe because the search only enters vv when low(v)≤k<high(v)low(v) \le k < high(v), and then kk starts with p(v)p(v).

insert finds the leaf with SEARCH, adds the key, and calls SPLIT-LEAF when the leaf overflows. An inner node that overflows moves one of its separators up to its parent, again chosen within dd positions of the middle so that the shortest one moves up. A full root splits into a new root with one separator. range walks the leaves whose fence interval meets [lo,hi][lo, hi].

Example

Insert ten names in this order into a tree with at most 4 entries per node and a split interval with d=1d = 1: Smith, Smithers, Smithson, Smythe, Smyth, Snow, Sato, Sanders, Smit, Smart. In the trace, a leaf is written as [prefix | stored keys].

  1. The fifth insert overflows the leaf Smith, Smithers, Smithson, Smyth, Smythe. Here c=3c = 3, and the three candidates are j=2j = 2 with separator "Smiths", j=3j = 3 with "Smy", and j=4j = 4 with "Smythe". The shortest is "Smy". The root becomes {Smy}, and the leaves are [ | Smith Smithers Smithson] and [ | Smyth Smythe].
  2. Snow and Sato go into the two leaves. Sanders then overflows the left leaf Sanders, Sato, Smith, Smithers, Smithson. The candidates are "Sm" (j=2j = 2, between Sato and Smith), "Smithe" (j=3j = 3) and "Smiths" (j=4j = 4), so the split takes "Sm" and leaves two keys on the left.
  3. The middle leaf now has the fences "Sm" and "Smy", which share the prefix "Sm", so it stores [Sm | ith ithers ithson]. Smit goes into it. Smart then overflows it with the keys Smart, Smit, Smith, Smithers, Smithson. The candidates are "Smith" (j=2j = 2, between Smit and Smith), "Smithe" (j=3j = 3) and "Smiths" (j=4j = 4). The split takes "Smith", and the new leaf with the fences "Sm" and "Smith" stores [Sm | art it]. The shorter separator "Smi", between Smart and Smit, is at j=1j = 1, outside the split interval, so it is not a choice.

The final tree from the code is:

node fences stored prefix stored entries
root open none Sm, Smith, Smy
leaf 1 open to Sm none Sanders, Sato
leaf 2 Sm to Smith Sm art, it
leaf 3 Smith to Smy Sm ith, ithers, ithson
leaf 4 Smy to open none Smyth, Smythe, Snow

The separators take 10 characters. With d=0d = 0 the same inserts give the separators Smi, Smithe and Smy, 12 characters, and two leaves store the prefixes "Smi" and "Sm". On a larger run, 200 random keys of the form "customer-" followed by up to 5 letters (seed 7, at most 4 entries per node) give 143 distinct keys. The inner nodes then store 183 characters of separators instead of 525 characters for the same separators written in full, and 244 instead of 565 with d=0d = 0.

Correctness

The proofs are in proofs/correctness.md. They rest on three facts.

  • Shortest separator. For a<ba < b, the string ss of L3 satisfies a<s≤ba < s \le b, and no shorter string does. Let tt have ∣t∣≤i|t| \le i and t≤bt \le b. If tt is a prefix of bb, it is a prefix of aa too, because the first ii characters agree, so t≤at \le a. Otherwise tt first differs from bb at a position j<ij < i with t[j]<b[j]=a[j]t[j] < b[j] = a[j], so t<at < a.
  • Prefix of an interval. If low≤k<highlow \le k < high and pp is the longest common prefix of lowlow and highhigh, then kk starts with pp. So stripping pp loses nothing, and the order of the stored suffixes in vv is the order of the full keys.
  • Fence invariant. Every insert and split keeps low(v)≤k<high(v)low(v) \le k < high(v) for every key in the subtree of vv. Then SEARCH visits the only leaf that can hold kk, exactly as in a B+ tree.
Proof: Shortest separators and stored prefixes keep the prefix B-tree a correct B+ treefull

Strings are compared in lexicographic order: t<ut < u if tt is a proper prefix of uu, or if at the first position jj where they differ, t[j]<u[j]t[j] < u[j]. We use the notation of the page: a node vv has fences low(v)low(v) and high(v)high(v) (either may be open), p(v)p(v) is the longest common prefix of the two fences (empty if one is open), and an inner node with children c0,…,cmc_0, \ldots, c_m has separators s1<⋯<sms_1 < \cdots < s_m.

Lemma 1 (shortest separator). Let a<ba < b and let ss be the result of SHORTEST-SEPARATOR(a,b)(a, b). Then a<s≤ba < s \le b, and every string tt with a<t≤ba < t \le b has ∣t∣≥∣s∣|t| \ge |s|.

Proof. Let ii be the value at which the loop of L2 stops. Then a[0..i−1]=b[0..i−1]a[0..i-1] = b[0..i-1]. Since a<ba < b, either aa is a proper prefix of bb, and then i=∣a∣<∣b∣i = |a| < |b|, or i<∣a∣i < |a| and a[i]<b[i]a[i] < b[i], because ii is the first difference and a<ba < b. In both cases bb has a character at position ii, so s=b[0..i]s = b[0..i] has length i+1i + 1.

s≤bs \le b because ss is a prefix of bb. For a<sa < s: in the first case a=s[0..i−1]a = s[0..i-1] is a proper prefix of ss; in the second case ss and aa agree before ii and a[i]<b[i]=s[i]a[i] < b[i] = s[i].

Now let ∣t∣≤i|t| \le i and t≤bt \le b. If tt is a prefix of bb, then t=b[0..∣t∣−1]=a[0..∣t∣−1]t = b[0..|t|-1] = a[0..|t|-1] is a prefix of aa, so t≤at \le a. Otherwise tt is not a prefix of bb and t≤bt \le b, so at the first position jj where tt and bb differ, j<∣t∣≤ij < |t| \le i and t[j]<b[j]=a[j]t[j] < b[j] = a[j], so t<at < a. In both cases tt is not in (a,b](a, b]. □\square

Lemma 2 (prefix of an interval). Let low<highlow < high, let pp be their longest common prefix, and let low≤k<highlow \le k < high. Then kk starts with pp. If kk and k′k' both lie in [low,high)[low, high) and k=pxk = p x, k′=px′k' = p x', then k<k′k < k' if and only if x<x′x < x'.

Proof. Suppose kk does not start with pp. If kk is a proper prefix of pp, then kk is a proper prefix of lowlow, so k<lowk < low, which is false. Otherwise kk first differs from pp at some j<∣p∣j < |p|. If k[j]<p[j]=low[j]k[j] < p[j] = low[j], then k<lowk < low. If k[j]>p[j]=high[j]k[j] > p[j] = high[j], then k>highk > high. Both are false. The second claim holds because removing a common prefix from two strings does not change their order. □\square

If a fence is open, pp is empty and both claims hold trivially.

Invariant. (I1) The tree is a B+ tree: every leaf has the same depth, and an inner node with mm separators has m+1m + 1 children. (I2) The root has open fences, and child cic_i of an inner node vv has the fences sis_i and si+1s_{i+1}, where s0=low(v)s_0 = low(v) and sm+1=high(v)s_{m+1} = high(v). (I3) Every key in the subtree of vv, and every separator stored in vv, lies in [low(v),high(v))[low(v), high(v)), and vv stores each of them without the prefix p(v)p(v), in increasing order.

By Lemma 2, (I3) is well defined: each stored item starts with p(v)p(v), and the stored suffixes are in the same order as the full strings.

Claim 1 (SEARCH). If the invariant holds, SEARCH(T,k)(T, k) returns true if and only if kk is a key of TT.

Proof. We show that SEARCH visits a node vv with low(v)≤k<high(v)low(v) \le k < high(v) at each level. This holds for the root. At an inner node vv, by Lemma 2 the suffix test at L6 counts exactly the separators si≤ks_i \le k. So jj is the index with sj≤k<sj+1s_j \le k < s_{j+1} (with the conventions of I2), which by (I2) means low(cj)≤k<high(cj)low(c_j) \le k < high(c_j). By (I3) for the siblings, any key equal to kk can only be in the subtree of cjc_j, because the fence intervals of the children are disjoint. At the leaf, L8 compares the suffix of kk with the stored suffixes, which by Lemma 2 is the same as comparing full keys. □\square

Claim 2 (insert keeps the invariant). Adding a key to the leaf that SEARCH reaches keeps (I3), since that leaf's interval contains the key. Consider SPLIT-LEAF on a leaf vv with keys k0<⋯<kn−1k_0 < \cdots < k_{n-1} in [low(v),high(v))[low(v), high(v)), and the split point jj with 1≤j≤n−11 \le j \le n - 1. By Lemma 1, $s = $ SHORTEST-SEPARATOR(kj−1,kj)(k_{j-1}, k_j) satisfies kj−1<s≤kjk_{j-1} < s \le k_j. So every key of the left part lies in [low(v),s)[low(v), s) and every key of the right part lies in [s,high(v))[s, high(v)). Also low(v)≤k0≤kj−1<slow(v) \le k_0 \le k_{j-1} < s and s≤kj<high(v)s \le k_j < high(v), so ss lies strictly inside the old interval, and inserting it into the parent just after the pointer to vv keeps the separators of the parent sorted. The new fences of the two leaves are exactly [low(v),s)[low(v), s) and [s,high(v))[s, high(v)), as (I2) demands, and L14 stores their keys without the new prefixes, as (I3) demands.

An inner node vv with separators s1<⋯<sms_1 < \cdots < s_m that overflows moves one separator sts_t up. The left node keeps c0,…,ct−1c_0, \ldots, c_{t-1} and s1,…,st−1s_1, \ldots, s_{t-1} with the fences low(v)low(v) and sts_t; the right node keeps ct,…,cmc_t, \ldots, c_m and st+1,…,sms_{t+1}, \ldots, s_m with the fences sts_t and high(v)high(v). Every child keeps its old fences, so (I2) and (I3) hold below, and each of the two nodes stores its separators again without its new prefix. A root split makes a new root with open fences and the single separator, which keeps (I1) because both halves have the same height. □\square

By Claims 1 and 2, after any sequence of inserts, contains answers correctly, and the leaves read from left to right give all keys in increasing order, which is what range uses. The choice of jj inside the split interval does not affect correctness, only the length of ss: by Lemma 1 the separator at each candidate point is as short as any separator at that point can be.

The tests check Lemma 1 against all strings of length at most 4 over a three-letter alphabet, Lemma 2 against all strings of length at most 4 over two letters, and the invariant, contains, the key order and range against a Python set after random inserts.

Complexity

Costs are in the page I/O model: one node is one page, and a page read is one I/O. In the external memory model, the memory holds M/B blocks; this page counts page reads only and does not use a buffer size.

  • Search reads one page per level, O(log⁡fn)O(\log_f n) pages, where ff is the number of separators that fit in an inner page. In memory it does a binary search per node with O(L)O(L) characters per comparison, O(Llog⁡n)O(L \log n) in all, plus O(L)O(L) per level to strip and add back the prefix.
  • Insert costs one search, plus a split at each level in the worst case. The split interval adds O(dL)O(d L) work per split to compare the candidate separators.
  • Space is at most that of the plain B+ tree on the same keys, and usually much less in the inner levels.
  • Fan-out. If separators shrink from an average of LL to ℓ\ell characters and a pointer takes qq bytes, the fan-out grows by about (L+q)/(ℓ+q)(L + q) / (\ell + q). The height is ⌈log⁡fn⌉\lceil \log_f n \rceil and drops by one level only when ff grows enough; the gain in height is a measured effect that depends on the keys, not a guarantee.

Variants

  • Simple prefix B-tree. Shortest separators and the split interval, but every key stored in full. Most of the gain is in the inner levels.
  • Prefix truncation in leaves. Many systems store the prefix shared by the fences of a leaf once and remove it from every key of the leaf, as on this page. Graefe (2011) describes this with fence keys kept in each node.
  • Front coding inside a page. Each key stores only how many characters it shares with the key before it, as in front coding. This compresses more but needs a sequential decode, so binary search in the page becomes harder.
  • Normalized keys. Multi-column keys are first mapped to one byte string whose order is the order of the columns, so that the string methods of this page apply to any key type.
  • Tries. A trie or an adaptive radix tree stores each shared prefix once for all keys, not once per node, and has no separators at all, at the cost of a less regular page layout.

When to use it

Use it for B+ trees on long string keys that share prefixes, such as URLs, file paths, names and composite keys. Most disk-based database systems use some of these ideas in their B-tree code. For short fixed-size integer keys the gain is small, because a separator cannot be shorter than one byte of difference.

Pitfalls

  • Wrong separator convention. The shortest separator must respect the rule used by the search. With "left < s ≤ right", the separator is a prefix of the first key on the right. A search that treats an equal key as belonging to the left goes wrong.
  • Choosing a separator from a deleted key. A separator does not need to be a key of the tree. Code that assumes it is, for example to find "the key equal to the separator", breaks after deletes.
  • Prefixes after a split. A split changes the fences of the two new nodes, so their prefixes can change. Every stored key must be stored again with the new prefix, as L14 does.
  • Too wide a split interval. A large dd gives very uneven splits and lowers the fill of the pages. Keep dd small against the number of entries in a node.
  • Fan-out in entries. If the page capacity is a count of entries, short separators save nothing. The gain comes only when a page holds as many entries as fit in its bytes.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

prefix_b_tree.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/prefix-b-tree/. The authors are listed in prov/AJZDXP.jsonl.

"""Prefix B-tree (Bayer and Unterauer 1977) on string keys.

A B+ tree: the keys are in the leaves, and the inner nodes hold separators.
A separator s between a left node and a right node satisfies
left keys < s <= right keys. Two ideas of the paper are used:

* simple prefix B-tree: a leaf split puts the shortest separator between the
  two halves into the parent, and the split point is chosen inside a split
  interval of 2 d + 1 positions so that this separator is short;
* prefix B-tree: every key in a node lies between the two fences of the node
  (the separators that bound it in its parent, or the fences of the parent),
  so all keys of the node start with the common prefix of the fences. The
  node stores its keys and separators without that prefix.

Capacity is counted in entries to keep the code short; real systems count
bytes, which is where short separators pay off.
"""

from bisect import bisect_left, bisect_right, insort
from typing import Iterator, List, Optional, Tuple


def shortest_separator(a: str, b: str) -> str:
    """SHORTEST-SEPARATOR: the shortest s with a < s <= b, for a < b."""
    if not a < b:
        raise ValueError("need a < b")
    i = 0                                                    # @line L1
    while i < len(a) and a[i] == b[i]:                       # @line L2
        i += 1                                               # @line L2
    return b[: i + 1]                                        # @line L3


def common_prefix(low: Optional[str], high: Optional[str]) -> str:
    """The prefix that every key in [low, high) has. An open end gives ''."""
    if low is None or high is None:
        return ""
    i = 0
    while i < len(low) and i < len(high) and low[i] == high[i]:
        i += 1
    return low[:i]


class Node:
    """A node with fences [low, high). keys holds suffixes after the prefix.

    In a leaf, keys are the stored keys. In an inner node, keys are the
    separators, and len(children) == len(keys) + 1.
    """

    def __init__(self, leaf: bool, low: Optional[str], high: Optional[str]):
        self.leaf = leaf
        self.low = low
        self.high = high
        self.prefix = common_prefix(low, high)
        self.keys: List[str] = []
        self.children: List["Node"] = []

    def full_keys(self) -> List[str]:
        return [self.prefix + s for s in self.keys]

    def set_fences(self, low: Optional[str], high: Optional[str]) -> None:
        """Change the fences and store the keys again without the new prefix."""
        full = self.full_keys()
        self.low, self.high = low, high
        self.prefix = common_prefix(low, high)
        self.keys = [k[len(self.prefix):] for k in full]


class PrefixBTree:
    def __init__(self, capacity: int = 4, d: int = 1):
        """capacity: the largest number of keys or separators in a node.

        d: the half width of the split interval (d = 0 splits in the middle).
        """
        if capacity < 3:
            raise ValueError("capacity must be at least 3")
        self.capacity = capacity
        self.d = d
        self.root = Node(True, None, None)

    # ----- search -----

    def _child_index(self, v: Node, k: str) -> int:
        # k lies in [v.low, v.high), so it starts with v.prefix.
        return bisect_right(v.keys, k[len(v.prefix):])      # @line L6

    def _leaf_for(self, k: str) -> Tuple[Node, List[Tuple[Node, int]]]:
        v = self.root                                        # @line L4
        path = []
        while not v.leaf:                                    # @line L5
            j = self._child_index(v, k)                      # @line L6
            path.append((v, j))
            v = v.children[j]                                # @line L7
        return v, path

    def contains(self, k: str) -> bool:
        """SEARCH."""
        v, _ = self._leaf_for(k)
        s = k[len(v.prefix):]
        i = bisect_left(v.keys, s)
        return i < len(v.keys) and v.keys[i] == s            # @line L8

    # ----- insert -----

    def insert(self, k: str) -> bool:
        """Insert k; return False if it was already there."""
        if not isinstance(k, str):
            raise TypeError("keys are strings")
        v, path = self._leaf_for(k)
        s = k[len(v.prefix):]
        i = bisect_left(v.keys, s)
        if i < len(v.keys) and v.keys[i] == s:
            return False
        v.keys.insert(i, s)
        while len(v.keys) > self.capacity:
            parent = path.pop()[0] if path else None
            if v.leaf:
                sep, right = self._split_leaf(v)
            else:
                sep, right = self._split_inner(v)
            if parent is None:
                root = Node(False, None, None)
                root.keys = [sep]
                root.children = [v, right]
                self.root = root
                break
            j = parent.children.index(v)
            parent.keys.insert(j, sep[len(parent.prefix):])  # @line L13
            parent.children.insert(j + 1, right)            # @line L13
            v = parent
        return True

    def _choose(self, n: int, sep_of) -> int:
        """The split index j in the split interval with the shortest separator."""
        c = (n + 1) // 2                                     # @line L9
        lo, hi = max(1, c - self.d), min(n - 1, c + self.d)
        best = None
        for j in range(lo, hi + 1):                          # @line L10
            key = (len(sep_of(j)), abs(j - c), j)
            if best is None or key < best:
                best = key
        return best[2]

    def _split_leaf(self, v: Node) -> Tuple[str, Node]:
        full = v.full_keys()
        n = len(full)
        j = self._choose(n, lambda t: shortest_separator(full[t - 1], full[t]))  # @line L10
        sep = shortest_separator(full[j - 1], full[j])       # @line L11
        right = Node(True, sep, v.high)                      # @line L12
        right.keys = [x[len(right.prefix):] for x in full[j:]]  # @line L14
        v.keys = [x[len(v.prefix):] for x in full[:j]]       # @line L12
        v.set_fences(v.low, sep)                             # @line L14
        return sep, right

    def _split_inner(self, v: Node) -> Tuple[str, Node]:
        full = v.full_keys()
        n = len(full)
        # Separator t moves up; the left node keeps full[:t] and the right full[t+1:].
        t = self._choose(n - 1, lambda u: full[u]) if n > 2 else 1
        sep = full[t]
        right = Node(False, sep, v.high)
        right.keys = [x[len(right.prefix):] for x in full[t + 1:]]
        right.children = v.children[t + 1:]
        v.keys = [x[len(v.prefix):] for x in full[:t]]
        v.children = v.children[: t + 1]
        v.set_fences(v.low, sep)
        self._refence(v)
        self._refence(right)
        return sep, right

    def _refence(self, v: Node) -> None:
        """Give each child of v the fences that v now implies."""
        bounds = [v.low] + v.full_keys() + [v.high]
        for i, c in enumerate(v.children):
            c.set_fences(bounds[i], bounds[i + 1])

    # ----- scans and checks -----

    def range(self, lo: str, hi: str) -> List[str]:
        """All keys k with lo <= k <= hi, in order."""
        out: List[str] = []
        self._collect(self.root, lo, hi, out)
        return out

    def _collect(self, v: Node, lo: str, hi: str, out: List[str]) -> None:
        if v.high is not None and v.high <= lo:
            return
        if v.low is not None and v.low > hi:
            return
        if v.leaf:
            out.extend(k for k in v.full_keys() if lo <= k <= hi)
            return
        for c in v.children:
            self._collect(c, lo, hi, out)

    def keys(self) -> List[str]:
        out: List[str] = []
        self._all(self.root, out)
        return out

    def _all(self, v: Node, out: List[str]) -> None:
        if v.leaf:
            out.extend(v.full_keys())
        else:
            for c in v.children:
                self._all(c, out)

    def height(self) -> int:
        h, v = 1, self.root
        while not v.leaf:
            h, v = h + 1, v.children[0]
        return h

    def stored_chars(self) -> Tuple[int, int]:
        """(characters of separators as stored, characters of the full separators)."""
        stored = full = 0
        stack = [self.root]
        while stack:
            v = stack.pop()
            if not v.leaf:
                stored += sum(len(s) for s in v.keys)
                full += sum(len(s) for s in v.full_keys())
                stack.extend(v.children)
        return stored, full

    def check(self) -> None:
        """Raise AssertionError if an invariant of the page fails."""
        depths = set()
        self._check(self.root, None, None, 1, depths)
        assert len(depths) == 1, "leaves at different depths"

    def _check(self, v: Node, low, high, depth, depths) -> None:
        assert v.low == low and v.high == high, "wrong fences"
        assert v.prefix == common_prefix(low, high)
        full = v.full_keys()
        assert full == sorted(full) and len(set(full)) == len(full)
        assert len(full) <= self.capacity
        for k in full:
            assert low is None or low <= k
            assert high is None or k < high
        if v.leaf:
            depths.add(depth)
            return
        assert len(v.children) == len(v.keys) + 1
        bounds = [low] + full + [high]
        for i, c in enumerate(v.children):
            self._check(c, bounds[i], bounds[i + 1], depth + 1, depths)
test_prefix_b_tree.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/prefix-b-tree/. The authors are listed in prov/AJZDXP.jsonl.

import itertools
import random
import unittest

from prefix_b_tree import PrefixBTree, common_prefix, shortest_separator


def all_strings(alphabet, max_len):
    out = [""]
    for n in range(1, max_len + 1):
        out.extend("".join(t) for t in itertools.product(alphabet, repeat=n))
    return out


def random_key(rng, alphabet="abc", max_len=6):
    return "".join(rng.choice(alphabet) for _ in range(rng.randint(1, max_len)))


class TestShortestSeparator(unittest.TestCase):
    def test_against_brute_force(self):
        strings = sorted(set(all_strings("abc", 3)))
        candidates = all_strings("abc", 4)
        for a in strings:
            for b in strings:
                if not a < b:
                    continue
                s = shortest_separator(a, b)
                self.assertTrue(a < s <= b)
                best = min(len(t) for t in candidates if a < t <= b)
                self.assertEqual(len(s), best)

    def test_examples(self):
        self.assertEqual(shortest_separator("Smith", "Smyth"), "Smy")
        self.assertEqual(shortest_separator("cat", "catalog"), "cata")
        self.assertEqual(shortest_separator("apple", "banana"), "b")
        with self.assertRaises(ValueError):
            shortest_separator("b", "a")

    def test_common_prefix_is_shared_by_the_interval(self):
        strings = all_strings("ab", 4)
        for low in strings:
            for high in strings:
                if not low < high:
                    continue
                p = common_prefix(low, high)
                for k in strings:
                    if low <= k < high:
                        self.assertTrue(k.startswith(p))


class TestPrefixBTree(unittest.TestCase):
    def test_against_a_sorted_set(self):
        for seed in range(12):
            rng = random.Random(seed)
            t = PrefixBTree(capacity=rng.choice([3, 4, 5, 8]), d=rng.choice([0, 1, 2]))
            ref = set()
            for _ in range(rng.randint(1, 200)):
                k = random_key(rng)
                self.assertEqual(t.insert(k), k not in ref)
                ref.add(k)
            t.check()
            self.assertEqual(t.keys(), sorted(ref))
            for _ in range(60):
                k = random_key(rng)
                self.assertEqual(t.contains(k), k in ref)
            for _ in range(30):
                lo, hi = sorted([random_key(rng), random_key(rng)])
                self.assertEqual(t.range(lo, hi), sorted(x for x in ref if lo <= x <= hi))

    def test_sorted_and_reverse_inserts(self):
        keys = sorted(set(all_strings("abcd", 3)) - {""})
        for order in (keys, keys[::-1]):
            t = PrefixBTree(capacity=4, d=1)
            for k in order:
                t.insert(k)
            t.check()
            self.assertEqual(t.keys(), keys)
            self.assertTrue(all(t.contains(k) for k in keys))
            self.assertFalse(t.contains("e"))

    def test_prefix_truncation_saves_characters(self):
        rng = random.Random(7)
        t = PrefixBTree(capacity=4, d=1)
        for _ in range(200):
            t.insert("customer-" + random_key(rng, "abcdef", 5))
        t.check()
        stored, full = t.stored_chars()
        self.assertLess(stored, full)

    def test_split_interval_shortens_separators(self):
        keys = ["aaaa", "aaab", "aaac", "aaad", "b"]
        mid = PrefixBTree(capacity=4, d=0)
        wide = PrefixBTree(capacity=4, d=1)
        for k in keys:
            mid.insert(k)
            wide.insert(k)
        self.assertEqual(mid.root.full_keys(), ["aaad"])
        self.assertEqual(wide.root.full_keys(), ["b"])
        mid.check()
        wide.check()

    def test_hand_cases(self):
        t = PrefixBTree(capacity=3)
        self.assertFalse(t.contains("a"))
        self.assertEqual(t.range("a", "z"), [])
        self.assertTrue(t.insert("a"))
        self.assertFalse(t.insert("a"))
        with self.assertRaises(TypeError):
            t.insert(3)
        with self.assertRaises(ValueError):
            PrefixBTree(capacity=2)


if __name__ == "__main__":
    unittest.main()

History

Rudolf Bayer and Karl Unterauer at the Technical University of Munich published "Prefix B-trees" in ACM Transactions on Database Systems in March 1977, after an IBM research report of 1976. They described the simple prefix B-tree, with short separators in the index part, and the prefix B-tree, in which the prefixes are not stored but rebuilt as the tree is searched. Graefe's survey of 2011 describes how these ideas, together with fence keys and normalized keys, are used in current B-tree code.

References

  1. Rudolf Bayer and Karl Unterauer, Prefix B-trees, ACM Transactions on Database Systems 2(1) (1977), pp. 11 to 26, the simple prefix B-tree (shortest separators in the index part, the split interval) and the prefix B-tree (prefixes that are not stored but rebuilt during the search)
  2. Goetz Graefe, Modern B-tree techniques, Foundations and Trends in Databases 3(4) (2011), pp. 203 to 402, the sections on compression of keys in B-tree nodes (prefix truncation, shortened separator keys, fence keys); section level only

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of io.average
  • a full proof of io.best
  • a full proof of io.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources