Data structureresearch
Bw-tree
Also called latch-free B-tree with delta records.
A latch-free B+ tree that changes pages by prepending delta records and installs them with compare-and-swap on a mapping table.
- Time
- O(h (c + log B)) worst · averageO(h) best
- Space
- O(n) extra
- Where
- B = the largest number of entries in a page; c = the largest length of a delta chain; h = the height of the tree; n = the number of keys
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Justin J. Levandoski, David B. Lomet, Sudipta Sengupta, 2013
The Bw-tree is a B+ tree in which no thread ever takes a latch. Pages do not refer to each other by memory addresses but by page ids, and a mapping table maps each page id to the current address of the page. A thread never changes a page in place. It makes a small delta record that describes the change, points it at the current page, and installs it with one compare-and-swap on the slot of the page in the mapping table. Long chains of deltas are later merged into a new page, and splits are done in two steps, each one compare-and-swap, in the style of the B-link tree. The operations are linearizable and the structure is lock-free (a theorem, under the invariant of the proof); its speed is a measurement.
In plain words
Think of a shared notebook in which nobody may erase anything. To change an entry, you write the change on a sticky note, stick it on top of the page, and point the table of contents at your note. If somebody else changed that entry of the table while you wrote, your change fails and you try again. A reader reads the notes first, newest first, and then the page under them.
When a page has too many notes, somebody copies it out clean and points the table at the copy. When a page gets too full, somebody moves its upper half to a new page and puts a note "the keys from 35 on are now on page 3" on the old page. Anybody who sees that note can later add the new page to the index above.
The abstract type
A map from ordered keys to values, used by many threads at the same time:
lookup(k): the value of , or nothing.upsert(k, v): insert with , or replace its value.delete(k).- Range scans along the leaf level.
Each operation is linearizable: it acts as if it took place at one instant between its start and its end.
Representation
- Mapping table. An array from page ids (pids) to the head of a page. Every change of the tree is a compare-and-swap (CAS) on one slot of . A page that is not yet reachable can be set up without a CAS.
- Base page. A sorted array of entries, as in a B+ tree, with a range and the pid of its right sibling. A leaf holds keys and values; an inner page holds separator keys and child pids.
- Delta records. A delta points to the previous head of the same page. A leaf has insert and delete deltas. A split delta says that the keys from on are now in page , and so sets and the right link to . An index term delta on an inner page adds a child.
- Chain. The head of a page is a chain of zero or more deltas in front of one base page. The newest delta comes first.
Because pages refer to each other by pid, a change of one page never needs to update a pointer in another page. This is what lets one CAS install it, and it also lets the store move a page to flash and back without changing its parent.
Operations
UPDATE(k, kind, v) ▷ upsert or delete- 1
repeat (pid, parent, h) ← FIND(k, 0) - 2
(found, old) ← search the chain h for k: the newest delta on k decides, else a binary search of the base page - 3
if kind = delete and not found then return nothing - 4
d ← a new delta (kind, k, v) whose next pointer is h - 5
until CAS(M[pid], h, d) - 6
if the chain of pid is longer than max_chain then CONSOLIDATE(pid) - 7
if the page of pid holds more than max_page entries then SPLIT(pid, parent); return old
FIND(k, level)- 1
pid ← root; parent ← nothing - 2
loop h ← M[pid] - 3
(low, high, right) ← the bounds of h (from the newest split delta, else the base page); if k ≥ high then - 4
if the walk came down to pid then HELP-ALONG(parent, high, right); pid ← right; continue - 5
if the level of h is level then return (pid, parent, h) - 6
parent ← pid; pid ← the child for k in h (the index term deltas first, then the base page)
CONSOLIDATE(pid)- 1
h ← M[pid]; b ← a new base page with the content of h - 2
CAS(M[pid], h, b) ▷ if it fails, another thread changed the page; keep the new head SPLIT(pid, parent)- 3
h ← M[pid]; sep ← the middle key of h; Q ← a new pid with the entries ≥ sep, the range [sep, high) and the right link of h - 4
if not CAS(M[pid], h, a split delta (sep, Q) on h) then return - 5
HELP-ALONG(parent, sep, Q) HELP-ALONG(parent, sep, q)- 6
loop g ← M[parent]; if g is not one level above q, or sep is not in its range, or g already routes sep to q, then return - 7
if CAS(M[parent], g, an index term delta (sep → q) on g) then return
- Lookup is FIND followed by the search of L2.
- Root split. The root has no parent, so its split makes two new pages from its content and replaces the root head by a new inner base page one level up, in one CAS.
- Retry. A failed CAS at L5 means that another thread changed the page; the operation starts again at L1. A failed CAS at L15 or L17 is not retried by the code on this page: the other thread's change wins, and the next update of the page checks again.
- Help along. A thread that reaches a page by its parent and must follow a right link has found a split whose index term is missing, and it posts the term (L11). So a thread that stops after L17 never blocks the others.
- Merges are also in the paper, in three steps (a remove node delta, a merge delta on the left sibling and an index term delete delta on the parent). The code on this page does not merge pages.
Example
The tree has max_page = 4 and max_chain = 3, and starts as one empty leaf, pid 0, the root. These are the upserts of 10, 20, 30, 40, 25, 35 and 45, one thread, as the code on this page runs them.
- 10, 20, 30. Each one is an insert delta on pid 0. The chain is now ins 30, ins 20, ins 10, then the empty base page.
- 40. The fourth delta makes the chain longer than 3, so the page is consolidated: one CAS installs the base page [10, 20, 30, 40].
- 25. Now pid 0 has 5 entries. It is the root, so the root splits at the middle key 25: pid 1 gets [25, 30, 40] with the range [25, ∞), pid 2 gets [10, 20] with the range [-∞, 25) and the right link 1, and one CAS makes pid 0 the inner page [-∞ → 2, 25 → 1].
- 35. An insert delta on pid 1.
- 45. A second delta on pid 1, which now has the 5 keys 25, 30, 35, 40 and 45. The split takes the middle key 35, sets up pid 3 as the base page [35, 40, 45] with the range [35, ∞), and puts the split delta (35, 3) on pid 1. The chain of pid 1 is now split 35, ins 45, ins 35, then the base page [25, 30, 40], and its content is [25, 30]. The help-along step puts the index term delta (35 → 3) on the root.
| pid | chain, newest first | content | range |
|---|---|---|---|
| 0 | term (35 → 3), base [-∞ → 2, 25 → 1] | 3 children | [-∞, ∞) |
| 1 | split (35, 3), ins 45, ins 35, base [25, 30, 40] | 25, 30 | [25, 35) |
| 2 | base [10, 20] | 10, 20 | [-∞, 25) |
| 3 | base [35, 40, 45] | 35, 40, 45 | [35, ∞) |
The run made 11 successful CAS operations: 7 deltas, 1 consolidation, 1 root split, 1 split delta and 1 index term. A lookup of 40 now goes from the root to pid 3 directly. Before the index term was posted, it would have gone to pid 1, seen that 40 is at least its new high key 35, and followed the right link to pid 3.
Correctness
The proofs are in proofs/correctness.md. The main points:
- One CAS per change. A CAS on succeeds only if the head is still the one the thread read, so each change is computed from the page as it is at the instant it is installed.
- Invariant. Each level, read along the right links, splits the key space into ranges in order; each inner page routes a key to a child whose low key is at most that key; every key is in the leaf whose range holds it; and a low key never changes while a high key can only fall. Every kind of CAS (delta, consolidation, split delta, index term, root split) keeps this invariant.
- Find. Under the invariant, a walk that follows a right link when the key is at least the high key always reaches the page whose range holds the key, even if a split is half done.
- Linearizability (theorem). An update takes effect at its successful CAS at L5, and a lookup at its read of the leaf head. Splits and consolidations do not change the map.
- Lock-freedom (theorem). A CAS fails only because another CAS on the same slot succeeded, so some operation always makes progress. One operation can retry without bound, so the Bw-tree is not wait-free.
The tests check sequential runs against a dict, concurrent writers with disjoint keys, a split stopped half way, and, by a search over all orders, that every interleaving of three threads with four operations each on 60 seeds is linearizable.
Proof: Each compare-and-swap keeps the Bw-tree a correct B-link structure, so its operations are linearizablefull
We use the notation of the page and the code. The mapping table maps a pid to the head of a chain. The page of a pid is its chain read at one instant. Its bounds are those of the newest split delta in the chain, or of the base page if there is none, and its content is logical(h): the base, with the deltas applied from the oldest to the newest, restricted to . A page is reachable if a walk from the root along child pointers and right links reaches it.
The only writes to shared state are CAS operations on single slots of , and the setup of a new pid before it is reachable. A CAS succeeds only if is still , so the new head is computed from the page as it is at the instant of the CAS. We show that the following invariant holds after every successful CAS. Since it holds for the initial tree (one empty leaf root with the range ), it holds at every instant.
Invariant.
- (B1) The reachable pages of each level, read from the page with along the right links, have the ranges of a partition of , in increasing order. The root is the only page of the top level.
- (B2) For an inner page at level and a key in its range,
inner_routereturns a pid of a page at level whose is at most . - (B3) The key set of the tree is the union of the contents of the reachable leaves, and each key is in the content of the leaf whose range holds it.
- (B4) The of a page never changes after it is reachable, and its never increases.
Lemma 1 (find). If the invariant holds at each instant, _find(k, level) returns a pid and a head such that, at the instant was read, was the head of a reachable page at that level whose range held .
Proof. The walk starts at the root, whose range is . At any page it reads, it holds the property "the page is reachable, at the current level, and ". This holds at the root. If , the walk moves to , whose is by (B1), at the same level, and reachable. If and the level is the wanted one, the walk returns it. If it is higher, by (B2) the child has and is one level down. By (B4), the property "low ≤ k" stays true after the read. By (B1), the pages to the right of a page with include the page whose range holds , and in a finite run there are finitely many pages, so the walk ends.
Lemma 2 (each CAS keeps the invariant).
Insert, update or delete delta (L5). The CAS puts a delta in front of the head of a leaf whose range holds (Lemma 1, and the CAS validates that the page has not changed since). It changes only the state of in the content, and no bounds, so (B1), (B2) and (B4) are kept, and (B3) holds with added or removed.
Consolidation (L15). The new base page is logical(h): the same bounds and the same content. The CAS validates , so nothing changes logically.
Split (L16 and L17). The new page gets the keys of the content of that are , the range and the right link of , and it is not reachable before the CAS. The CAS puts a split delta on , which sets the range of to and its right link to . Because the CAS validates , the content of is exactly the part of the content of in at that instant. So the level now has , and then the old right neighbour, which is (B1). The contents together are unchanged, so (B3) holds. keeps its and its falls, which is (B4). The new page is not the root, and the root never gets a split delta (it splits by a root split), so the top level still has one page.
Index term (L20). The delta adds the entry to a parent at level , with at level (the level check of L19) and . inner_route returns only for , so (B2) holds. No bounds or contents change.
Root split. The CAS replaces the root head by a new base page one level up, with the two entries and . and were built from the content of , with the ranges and and the link , and they were not reachable before. The CAS validates , so their contents are exactly that of the old root. The old top level becomes the level of and , which is (B1). (B2) holds for the new root, and the pages below are unchanged.
Theorem (linearizability). Every operation of the code is linearizable with respect to a map from keys to values.
Proof. Take as the linearization point of an update its successful CAS at L5; of a delete of an absent key, the read of the leaf head that _find returns; and of a lookup, the same read. By Lemma 1, at that instant the head is that of the reachable leaf whose range holds , and by (B3) the state of in its content is the state of in the map. The result of the operation (the old value, or the value found) is computed from that head, so it is the value of at the linearization point. Each linearization point lies between the start and the end of its operation. The changes of structure (consolidation, split, index term, root split) do not change the map, by Lemma 2.
Lock-freedom. A CAS fails only because another CAS on the same pid has succeeded in the meantime. So while some operation retries, others make progress. A single operation can retry without bound, so the structure is lock-free, not wait-free.
Help along. The correctness above does not need the index term of a split to be posted: a search that reaches for a key follows the right link (Lemma 1). Posting it, by the thread that made the split or by any thread that took the side link, only makes later searches shorter.
The tests compare sequential runs with a Python dict, check that every concurrent run of three threads with four operations each on shared keys has a linear order that respects real time and matches a dict (by a search over all orders), check concurrent writers with disjoint keys and readers of fixed keys, and stop a split after its split delta to show that a later reader posts the index term.
Complexity
- Lookup. At each of the levels, a scan of at most deltas and a binary search of a base page of at most entries, so without contention. Right links add steps only while a split is half done.
- Update. A lookup and one CAS. Under contention a CAS can fail and the operation starts again, so there is no bound on the time of one operation, only on the progress of the system.
- Consolidation costs with a merge of the deltas into the base page (the code on this page sorts, which costs a log factor more). It happens once per updates of a page, so its amortized cost per update is .
- Space. : the base pages, at most deltas per page, and one mapping table slot per page. Old chains must be kept until no thread can still read them, which the paper does with epochs.
Variants
- LLAMA. The authors' store under the Bw-tree. It writes pages and deltas to a log-structured store on flash and can keep a page on flash while its pid stays the same.
- OpenBw-Tree. The open version of Wang et al. (2018), which adds pre-allocated delta space in each page, faster consolidation, a different garbage collection and other changes to the original design.
- B-link tree. The same right links and the same two-step split, but with latches on the pages instead of a CAS on a mapping table.
- Other designs. In-memory indexes that use optimistic locks, such as the adaptive radix tree with optimistic lock coupling, are not latch-free but avoid the chain walks.
When to use it
The Bw-tree fits an ordered index on a multicore machine where threads must never block each other, and where the pages may live on flash, since the mapping table lets a page move without changes to its parent. Microsoft used it in the Hekaton in-memory engine of SQL Server. It is a research design with many details that the paper does not fix. Wang et al. found that even their optimized version was slower than in-memory indexes with optimistic locks in their tests (a measurement). If latches are acceptable, a B-link tree or a tree with optimistic lock coupling is usually simpler and faster.
Pitfalls
- Memory reclamation. A thread can still be reading a chain after another thread has replaced it. Freeing the old chain at once is a use-after-free. The paper uses epoch-based reclamation; the Python code relies on the garbage collector.
- ABA. If the memory of a freed delta is reused for a new head of the same slot, a late CAS can succeed against the wrong page. Safe reclamation also prevents this ABA problem.
- Help along needs checks. A thread that posts an index term must check that the parent is one level above the new page, that the separator is still in the parent's range, and that the term is not already there (L19). Without these checks, two threads post the same term twice, or a term goes to a parent that has split.
- Long chains. Every lookup walks the chain. If consolidation is late, lookups slow down; if it is too early, it copies pages too often. The limit on chain length is a heuristic, tuned by measurement.
- Lost work. If the CAS of a split delta fails, the new page was set up for nothing and must be freed. If a consolidation CAS fails, the new base page is lost too.
- Merges. Removing a page needs three steps and careful rules for threads that are in the middle of the page being removed. Wang et al. report this as one of the hardest parts to get right.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bw-tree/. The authors are listed in prov/R4MGVH.jsonl.
"""Bw-tree of Levandoski, Lomet and Sengupta (ICDE 2013), as a simulation.
Pages are named by page ids (pids). A mapping table M maps a pid to the head
of a chain: zero or more delta records in front of a base page. Every change
is one compare-and-swap (CAS) on one slot of M, so no thread ever waits.
Threads are Python generators. Each operation reads a chain head, yields to
the scheduler, and then tries its CAS, so other threads can change the page
in between, as on a real machine. A seeded scheduler picks the thread that
runs next. The structure modifications are the two-step split of the paper
(a split delta on the page, then an index term delta on its parent) and
consolidation. Any thread that sees a half-done split helps to finish it.
Not modelled: page merges, the flash log of the LLAMA store and epoch-based
memory reclamation (Python's garbage collector frees unreachable chains).
"""
import math
import random
from bisect import bisect_right
from typing import Dict, Generator, List, Optional, Tuple
NEG, POS = -math.inf, math.inf
# ----- pages and deltas -----
class Base:
"""A base page. In a leaf, vals[i] is the value of keys[i]. In an inner
page, keys[i] is the low key of the child kids[i], and keys[0] == low."""
__slots__ = ("level", "keys", "vals", "kids", "low", "high", "right")
def __init__(self, level, keys, vals_or_kids, low, high, right):
self.level = level
self.keys = keys
self.vals = vals_or_kids if level == 0 else None
self.kids = vals_or_kids if level > 0 else None
self.low, self.high, self.right = low, high, right
class Delta:
__slots__ = ("kind", "key", "val", "nxt", "base", "length")
def __init__(self, kind: str, key, val, nxt):
self.kind = kind # "ins", "del", "split" or "term"
self.key = key # the key, or the separator of a split or an index term
self.val = val # the value, the new pid of a split, or (pid, high) of an index term
self.nxt = nxt
self.base = nxt if isinstance(nxt, Base) else nxt.base
self.length = 1 if isinstance(nxt, Base) else nxt.length + 1
def chain_length(h) -> int:
return 0 if isinstance(h, Base) else h.length
def base_of(h) -> Base:
return h if isinstance(h, Base) else h.base
def bounds(h) -> Tuple[object, object, Optional[int]]:
"""(low, high, right) of the page whose chain starts at h."""
b = base_of(h)
d = h
while isinstance(d, Delta):
if d.kind == "split": # the newest split is the tightest
return b.low, d.key, d.val
d = d.nxt
return b.low, b.high, b.right
def leaf_find(h, k):
"""Search one leaf chain for k: (found, value). Assumes low <= k < high."""
d = h
while isinstance(d, Delta):
if d.key == k and d.kind == "ins":
return True, d.val
if d.key == k and d.kind == "del":
return False, None
d = d.nxt
i = bisect_right(d.keys, k) - 1
if i >= 0 and d.keys[i] == k:
return True, d.vals[i]
return False, None
def inner_route(h, k) -> int:
"""The child pid for k in one inner chain. Assumes low <= k < high."""
d = h
while isinstance(d, Delta):
if d.kind == "term":
q, hi = d.val
if d.key <= k < hi:
return q
d = d.nxt
return d.kids[bisect_right(d.keys, k) - 1]
def logical(h) -> Tuple[Base, List, List]:
"""The contents of a chain as sorted keys and values (or kids)."""
b = base_of(h)
low, high, right = bounds(h)
deltas = []
d = h
while isinstance(d, Delta):
deltas.append(d)
d = d.nxt
if b.level == 0:
content = dict(zip(b.keys, b.vals))
for d in reversed(deltas):
if d.kind == "ins":
content[d.key] = d.val
elif d.kind == "del":
content.pop(d.key, None)
else:
content = dict(zip(b.keys, b.kids))
for d in reversed(deltas):
if d.kind == "term":
content[d.key] = d.val[0]
keys = sorted(x for x in content if low <= x < high)
return Base(b.level, keys, [content[x] for x in keys], low, high, right), keys, [content[x] for x in keys]
# ----- the tree -----
ROOT = 0
class BwTree:
def __init__(self, max_leaf: int = 4, max_inner: int = 4, max_chain: int = 3):
self.M: Dict[int, object] = {ROOT: Base(0, [], [], NEG, POS, None)}
self.next_pid = 1
self.max_leaf, self.max_inner, self.max_chain = max_leaf, max_inner, max_chain
self.stats = {"cas_ok": 0, "cas_fail": 0, "help": 0, "split": 0, "consolidate": 0, "root_split": 0}
def cas(self, pid: int, expected, new) -> bool:
if self.M[pid] is expected:
self.M[pid] = new
self.stats["cas_ok"] += 1
return True
self.stats["cas_fail"] += 1
return False
def new_pid(self, page) -> int:
pid = self.next_pid
self.next_pid += 1
self.M[pid] = page # not reachable yet, so no CAS is needed
return pid
# ----- traversal -----
def _find(self, k, level: int = 0) -> Generator:
"""Walk from the root to the page at the given level whose range holds k.
Returns (pid, parent pid, head). Helps to post missing index terms."""
pid, parent, came_down = ROOT, None, True # @line L8
while True:
h = self.M[pid] # @line L9
yield "read"
low, high, right = bounds(h) # @line L10
if k >= high: # @line L10
if came_down and parent is not None:
yield from self._help_along(parent, high, right) # @line L11
pid, came_down = right, False # @line L11
continue
b = base_of(h)
if b.level == level: # @line L12
return pid, parent, h # @line L12
parent, pid, came_down = pid, inner_route(h, k), True # @line L13
def _help_along(self, parent: int, sep, q: int) -> Generator:
"""Post the index term (sep -> q) on the parent if it is missing."""
while True:
g = self.M[parent] # @line L19
low, high, _ = bounds(g)
qh = self.M[q]
if base_of(g).level != base_of(qh).level + 1 or not (low <= sep < high):
return # @line L19
if inner_route(g, sep) == q: # @line L19
return
d = Delta("term", sep, (q, bounds(qh)[1]), g)
yield "cas"
self.stats["help"] += 1
if self.cas(parent, g, d): # @line L20
return
# ----- operations (generators) -----
def lookup(self, k) -> Generator:
pid, _, h = yield from self._find(k)
return leaf_find(h, k)[1]
def upsert(self, k, v) -> Generator:
"""Insert or update k; return the old value or None."""
return (yield from self._update(k, "ins", v))
def delete(self, k) -> Generator:
"""Delete k; return the old value or None."""
return (yield from self._update(k, "del", None))
def _update(self, k, kind, v) -> Generator:
while True:
pid, parent, h = yield from self._find(k) # @line L1
found, old = leaf_find(h, k) # @line L2
if kind == "del" and not found: # @line L3
return None # @line L3
d = Delta(kind, k, v, h) # @line L4
yield "cas"
if self.cas(pid, h, d): # @line L5
break
yield from self._maintain(pid, parent) # @line L6
return old
def _maintain(self, pid: int, parent: Optional[int]) -> Generator:
h = self.M[pid]
if chain_length(h) > self.max_chain: # @line L6
yield from self._consolidate(pid)
page, keys, _ = logical(self.M[pid])
limit = self.max_leaf if page.level == 0 else self.max_inner
if len(keys) > limit: # @line L7
ok = yield from self._split(pid, parent)
if ok and parent is not None:
yield from self._maintain_parent(parent)
def _maintain_parent(self, parent: int) -> Generator:
# The parent's own parent is found by a new walk from the root.
g = self.M[parent]
b = base_of(g)
if parent == ROOT:
yield from self._maintain(ROOT, None)
return
lo = bounds(g)[0]
found = yield from self._find(lo, b.level)
if found[0] == parent:
yield from self._maintain(parent, found[1])
def _consolidate(self, pid: int) -> Generator:
h = self.M[pid] # @line L14
page, _, _ = logical(h) # @line L14
yield "cas"
if self.cas(pid, h, page): # @line L15
self.stats["consolidate"] += 1
def _split(self, pid: int, parent: Optional[int]) -> Generator:
h = self.M[pid] # @line L16
page, keys, items = logical(h)
limit = self.max_leaf if page.level == 0 else self.max_inner
if len(keys) <= limit:
return False
mid = len(keys) // 2
sep = keys[mid] # @line L16
if pid == ROOT:
# A root split makes two new pages and swaps the root in one CAS.
r = Base(page.level, keys[mid:], items[mid:], sep, POS, None)
rp = self.new_pid(r)
l = Base(page.level, keys[:mid], items[:mid], NEG, sep, rp)
lp = self.new_pid(l)
root = Base(page.level + 1, [NEG, sep], [lp, rp], NEG, POS, None)
yield "cas"
if self.cas(ROOT, h, root):
self.stats["root_split"] += 1
return True
return False
q = Base(page.level, keys[mid:], items[mid:], sep, page.high, page.right)
qp = self.new_pid(q) # @line L16
d = Delta("split", sep, qp, h)
yield "cas"
if not self.cas(pid, h, d): # @line L17
return False # the new page is dropped
self.stats["split"] += 1
if parent is not None:
yield from self._help_along(parent, sep, qp) # @line L18
return True
# ----- checks (not concurrent) -----
def items(self) -> List[Tuple[object, object]]:
"""All (key, value) pairs, by a walk along the leaf level."""
pid = ROOT
while base_of(self.M[pid]).level > 0:
pid = inner_route(self.M[pid], NEG)
out = []
prev_high = NEG
while pid is not None:
page, keys, vals = logical(self.M[pid])
assert page.low == prev_high, "the leaf level is not contiguous"
out.extend(zip(keys, vals))
prev_high = page.high
pid = page.right
assert prev_high == POS
return out
def height(self) -> int:
return base_of(self.M[ROOT]).level + 1
def run(tree: BwTree, ops, seed: int, log: Optional[list] = None):
"""Run the operations as concurrent threads with a seeded scheduler.
ops is a list of (thread, name, key, value). Each thread runs its ops in
order. Returns the results and, if log is given, fills it with
(thread, name, key, value, result, start step, end step)."""
rng = random.Random(seed)
per_thread: Dict[int, List] = {}
for t, name, k, v in ops:
per_thread.setdefault(t, []).append((name, k, v))
gens: Dict[int, Tuple] = {}
results = []
step = 0
def start(t):
if per_thread[t]:
name, k, v = per_thread[t].pop(0)
g = tree.lookup(k) if name == "lookup" else tree.upsert(k, v) if name == "upsert" else tree.delete(k)
gens[t] = (g, name, k, v, step)
else:
gens.pop(t, None)
for t in list(per_thread):
start(t)
while gens:
t = rng.choice(sorted(gens))
g, name, k, v, s = gens[t]
step += 1
try:
next(g)
except StopIteration as e:
results.append((t, name, k, v, e.value))
if log is not None:
log.append((t, name, k, v, e.value, s, step))
start(t)
return results
def run_one(tree: BwTree, gen):
"""Run one operation alone and return its result."""
while True:
try:
next(gen)
except StopIteration as e:
return e.value
test_bw_tree.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bw-tree/. The authors are listed in prov/R4MGVH.jsonl.
import random
import unittest
from bw_tree import BwTree, Delta, base_of, bounds, chain_length, run, run_one
def apply(state, name, k, v):
"""The sequential reference: a Python dict. Returns (result, new state)."""
old = state.get(k)
if name == "lookup":
return old, state
s = dict(state)
if name == "upsert":
s[k] = v
else:
s.pop(k, None)
return old, s
def linearizable(log, init):
"""Brute force: is there an order of the operations that respects real
time (an operation that ended before another started comes first) and in
which every result matches the dict reference?"""
ops = list(log)
n = len(ops)
def dfs(done, state):
if len(done) == n:
return True
pending = [i for i in range(n) if i not in done]
for i in pending:
t, name, k, v, res, s, e = ops[i]
# i may go next only if no pending operation ended before i started
if any(ops[j][6] < s for j in pending if j != i):
continue
r, s2 = apply(state, name, k, v)
if r == res and dfs(done | {i}, s2):
return True
return False
return dfs(frozenset(), dict(init))
def preload(tree, keys):
for k in keys:
run_one(tree, tree.upsert(k, "v%d" % k))
class TestSequential(unittest.TestCase):
def test_against_a_dict(self):
rng = random.Random(1)
for seed in range(4):
t = BwTree(max_leaf=4, max_inner=4, max_chain=3)
ref = {}
for i in range(400):
k = rng.randrange(150)
r = rng.random()
if r < 0.6:
self.assertEqual(run_one(t, t.upsert(k, i)), ref.get(k))
ref[k] = i
elif r < 0.8:
self.assertEqual(run_one(t, t.delete(k)), ref.pop(k, None))
else:
self.assertEqual(run_one(t, t.lookup(k)), ref.get(k))
self.assertEqual(t.items(), sorted(ref.items()))
self.assertGreaterEqual(t.height(), 3)
self.assertGreater(t.stats["split"], 0)
self.assertGreater(t.stats["consolidate"], 0)
def test_delta_chain_and_consolidation(self):
t = BwTree(max_leaf=8, max_inner=4, max_chain=3)
for k in (5, 1, 9):
run_one(t, t.upsert(k, k))
h = t.M[0]
self.assertEqual(chain_length(h), 3)
self.assertEqual([h.kind, h.key, h.nxt.key, h.nxt.nxt.key], ["ins", 9, 1, 5])
run_one(t, t.delete(1)) # the fourth delta makes the chain too long
h = t.M[0]
self.assertEqual(chain_length(h), 0)
self.assertEqual(h.keys, [5, 9])
class TestConcurrent(unittest.TestCase):
def test_disjoint_writers_and_static_readers(self):
"""Each writer owns its keys; readers look up keys that never change."""
for seed in range(6):
rng = random.Random(seed)
t = BwTree(max_leaf=4, max_inner=4, max_chain=2)
static = list(range(0, 400, 10))
preload(t, static)
ops, final = [], {k: "v%d" % k for k in static}
for w in range(4):
for i in range(60):
k = 10 * rng.randrange(40) + 1 + w # writer w owns the keys that end in w + 1
if rng.random() < 0.75:
ops.append((w, "upsert", k, (w, i)))
final[k] = (w, i)
else:
ops.append((w, "delete", k, None))
final.pop(k, None)
for r in range(4, 6):
for i in range(40):
ops.append((r, "lookup", rng.choice(static), None))
owners = {}
for w, name, k, v in ops:
if name != "lookup":
self.assertEqual(owners.setdefault(k, w), w)
res = run(t, ops, seed)
for th, name, k, v, out in res:
if name == "lookup":
self.assertEqual(out, "v%d" % k)
self.assertEqual(t.items(), sorted(final.items()))
self.assertGreater(t.stats["cas_fail"], 0)
self.assertGreater(t.stats["split"] + t.stats["root_split"], 3)
def test_linearizable_on_shared_keys(self):
fails = 0
for seed in range(60):
rng = random.Random(100 + seed)
t = BwTree(max_leaf=2, max_inner=2, max_chain=1)
init = {k: "init" for k in range(0, 12, 2)}
for k in init:
run_one(t, t.upsert(k, "init"))
t.stats["cas_fail"] = 0
ops = []
for th in range(3):
for i in range(4):
name = rng.choice(["upsert", "upsert", "delete", "lookup"])
ops.append((th, name, rng.randrange(12), (th, i) if name == "upsert" else None))
log = []
run(t, ops, seed, log)
self.assertTrue(linearizable(log, init), log)
fails += t.stats["cas_fail"]
t.items() # the leaf level is still contiguous
self.assertGreater(fails, 0) # the runs did have races
def test_checker_rejects_a_bad_history(self):
# Thread 0 writes 5 and ends; then thread 1 starts and reads nothing.
bad = [(0, "upsert", 5, "a", None, 1, 2), (1, "lookup", 5, None, None, 3, 4)]
self.assertFalse(linearizable(bad, {}))
good = [(0, "upsert", 5, "a", None, 1, 4), (1, "lookup", 5, None, None, 2, 3)]
self.assertTrue(linearizable(good, {}))
def test_half_done_split_is_helped(self):
"""Stop a split after its split delta; a later reader posts the index term."""
t = BwTree(max_leaf=4, max_inner=8, max_chain=10)
ref = {k: "v%d" % k for k in range(0, 50, 5)}
preload(t, ref) # several leaves under one root
self.assertEqual(base_of(t.M[0]).level, 1)
root_before = t.M[0]
g = t.upsert(41, "x")
ref[41] = "x"
# Run the upsert until its split delta is installed, then stop it.
old_heads = {id(h) for h in t.M.values()}
split = None
while split is None:
next(g)
split = next((h for h in t.M.values() if id(h) not in old_heads
and isinstance(h, Delta) and h.kind == "split"), None)
sep = split.key
self.assertIs(t.M[0], root_before) # the parent has no index term yet
helps = t.stats["help"]
# A lookup that needs the new page still finds it by the side link.
self.assertEqual(run_one(t, t.lookup(sep)), ref[sep])
root = t.M[0] # and it posted the index term
self.assertIsInstance(root, Delta)
self.assertEqual((root.kind, root.key, root.val[0]), ("term", sep, split.val))
self.assertEqual(t.stats["help"], helps + 1)
for k in range(50):
self.assertEqual(run_one(t, t.lookup(k)), ref.get(k))
self.assertEqual(t.items(), sorted(ref.items()))
if __name__ == "__main__":
unittest.main()
History
Justin Levandoski, David Lomet and Sudipta Sengupta of Microsoft Research presented the Bw-tree at ICDE 2013, together with the LLAMA store under it. It built on the B-link tree of Lehman and Yao (1981), which brought in right links and splits in two steps, and replaced its latches by delta records and a CAS on a mapping table. In 2018, Ziqi Wang, Andrew Pavlo and coauthors at Carnegie Mellon University built the OpenBw-Tree, described the details that the paper leaves open, and compared it with other in-memory indexes.
References
- Justin J. Levandoski, David B. Lomet and Sudipta Sengupta, The Bw-Tree: a B-tree for new hardware platforms, Proceedings of the 29th IEEE International Conference on Data Engineering (ICDE 2013), pp. 302 to 313, the mapping table, delta updates, consolidation, the two-step split with an index term delta, merges, epoch-based memory reclamation and the flash log
- Ziqi Wang, Andrew Pavlo, Hyeontaek Lim, Viktor Leis, Huanchen Zhang, Michael Kaminsky and David G. Andersen, Building a Bw-Tree takes more than just buzz words, Proceedings of ACM SIGMOD 2018, pp. 473 to 488, the OpenBw-Tree, its missing details and optimizations, and the comparison with other in-memory indexes
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag R4MGVH Edit this page History Report an error Markdown