Data structureresearch
ALEX updatable learned index
Also called ALEX.
A learned index that supports inserts by gapped arrays at its leaves and by splitting and retraining nodes when they fill.
- Time
- O(h + C) worstO(h + log e) averageO(h) best
- Space
- O(n) extra
- Where
- C = the largest number of slots in a data node; e = the distance from the predicted slot to the true slot; h = the depth of the tree; n = the number of keys
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jialin Ding, Umar Farooq Minhas, Jia Yu, Chi Wang, Jaeyoung Do, Yinan Li, Hantian Zhang, Badrish Chandramouli, Johannes Gehrke, Donald Kossmann, David Lomet, Tim Kraska, 2020
ALEX is a learned index that accepts inserts and deletes. Its leaves, the data nodes, are sorted arrays with gaps, and each has a linear model that predicts the slot of a key. An insert puts the key in the slot that the model predicts when that keeps the order, so later lookups find it at or near the prediction, and an exponential search from the prediction finishes the lookup. Its inner nodes also hold linear models, which choose a child, and the tree grows by expanding and splitting nodes when they fill. ALEX is exact: the models only guide the search. Its reported speed and size are measurements, not bounds.
In plain words
Think of a shelf of books in order, with some free spaces left on purpose. A good guess tells you that a book with a title starting with "M" should be about halfway along the shelf. When you buy a new book, you put it where the guess says, if that space is free and the order stays right. If the space is not free, you push a few neighbours one place to the nearest free space. Because books sit where the guess says, finding a book later takes only a short look around the guessed place.
When a shelf gets too full, you either get a longer shelf and spread the books out again, or you split the shelf into two. A small guide above the shelves, also a guess, tells you which shelf to go to.
The abstract type
An ordered set of distinct keys (numbers):
contains(k): is in the set.insert(k)anddelete(k).range(lo, hi): the keys in , in order.
These are the operations of a B+ tree, and ALEX is meant to replace one in main memory.
Representation
- Inner node. A linear model and an array of child pointers of size , a power of 2. The slot of is , clamped to . A child can fill several adjacent slots.
- Data node. A gapped array of slots, a bitmap of the occupied slots, and a linear model that maps a key to a slot. The keys are in increasing order across the occupied slots. Each gap holds a copy of the next key to its right (or ), so the whole array is sorted and a plain search works on it. The data nodes are linked in key order for range scans.
- Density limits. The paper uses a lower limit and an upper limit for the fraction of occupied slots. A new or rebuilt node has density ; a node that would go above expands or splits.
The paper also gives a second layout for data nodes, the packed memory array, which keeps the gaps spread evenly and so bounds the cost of a shift.
Operations
LOOKUP(k)- 1
v ← root - 2
while v is an inner node do v ← v.child[clamp(⌊v.model(k)⌋, 0, v.fanout - 1)] - 3
p ← clamp(round(v.model(k)), 0, v.capacity - 1) - 4
i ← EXPONENTIAL-SEARCH from p for the first slot with a value ≥ k - 5
return true if the first occupied slot at or after i holds k INSERT(k)- 6
v ← the data node of k, as in L1 to L2 - 7
if v.n + 1 > d_u · v.capacity then - 8
if ⌈(v.n + 1) / d_l⌉ ≤ C then EXPAND: rebuild v with that many slots, a new model, and model-based placement - 9
else SPLIT v (sideways if it fills two or more slots of its parent, after doubling the parent if needed; else down), and go to L6 - 10
p ← the predicted slot; i ← the first slot with a value ≥ k; q ← the first occupied slot at or after i - 11
if i < q then put k in the gap of [i, q - 1] that is closest to p - 12
else shift the keys between q (or i - 1) and the nearest gap one place toward the gap, and put k in the freed slot - 13
copy k into the gaps just before it; set its bit
- Model-based placement. When a node is built or expanded, each key in order goes to its predicted slot, moved right if that slot is not after the previous key, and moved left if the keys after it would not fit.
- Sideways split. The data node is cut by the parent's slots: if it fills the slots , the keys routed to and to form two new nodes. If it fills only one slot, the parent first doubles its child array (slot becomes and , and its model is multiplied by 2), when it is still under the fanout limit.
- Split down. If the parent cannot grow, a new inner node with two slots replaces the data node, and its keys go to two new data nodes.
- Delete clears the slot and its bit, and copies the next key into the new gap and the gaps before it. The paper also contracts a node that gets too sparse; the code on this page does not.
The paper chooses between expanding and splitting, and builds the tree at bulk load, with cost models that predict the search and shift cost of a node from its statistics. The code on this page uses fixed limits instead (a largest capacity and a largest fanout), and the bulk load is one root over one data node per slot.
Example
A data node with slots gets the keys 10, 20, 30, 40, 50 and 60. The least-squares line through (key, rank), scaled to 10 slots, is , so the keys go to the slots 0, 2, 3, 5, 7 and 8 (the rounded values of 0, 1.67, 3.33, 5, 6.67 and 8.33). The array is
| slot | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| value | 10 | 20 | 20 | 30 | 40 | 40 | 50 | 50 | 60 | ∞ |
| occupied | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 0 |
- insert(35). The model predicts , slot 4. The first slot with a value is slot 4 (a gap with the copy 40), and the first occupied slot from there is 5. Slot 4 is in the gap run , so 35 goes to slot 4, exactly where the model says.
- insert(15). Predicted slot 1, a gap between 10 and 20. 15 goes to slot 1.
- insert(33). Predicted slot 4, which now holds 35. The first slot with a value is 4, and it is occupied, so there is no gap between 30 and 35. The nearest gap is slot 6 on the right (slots 0 to 3 are all full on the left). The keys 35 and 40 move to the slots 5 and 6, and 33 goes to slot 4.
- lookup(40). The model predicts ; slot 5 holds 35 now. The exponential search goes right and finds 40 in slot 6, one slot away.
Inside an index with , the insert of 33 would be the ninth key in 10 slots, above , so the node would first expand to slots and place all keys again by the new model.
Measurement. With 5,000 random keys from (seed 11), a largest capacity of 256 slots and a largest fanout of 64, the bulk load gives one root and 64 data nodes, and a lookup of a stored key reads 3.2 slots on average in the exponential search. After 5,000 more random inserts, the tree has depth 3, 11 inner nodes and 74 data nodes, after 113 expansions and 10 splits, and a lookup reads 3.1 slots on average.
Correctness
The proofs are in proofs/correctness.md. The main points:
- Routing. All models have a slope of at least 0 (a least-squares line through sorted points cannot fall), so the routing is monotone: a smaller key never goes to a later leaf. A split partitions the keys of a node by the routing function that will route them, so every key stays in the leaf that its route reaches.
- Gapped array. The occupied values are strictly increasing, and every gap holds the next key to its right. So the array is sorted, the exponential search finds the first slot with a value , and is present if and only if the first occupied slot from there holds .
- Insert. The slot that the code chooses is between the last key below and the first key above it, and a shift moves a run of keys by one place without changing their order. Only the gaps just before a changed slot need a new copy.
- Termination. An expansion makes room at once. Each split halves the slots of a node in its parent or splits down into two nonempty nodes, so the loop at L9 ends.
The models affect only the speed. A bad model gives long searches and long shifts, but never a wrong answer.
Proof: Routing by monotone models and gapped arrays with gap values keep ALEX exactfull
We use the notation of the page and of the code. An inner node with slots routes a key to the slot . The route of is the path from the root that follows these slots, and is the data node at its end. A data node has slots with values and bits . Its keys are the values of the occupied slots.
Invariant.
- (R1) Every key of the index is stored in , exactly once.
- (R2) Every model of an inner node has a slope , and each child of fills one run of consecutive slots.
- (G1) In each data node, the values of the occupied slots are strictly increasing from left to right.
- (G2) Each gap holds the value of the next occupied slot to its right, or if there is none. With (G1), the whole array is nondecreasing.
- (D) The number of keys of a data node is at most , and after an insert at most .
- (L) The data nodes, read along the
nextlinks, are in the order of the leaves of the tree from left to right.
Lemma 1 (slopes). fit_linear on sorted keys returns a slope of at least 0.
Proof. The slope is , times a positive scale. The keys and the ranks are both sorted in the same order, so by Chebyshev's sum inequality .
The model of a node made by a down split has the slope , and doubling a node multiplies its slope by 2. So (R2) holds for slopes. The run property holds at the bulk load (one child per slot), is kept by doubling (slot becomes and ), and by a sideways split, which cuts a run into two runs.
Lemma 2 (monotone routing). If , then is equal to or comes before it in the left-to-right order of the leaves.
Proof. With , the floor and the clamp are nondecreasing, so at every inner node on the common part of the two routes. At the first node where the routes differ, takes a smaller slot, and by the run property a different child to the left.
Lemma 3 (exponential search). If (G1) and (G2) hold, lower_bound(k, p) returns the first index with , or if there is none.
Proof. If , the loop keeps and moves left by doubling steps. It stops with , or with for . If , the loop keeps and stops with , or with . In both cases every index below has a value (the array is nondecreasing), the first index with a value lies in , and bisect_left on returns it, or .
Lemma 4 (find). In a data node, is a key if and only if the first occupied slot exists and , where is the result of Lemma 3.
Proof. If with , then is a key. Conversely, let be in the occupied slot . Then , so . Every slot in has a value ; an occupied one would have a value by (G1), since it is left of ; so these slots are all gaps, and .
Lemma 5 (data node insert). If the node has a free slot and is not a key, DataNode.insert adds and keeps (G1) and (G2).
Proof. Let be from Lemma 3 and the first occupied slot . Slot is occupied (or ): a gap at would hold the value of the next occupied slot, which is , so its value would be , against the choice of . So the occupied slots left of hold the keys , the slots are gaps, and the occupied slots from on hold the keys .
If , the code puts in a slot of , which keeps (G1). If , there is no gap between the last key and the first key . The code finds the nearest gap on the right of or on the left of , which exists because a slot is free. On the right it moves the slots one place right and puts in ; on the left it moves the slots one place left and puts in . In both cases the order of the old keys does not change and is between the keys and the keys , so (G1) holds.
For (G2): a gap value depends only on the next occupied slot to its right. On the right shift, the run of gaps just before now has as its next key, and _refill_before sets it. The gaps after do not change their next key. On the left shift, the run of gaps just before had the next key , which is now in slot , so its value is still right; the slot goes to has no gap before it up to . If no shift is needed, the gaps between and the new slot get the value from _refill_before, and the gaps after it keep the next key .
Delete frees slot , gives it the value of slot (which is the next key by (G2)), and sets the run of gaps before it to the same value, which keeps (G1) and (G2).
Lemma 6 (rebuild). DataNode._build on sorted keys and slots puts the keys in strictly increasing slots and sets (G2).
Proof. The slot of the key with index is at least one more than the slot of the key before, and at most , which leaves a slot for each later key. The previous slot is at most , so the range is not empty. _refill_all then sets each gap to the next key from the right.
Theorem 1. After any sequence of bulk load, inserts and deletes, contains(k) is true exactly for the keys of the index, keys() lists them in increasing order, and range(lo, hi) returns the keys in in order.
Proof. We show that every operation keeps the invariant. The bulk load puts each key in the data node of its root slot, which is , and the rebuild of Lemma 6 gives (G1) and (G2). An insert goes to (L6). If the node is too dense (L7), an expansion (L8) rebuilds the same node with more slots, which keeps (R1) and, by Lemma 6, (G1) and (G2). The new capacity is , so after the insert the density is at most , and (D) holds. A split (L9) partitions the keys of the node with the routing function of the node that will route them: in a sideways split by the parent's slot, after the parent doubled if needed, and in a down split by the slot of the new inner node. So every key is again in its , (R1) holds, and the new nodes are built by Lemma 6. The loop then routes again. Each split either halves the run of slots of a node or makes a down split into two nonempty nodes, so the loop ends. When the node has room, Lemma 5 adds the key. The links of the new nodes replace the old node in the list, in slot order, which keeps (L).
By (R1), contains(k) checks the one node where can be, and by Lemmas 3 and 4 it answers correctly. By Lemma 2, all keys of an earlier leaf are smaller than all keys of a later leaf, so by (L) and (G1), keys() is sorted. range starts at ; by Lemma 2 every key is in that leaf or a later one, so the scan along the links, which stops at the first key , returns exactly the keys in .
The tests compare the gapped array and the whole index with a sorted Python list under random inserts, deletes, lookups and range queries, on uniform, narrow and sequential keys, and run check, which tests (R1), (G1), (G2), the runs of slots and the order of the links.
Complexity
- Lookup. model evaluations to reach a data node, then an exponential search that costs comparisons when the key is slots from the prediction. Finding the next occupied slot uses the bitmap. In the worst case, with a long run of gaps or a bad model, this is on a word RAM, or with word operations on the bitmap.
- Insert. A lookup plus a shift. With a gapped array the shift can cost in the worst case; the packed memory array of the paper bounds the amortized cost of a shift by . An expansion or a split rebuilds a node in time, amortized over the inserts that filled it.
- Space. The keys and the gaps, at least slots in all, plus one model and a bitmap per data node and one model and one pointer array per inner node. The models are small, which is why the index part of ALEX is much smaller than the inner nodes of a B+ tree.
These are bounds for the code; the paper's claims are measurements. It reports, on a machine with an Intel Core i9-9900K and 64 GB of memory, throughput up to 4.1 times that of a B+ tree and an index up to 2000 times smaller, on its datasets and workloads.
Variants
- Packed memory array nodes. The second layout of the paper keeps gaps evenly spread with density bounds per window, so the shift cost is bounded, at some cost in lookups.
- Cost models. The paper's ALEX estimates the cost of a node from the expected number of exponential search steps and shifts, and uses these estimates to choose between expanding, retraining and splitting.
- PGM-index. A learned index with a proved error bound per segment, made dynamic by rebuilding static parts. ALEX has no such bound and adapts to the data instead.
When to use it
ALEX fits an in-memory ordered index on numeric keys with a mix of lookups, short range scans and inserts, when the key distribution is smooth enough for linear models to predict positions. It is a research design: it does not handle strings directly, the paper does not cover concurrent access, and its speed depends on the data. Where predictable worst-case behaviour matters, a B+ tree or an adaptive radix tree is the safer choice.
Pitfalls
- Fixed limits instead of cost models. In the code on this page, 1,000 inserts in increasing order past the last key of an index of 100 keys, with a capacity of 32 and a fanout of 4, give a tree of depth 64 with 66 inner nodes (a measurement). Every new key goes to the rightmost node, which splits down again and again. The cost models of the paper, or a larger fanout, are needed for such patterns.
- Gap values. A search on the slot array is only correct if every gap holds the next key to its right. Forgetting to update the gaps before a new key, or after a delete, gives wrong lookups.
- Floating-point models. Rounding can change which slot a key routes to. This is not a problem if lookup and insert use the same code for the routing, but it is if two code paths compute the slot in different ways.
- Negative slopes. If a model could fall, the routing would no longer be monotone, and range scans along the leaves would miss keys. Least squares on sorted keys cannot give a negative slope, but a hand-made model can.
- Duplicates. The design assumes distinct keys. Store a list per key, or make keys unique, before indexing.
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/alex-learned-index/. The authors are listed in prov/DS250H.jsonl.
"""ALEX, the updatable learned index of Ding et al. (SIGMOD 2020), simplified.
Inner nodes hold a linear model and a child array whose size is a power of 2;
a child may fill several adjacent slots. Data nodes are gapped arrays with a
linear model, a bitmap of occupied slots and gap values (each gap holds the
next key to its right, so the slot array is sorted and exponential search
works). Inserts are model-based. A full data node expands while it is small
enough, and otherwise splits: sideways if it fills two or more slots of its
parent, after doubling the parent if the parent can grow, and else down.
Simplifications: the cost models of the paper are replaced by fixed limits,
bulk loading uses one root over many data nodes, and deletes do not contract.
"""
import math
from bisect import bisect_left
from typing import List, Optional, Tuple
INF = math.inf
def fit_linear(keys: List[int], scale: float) -> Tuple[float, float]:
"""Least squares line of (key, rank), scaled so the ranks fill [0, scale)."""
n = len(keys)
if n == 0:
return 0.0, 0.0
if n == 1:
return 0.0, scale / 2
mx = sum(keys) / n
my = (n - 1) / 2
sxx = sum((k - mx) ** 2 for k in keys)
sxy = sum((k - mx) * (i - my) for i, k in enumerate(keys))
a = sxy / sxx if sxx else 0.0
b = my - a * mx
f = scale / n
return a * f, b * f
class DataNode:
def __init__(self, keys: List[int], capacity: int):
self.parent: Optional["InnerNode"] = None
self.next: Optional["DataNode"] = None
self.prev: Optional["DataNode"] = None
self._build(keys, capacity)
def _build(self, keys: List[int], capacity: int) -> None:
n = len(keys)
assert capacity >= max(n, 1)
self.capacity = capacity
self.a, self.b = fit_linear(keys, capacity)
self.vals: List[float] = [INF] * capacity
self.occ = [False] * capacity
self.n = n
prev = -1
for idx, k in enumerate(keys): # model-based placement
p = self.predict(k)
p = max(p, prev + 1)
p = min(p, capacity - (n - idx))
self.vals[p] = k
self.occ[p] = True
prev = p
self._refill_all()
def predict(self, k) -> int:
p = int(round(self.a * k + self.b))
return min(max(p, 0), self.capacity - 1)
def _refill_all(self) -> None:
nxt = INF
for i in range(self.capacity - 1, -1, -1):
if self.occ[i]:
nxt = self.vals[i]
else:
self.vals[i] = nxt
def _refill_before(self, p: int) -> None:
"""Set the gaps just before slot p to the value of slot p."""
v = self.vals[p] if p < self.capacity else INF
i = p - 1
while i >= 0 and not self.occ[i]:
self.vals[i] = v
i -= 1
def keys(self) -> List[int]:
return [self.vals[i] for i in range(self.capacity) if self.occ[i]]
def lower_bound(self, k, p: int) -> Tuple[int, int]:
"""EXPONENTIAL-SEARCH from p: the first slot whose value is >= k, and the probes."""
vals, c = self.vals, self.capacity
probes = 1
if vals[p] >= k:
step, hi = 1, p
while hi - step >= 0 and vals[hi - step] >= k:
probes += 1
hi -= step
step *= 2
lo = max(hi - step, 0)
else:
step, lo = 1, p
while lo + step < c and vals[lo + step] < k:
probes += 1
lo += step
step *= 2
hi = min(lo + step, c)
i = bisect_left(vals, k, lo, hi)
probes += max(1, (hi - lo).bit_length())
return i, probes
def _next_occupied(self, i: int) -> int:
while i < self.capacity and not self.occ[i]:
i += 1
return i
def find(self, k) -> Tuple[bool, int]:
p = self.predict(k) # @line L3
i, probes = self.lower_bound(k, p) # @line L4
j = self._next_occupied(i) # @line L5
return j < self.capacity and self.vals[j] == k, probes # @line L5
def insert(self, k) -> bool:
"""Model-based insert into a node that has a free slot."""
assert self.n < self.capacity
p = self.predict(k) # @line L10
i, _ = self.lower_bound(k, p) # @line L10
q = self._next_occupied(i) # @line L10
if q < self.capacity and self.vals[q] == k:
return False
if i < q: # @line L11
slot = min(max(p, i), q - 1) # @line L11
else: # @line L12
right = q
while right < self.capacity and self.occ[right]:
right += 1
left = i - 1
while left >= 0 and self.occ[left]:
left -= 1
if right < self.capacity and (left < 0 or right - q <= i - 1 - left):
for t in range(right, q, -1): # @line L12
self.vals[t] = self.vals[t - 1]
self.occ[t] = True
slot = q
else:
for t in range(left, i - 1): # @line L12
self.vals[t] = self.vals[t + 1]
self.occ[t] = True
slot = i - 1
self.vals[slot] = k # @line L13
self.occ[slot] = True # @line L13
self._refill_before(slot) # @line L13
self.n += 1
return True
def delete(self, k) -> bool:
found, _ = self.find(k)
if not found:
return False
i, _ = self.lower_bound(k, self.predict(k))
j = self._next_occupied(i)
self.occ[j] = False
self.vals[j] = self.vals[j + 1] if j + 1 < self.capacity else INF
self._refill_before(j)
self.n -= 1
return True
class InnerNode:
def __init__(self, a: float, b: float, fanout: int):
assert fanout & (fanout - 1) == 0
self.a, self.b = a, b
self.children: List[object] = [None] * fanout
self.parent: Optional["InnerNode"] = None
def slot(self, k) -> int:
s = math.floor(self.a * k + self.b)
return min(max(s, 0), len(self.children) - 1)
def span(self, child) -> Tuple[int, int]:
s = self.children.index(child)
e = s
while e < len(self.children) and self.children[e] is child:
e += 1
return s, e
class ALEX:
def __init__(self, keys=(), max_capacity: int = 64, max_fanout: int = 16,
d_lower: float = 0.6, d_upper: float = 0.8, leaf_keys: int = 16):
if not 0 < d_lower < d_upper <= 1:
raise ValueError("need 0 < d_lower < d_upper <= 1")
if max_fanout < 2 or max_fanout & (max_fanout - 1):
raise ValueError("max_fanout must be a power of 2, at least 2")
keys = sorted(set(keys))
self.max_capacity = max_capacity
self.max_fanout = max_fanout
self.dl, self.du = d_lower, d_upper
self.size = len(keys)
self.expansions = self.splits = 0
fanout = 2
while fanout < max_fanout and fanout * leaf_keys < len(keys):
fanout *= 2
a, b = fit_linear(keys, fanout) if keys else (0.0, 0.0)
root = InnerNode(a, b, fanout)
parts: List[List[int]] = [[] for _ in range(fanout)]
for k in keys:
parts[root.slot(k)].append(k)
prev = None
pending: List[int] = []
for s in range(fanout):
if len(parts[s]) > max_capacity * d_lower:
pending.extend(parts[s]) # too many keys for one node: insert them later
parts[s] = []
d = DataNode(parts[s], self._capacity_for(len(parts[s])))
d.parent = root
root.children[s] = d
d.prev = prev
if prev is not None:
prev.next = d
prev = d
self.root = root
self.size -= len(pending)
for k in pending:
self.insert(k)
def _capacity_for(self, n: int) -> int:
"""The slots of a new node with n keys: n / d_lower, at most max_capacity."""
return max(2, n + 1, min(math.ceil(n / self.dl), self.max_capacity))
# ----- lookups -----
def _leaf(self, k) -> DataNode:
v = self.root # @line L1
while isinstance(v, InnerNode): # @line L2
v = v.children[v.slot(k)] # @line L2
return v
def contains(self, k) -> bool:
return self._leaf(k).find(k)[0]
def probes(self, k) -> int:
"""How many slots the exponential search reads for k (a measurement)."""
return self._leaf(k).find(k)[1]
def range(self, lo, hi) -> List[int]:
"""The keys k with lo <= k <= hi, by a scan along the data nodes."""
out: List[int] = []
d: Optional[DataNode] = self._leaf(lo)
while d is not None:
for i in range(d.capacity):
if d.occ[i]:
if d.vals[i] > hi:
return out
if d.vals[i] >= lo:
out.append(d.vals[i])
d = d.next
return out
def keys(self) -> List[int]:
out: List[int] = []
d = self._first_leaf()
while d is not None:
out.extend(d.keys())
d = d.next
return out
def _first_leaf(self) -> DataNode:
v = self.root
while isinstance(v, InnerNode):
v = v.children[0]
return v
# ----- updates -----
def insert(self, k) -> bool:
while True:
d = self._leaf(k) # @line L6
if d.find(k)[0]:
return False
if d.n + 1 <= self.du * d.capacity: # @line L7
d.insert(k)
self.size += 1
return True
need = max(2, math.ceil((d.n + 1) / self.dl))
if need <= self.max_capacity: # @line L8
d._build(d.keys(), need) # @line L8
self.expansions += 1
else:
self._split(d) # @line L9
def delete(self, k) -> bool:
ok = self._leaf(k).delete(k)
if ok:
self.size -= 1
return ok
def _replace(self, old: DataNode, parts: List[Tuple[DataNode, int, int]], parent: InnerNode) -> None:
for d, s, e in parts:
d.parent = parent
for t in range(s, e):
parent.children[t] = d
first, last = parts[0][0], parts[-1][0]
for x, y in zip(parts, parts[1:]):
x[0].next, y[0].prev = y[0], x[0]
first.prev, last.next = old.prev, old.next
if old.prev is not None:
old.prev.next = first
if old.next is not None:
old.next.prev = last
def _split(self, d: DataNode) -> None:
self.splits += 1
p = d.parent
s, e = p.span(d)
if e - s == 1 and len(p.children) < self.max_fanout:
# Double the parent: slot j becomes 2j and 2j + 1.
p.children = [c for c in p.children for _ in (0, 1)]
p.a, p.b = 2 * p.a, 2 * p.b
s, e = 2 * s, 2 * e
keys = d.keys()
if e - s >= 2: # split sideways
mid = (s + e) // 2
left = [k for k in keys if p.slot(k) < mid]
right = [k for k in keys if p.slot(k) >= mid]
l = DataNode(left, self._capacity_for(len(left)))
r = DataNode(right, self._capacity_for(len(right)))
self._replace(d, [(l, s, mid), (r, mid, e)], p)
return
# Split down: a new inner node with two children replaces d.
lo, hi = keys[0], keys[-1]
a = 2.0 / (hi - lo + 1)
q = InnerNode(a, -a * lo, 2)
q.parent = p
left = [k for k in keys if q.slot(k) == 0]
right = [k for k in keys if q.slot(k) == 1]
l = DataNode(left, self._capacity_for(len(left)))
r = DataNode(right, self._capacity_for(len(right)))
for t in range(s, e):
p.children[t] = q
self._replace(d, [(l, 0, 1), (r, 1, 2)], q)
# ----- checks -----
def depth(self) -> int:
def h(v):
if isinstance(v, DataNode):
return 1
return 1 + max(h(c) for c in v.children)
return h(self.root)
def nodes(self) -> Tuple[int, int]:
"""The number of inner nodes and of data nodes."""
inner, data, stack, seen = 0, 0, [self.root], set()
while stack:
v = stack.pop()
if id(v) in seen:
continue
seen.add(id(v))
if isinstance(v, DataNode):
data += 1
else:
inner += 1
stack.extend(v.children)
return inner, data
def check(self) -> None:
"""Raise AssertionError if an invariant fails."""
seen = []
self._check(self.root, seen)
assert len(seen) == self.size
assert seen == sorted(seen) and len(set(seen)) == len(seen)
assert self.keys() == seen
def _check(self, v, seen: List[int]) -> None:
if isinstance(v, DataNode):
assert v.n == sum(v.occ) <= v.capacity <= max(self.max_capacity, 2)
nxt = INF
for i in range(v.capacity - 1, -1, -1):
if v.occ[i]:
nxt = v.vals[i]
assert v.vals[i] == nxt, "gap value is not the next key"
for k in v.keys():
assert self._leaf(k) is v, "key is not in the node it routes to"
seen.extend(v.keys())
return
prev = None
for c in v.children:
assert c.parent is v
if c is not prev:
self._check(c, seen)
prev = c
ids = [id(c) for c in v.children]
for x in set(ids): # each child fills one run of slots
idx = [i for i, y in enumerate(ids) if y == x]
assert idx == list(range(idx[0], idx[-1] + 1))
test_alex_learned_index.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alex-learned-index/. The authors are listed in prov/DS250H.jsonl.
import bisect
import random
import unittest
from alex_learned_index import ALEX, DataNode
class SortedList:
"""The reference: a plain sorted Python list."""
def __init__(self, keys=()):
self.a = sorted(set(keys))
def insert(self, k):
i = bisect.bisect_left(self.a, k)
if i < len(self.a) and self.a[i] == k:
return False
self.a.insert(i, k)
return True
def delete(self, k):
i = bisect.bisect_left(self.a, k)
if i < len(self.a) and self.a[i] == k:
del self.a[i]
return True
return False
def range(self, lo, hi):
return self.a[bisect.bisect_left(self.a, lo):bisect.bisect_right(self.a, hi)]
class TestDataNode(unittest.TestCase):
def test_gapped_array_inserts(self):
rng = random.Random(1)
for trial in range(40):
cap = rng.randrange(4, 40)
keys = sorted(rng.sample(range(200), rng.randrange(0, cap // 2 + 1)))
d = DataNode(keys, cap)
ref = SortedList(keys)
while d.n < cap:
k = rng.randrange(-20, 220)
self.assertEqual(d.insert(k), ref.insert(k))
self.assertEqual(d.keys(), ref.a)
for k in range(-25, 225):
self.assertEqual(d.find(k)[0], k in ref.a)
for k in list(ref.a)[::2] + [999]:
self.assertEqual(d.delete(k), ref.delete(k))
self.assertEqual(d.keys(), ref.a)
def test_model_based_placement(self):
d = DataNode([10, 20, 30, 40, 50, 60], 10)
self.assertEqual([i for i in range(10) if d.occ[i]], [0, 2, 3, 5, 7, 8])
self.assertEqual(d.vals, [10, 20, 20, 30, 40, 40, 50, 50, 60, float("inf")])
self.assertEqual([d.predict(k) for k in (10, 35, 60)], [0, 4, 8])
self.assertTrue(d.insert(35)) # slot 4 is the predicted slot and a gap
self.assertEqual(d.vals[4], 35)
self.assertTrue(d.insert(15)) # slot 1 is the predicted slot and a gap
self.assertEqual(d.vals[1], 15)
self.assertTrue(d.insert(33)) # no gap between 30 and 35: shift 35 and 40 right
self.assertEqual([d.vals[i] for i in range(10) if d.occ[i]], [10, 15, 20, 30, 33, 35, 40, 50, 60])
self.assertEqual([i for i in range(10) if not d.occ[i]], [9])
self.assertFalse(d.insert(33))
class TestALEX(unittest.TestCase):
def workload(self, seed, keyspace, n0, ops, **kw):
rng = random.Random(seed)
init = rng.sample(range(keyspace), n0)
t = ALEX(init, **kw)
ref = SortedList(init)
t.check()
for step in range(ops):
r = rng.random()
if r < 0.6:
k = rng.randrange(keyspace)
self.assertEqual(t.insert(k), ref.insert(k))
elif r < 0.75:
k = rng.choice(ref.a) if ref.a and rng.random() < 0.8 else rng.randrange(keyspace)
self.assertEqual(t.delete(k), ref.delete(k))
elif r < 0.9:
k = rng.randrange(keyspace)
self.assertEqual(t.contains(k), k in ref.a)
else:
lo = rng.randrange(keyspace)
hi = lo + rng.randrange(keyspace // 20)
self.assertEqual(t.range(lo, hi), ref.range(lo, hi))
if step % 200 == 0:
t.check()
t.check()
self.assertEqual(t.keys(), ref.a)
return t
def test_uniform_inserts(self):
for seed in range(3):
t = self.workload(seed, 10 ** 5, 200, 1500)
self.assertGreater(t.splits, 0)
self.assertGreater(t.expansions, 0)
def test_skewed_inserts_split_down(self):
rng = random.Random(7)
t = ALEX(range(0, 400, 4), max_capacity=32, max_fanout=4)
ref = SortedList(range(0, 400, 4))
for _ in range(800): # all new keys fall in a narrow range
k = 1000 + rng.randrange(2000)
self.assertEqual(t.insert(k), ref.insert(k))
t.check()
self.assertEqual(t.keys(), ref.a)
self.assertGreaterEqual(t.depth(), 3)
for k in range(990, 3010, 7):
self.assertEqual(t.contains(k), k in ref.a)
def test_sequential_inserts(self):
t = ALEX([], max_capacity=32, max_fanout=8)
for k in range(600):
self.assertTrue(t.insert(k))
t.check()
self.assertEqual(t.keys(), list(range(600)))
self.assertFalse(t.insert(10))
def test_lookups_are_short_on_linear_keys(self):
keys = list(range(0, 30000, 3))
t = ALEX(keys, max_capacity=256, max_fanout=1024)
self.assertTrue(all(t.contains(k) for k in keys[::50]))
worst = max(t.probes(k) for k in keys[::50])
self.assertLessEqual(worst, 4)
def test_bad_arguments(self):
with self.assertRaises(ValueError):
ALEX([], d_lower=0.9, d_upper=0.8)
with self.assertRaises(ValueError):
ALEX([], max_fanout=6)
if __name__ == "__main__":
unittest.main()
History
Tim Kraska and coauthors proposed learned indexes in 2018, with a recursive model index over a static sorted array. Jialin Ding, Umar Farooq Minhas and ten coauthors, with Tim Kraska as the last author, made the idea updatable with ALEX, at SIGMOD 2020. It brought in gapped arrays with model-based inserts, exponential search, and a tree whose nodes expand and split by cost models.
References
- Jialin Ding, Umar Farooq Minhas, Jia Yu, Chi Wang, Jaeyoung Do, Yinan Li, Hantian Zhang, Badrish Chandramouli, Johannes Gehrke, Donald Kossmann, David Lomet and Tim Kraska, ALEX: an updatable adaptive learned index, Proceedings of ACM SIGMOD 2020, pp. 969 to 984, the node layouts (gapped array and packed memory array), model-based inserts, exponential search, node expansion and splits, the cost models, bulk loading, and the experiments
- Tim Kraska, Alex Beutel, Ed H. Chi, Jeffrey Dean and Neoklis Polyzotis, The case for learned index structures, SIGMOD 2018, pp. 489 to 504, the recursive model index that ALEX starts from
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 DS250H Edit this page History Report an error Markdown