Algorithmresearch
Adaptive merging
Also called adaptive merging index.
Build an index as a side effect of queries: sorted runs are created on the first scan and each range query merges its keys into the final index.
- Time
- O(g m log s + t log m + log N + a) worst · averageO(log N + a) best
- Space
- O(N) extra
- Where
- N = the number of entries; a = the size of the answer; g = the number of uncovered key ranges of the query; m = the number of runs, at most N/s rounded up; s = the run size; t = the number of entries that the query merges
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Goetz Graefe, Harumi Kuno, 2010
Adaptive merging builds an index on a column as a side effect of range queries, with no index build up front. The first query reads the column in chunks that fit in memory, sorts each chunk, and keeps the results as sorted runs, as the first phase of an external merge sort would. Each query then takes the entries of its key range out of all runs, merges them, and puts them into a final partition that is fully sorted. A key range that one query has merged is answered from the final partition alone. The index thus grows where the queries go, like database cracking, but because the runs are already sorted, one query is enough to finish its key range. The answers are always exact (a theorem); the speed of convergence is a measurement.
In plain words
You have a big box of papers in random order. The first time somebody asks for "the papers from March to May", you take the papers out in stacks of 100, put each stack in order, and keep the stacks. Then you pull March to May out of every stack, which is quick because each stack is in order, and you put these papers in one big ordered binder.
The next person asks for "April to August". April and May are already in the binder. You pull only June to August out of the stacks and add them to the binder at the right place. Each paper goes into the binder once and stays there. After enough requests, the stacks are empty and the binder is a full index.
The problem
The input is a column of entries (key, row id). Queries arrive one at a time; each asks for all entries with , in key order. Nothing is known about the queries in advance, and there is no time to build an index before the first one. The goal is to answer each query exactly, with a cost that falls quickly toward that of a complete index for the key ranges that the queries use, and to spend no work on key ranges that no query uses.
A full scan costs for every query. A complete sorted index costs per query, for an answer of size , but needs work before the first query.
The algorithm
RANGE-QUERY(lo, hi)- 1
if there are no runs yet then - 2
cut the column into chunks of s entries - 3
sort each chunk in memory; these are the runs R_1, ..., R_m - 4
for each key range [a, b) of [lo, hi) that is not covered yet do - 5
for each run R_i do - 6
i ← the first index with a key ≥ a; j ← the first index with a key ≥ b ▷ two binary searches - 7
move the slice R_i[i .. j - 1] out of R_i - 8
merge the moved slices into one sorted list L - 9
insert L into the final partition F at the first key ≥ a - 10
add [lo, hi) to the covered key ranges; drop the empty runs - 11
return the entries of F with lo ≤ key < hi
- Covered ranges. The code keeps the merged key ranges as a sorted list of disjoint ranges. Step L4 asks for the parts of that are not in this list; there can be several if earlier queries covered pieces of the range.
- The final partition holds exactly the entries whose keys are in the covered ranges. All other entries are still in the runs.
- In the paper, the runs and the final partition are all partitions of one partitioned B-tree, in which an artificial leading key column names the partition. The code on this page keeps each run and the final partition as a sorted Python list.
- Run generation. The paper makes the runs in the first query, with any in-memory sort; replacement selection gives runs about twice the memory size. The code sorts fixed chunks.
Example
The column is 27, 3, 14, 8, 30, 19, 5, 22, 11 (row ids 0 to 8), and the run size is .
- Query [10, 20). There are no runs, so L2 and L3 make the runs , and . The whole range is uncovered. The binary searches find 14 in , 19 in and 11 in . They are merged into , and the runs are now , and . The answer is 11, 14, 19.
- Query [15, 25). The covered range is , so only is new. Only 22, from , moves. , the covered range becomes , and the answer, read from , is 19, 22.
- Query [0, 12). The new part is . The entries 3, 8 and 5 move and are merged into 3, 5, 8, which go to the front of . Now , the covered range is , the third run is empty and is dropped, and the runs left are and . The answer is 3, 5, 8, 11.
After these three queries, 7 of the 9 entries were moved, each one once, and any query inside now costs two binary searches in .
Measurement. With random keys in (seed 7), runs of 1,000 entries, and queries over random ranges of width (1% of the domain), the first query moves 1,005 entries, its answer. After 100 queries, 62,784 entries are in the final partition; after 400 queries, 97,925 are, and a query that falls in a covered range moves nothing. A full scan would read 100,000 entries for each query.
Correctness
The proofs are in proofs/correctness.md. The main points:
- Invariant. Every entry is in exactly one of the runs and the final partition; all of them are sorted; and an entry is in the final partition if and only if its key is in a covered range.
- Extraction. Because a run is sorted, the entries with a key in form one contiguous slice, which two binary searches find.
- Insertion. All keys in the final partition are in covered ranges, so none lies in the new range . The merged list therefore fits in one place of the final partition, and the partition stays sorted.
- Answer (theorem). After L10, is covered, so every entry of the answer is in the final partition, and L11 returns all of them in order.
- Each entry moves once (theorem). Entries only leave runs and only enter the final partition, so the total merge work over all queries is at most entries.
Proof: Adaptive merging answers every range query exactly and moves each entry at most oncefull
We use the notation of the page and the code. The column has entries , where is the key and the row id, so the entries are distinct even if keys are equal. A query asks for all entries with , in key order. The state after the first query is a list of runs , the final partition , and the covered set , a union of disjoint half-open key ranges.
Invariant. After each query:
- (P) Every entry of the column is in exactly one of .
- (S) and every are sorted by .
- (C) An entry is in if and only if its key is in .
Lemma 1 (run generation, L1 to L3). After the runs are made, (P), (S) and (C) hold with and empty.
Proof. The chunks of the column at the offsets are disjoint and cover the column, and each is sorted at L3.
Lemma 2 (gaps, L4). gaps(lo, hi) returns disjoint ranges whose union is .
Proof. The covered ranges are sorted and disjoint. The loop keeps a point such that every point of is either covered or in a gap already returned, and no point in a returned gap is covered. A covered range that starts after gives the gap , and then moves to . A range that ends at or before is skipped. The loop stops when the next range starts at or after , and the last gap is if .
Lemma 3 (extraction, L5 to L7). For a gap and a sorted run , bisect_left(R, (a,)) and bisect_left(R, (b,)) give the indices such that is exactly the set of entries of with a key in .
Proof. The tuple is smaller than every and larger than every with . So is the first index with a key , and likewise is the first index with a key . As is sorted, the keys in are exactly at . Removing a contiguous slice keeps sorted.
Lemma 4 (merge and insert, L8 and L9). After L9 for a gap , the invariant holds with replaced by .
Proof. By (C) and since is disjoint from (Lemma 2), no entry with a key in is in ; by (P) all of them are in the runs, and by Lemma 3 the pieces hold exactly these entries, each once. The merge of sorted pieces is sorted. Every key in is in , so it is either or . So , the first index of with a key , has all keys before it and all keys from it on, and putting the merged list at keeps sorted, which is (S). The entries move from the runs to and no entry is copied, which is (P). Now holds exactly the entries with a key in , which is (C).
Theorem 1 (exact answers). range_query(lo, hi) returns exactly the entries with , in order, and keeps the invariant.
Proof. By Lemmas 2 and 4, applied to each gap in turn, after the loop holds exactly the entries with a key in , and L10 records this union as the new . Removing empty runs changes nothing. As , all entries with a key in are in , which is sorted, so the slice between the first key and the first key at L11 is the answer, in order.
Theorem 2 (each entry moves once). Over any sequence of queries, each entry is sorted once at run generation and moved from a run to at most once. So the total number of moved entries is at most , and a query whose range is already in moves nothing and makes no search in the runs.
Proof. Entries only leave runs (L7) and only enter (L9), and no step moves an entry out of . A covered range has no gaps (Lemma 2), so the loop of L4 does not run.
Cost of one query. With gaps and runs, the query makes binary searches, each , merges the new entries in with a heap, and answers in from . Putting the block into a Python list costs for the shift; in a B-tree, as in the paper, it costs per gap.
The tests check the answers of random queries with many equal keys against a full scan, run the invariant check after each query, check that the moved count equals and is at most , check that a query over the whole key domain empties the runs, and check gaps against a brute force over small integer domains.
Complexity
- First query. Run generation sorts chunks of entries, comparisons, plus the cost of a normal query.
- Later query. For each of the uncovered ranges, two binary searches in each of the runs, ; a heap merge of the moved entries, ; and the answer from the final partition, . In a B-tree, inserting the merged list costs per range. The Python list on this page shifts the tail instead, which costs in the worst case.
- Fully covered query. , the cost of a complete index.
- Total merge work over any sequence of queries is , since each entry is merged once.
- Space. One copy of the column, split among the runs and the final partition.
Properties
- Exact. Every answer equals that of a full scan; the adaptivity changes only the cost.
- Fast convergence. A key range is complete after the first query that asks for it. Database cracking needs many queries over the same area before its pieces are small (a measurement of both papers on their workloads).
- Expensive first query. The first query sorts the whole column in runs, which costs more than the one partition pass of cracking.
- Monotone. No entry ever leaves the final partition, so the work per query only falls for repeated key ranges.
Variants and improvements
- Hybrids with cracking. Idreos, Manegold, Kuno and Graefe (2011) combine the two methods: the initial partitions can be cracked instead of sorted, and the final partition can be cracked, sorted or radix-clustered. Some hybrids keep a first query nearly as cheap as cracking and still converge quickly (a measurement in main-memory column stores).
- Merging more than the query asks. A query can merge a wider key range than its own, to finish the index in fewer queries at the cost of more work now.
- Updates. New entries can go into a new run, or straight into the final partition if their key is covered. Deletions can mark entries in either place.
- Replacement selection gives longer runs and so fewer binary searches per query.
When to use it
Adaptive merging fits a large table that is read mostly by range predicates on one attribute, when the workload is not known in advance, so index selection before the queries is not possible, and when the key ranges of interest are queried more than once. It suits disk-based systems with B-trees, where sorted runs and merges are the natural tools. If the first query must be cheap, cracking or a hybrid is better; if the workload is known and there is idle time, a bulk-loaded B-tree is simpler.
Pitfalls
- Many runs. Every uncovered range needs two binary searches in every run. With small runs and a large column, is large and the searches dominate. Use runs as large as the memory allows.
- Fragmented coverage. Many small covered ranges make large for a wide query. Join covered ranges that touch, as the code does.
- Half-open bounds. Mixing closed and half-open ranges in the covered list gives entries that are merged twice or never. Keep one convention.
- Equal keys. Search by key only (here by the tuple , which sorts before every entry with key ), not by a full entry, or a run is cut in the middle of equal keys.
- The first query's latency. Sorting all runs makes the first query much slower than a scan. A system that cannot accept this must make the runs in the background or use cracking for the start.
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/adaptive-merging/. The authors are listed in prov/4GVQ8M.jsonl.
"""Adaptive merging of Graefe and Kuno (EDBT 2010).
The index is built as a side effect of range queries. The first query cuts
the column into chunks of run_size entries and sorts each chunk, which gives
sorted runs (the partitions of a partitioned B-tree in the paper). Every
query then takes the entries of its key range that are still in the runs,
merges them, and puts them in the final partition, a sorted list. A key range
that has been merged once is answered from the final partition alone.
Entries are (key, row id) pairs, so equal keys are allowed. Query ranges are
half-open: range_query(lo, hi) returns the entries with lo <= key < hi.
"""
import heapq
from bisect import bisect_left, insort
from typing import List, Optional, Sequence, Tuple
Entry = Tuple[int, int]
class AdaptiveMergingIndex:
def __init__(self, column: Sequence[int], run_size: int):
if run_size < 1:
raise ValueError("run_size must be at least 1")
self.column = list(column)
self.run_size = run_size
self.runs: Optional[List[List[Entry]]] = None
self.final: List[Entry] = []
self.covered: List[Tuple[int, int]] = [] # disjoint, sorted, not touching
self.stats = {"sorted": 0, "moved": 0, "searches": 0, "queries": 0}
# ----- the covered key ranges -----
def gaps(self, lo: int, hi: int) -> List[Tuple[int, int]]:
"""The parts of [lo, hi) that are not covered yet."""
out, a = [], lo
for c, d in self.covered:
if d <= a:
continue
if c >= hi:
break
if c > a:
out.append((a, c))
a = max(a, d)
if a >= hi:
break
if a < hi:
out.append((a, hi))
return out
def _cover(self, lo: int, hi: int) -> None:
"""Add [lo, hi) to the covered ranges and join the ranges that touch."""
insort(self.covered, (lo, hi))
joined: List[Tuple[int, int]] = []
for c, d in self.covered:
if joined and c <= joined[-1][1]:
joined[-1] = (joined[-1][0], max(joined[-1][1], d))
else:
joined.append((c, d))
self.covered = joined
# ----- the algorithm -----
def _make_runs(self) -> None:
self.runs = []
for s in range(0, len(self.column), self.run_size): # @line L2
chunk = [(k, s + i) for i, k in enumerate(self.column[s:s + self.run_size])]
chunk.sort() # @line L3
self.runs.append(chunk)
self.stats["sorted"] += len(chunk)
def range_query(self, lo: int, hi: int) -> List[Entry]:
"""All entries (key, row id) with lo <= key < hi, in key order."""
self.stats["queries"] += 1
if self.runs is None: # @line L1
self._make_runs()
if lo >= hi:
return []
for a, b in self.gaps(lo, hi): # @line L4
pieces = []
for run in self.runs: # @line L5
i = bisect_left(run, (a,)) # @line L6
j = bisect_left(run, (b,)) # @line L6
self.stats["searches"] += 2
if i < j:
pieces.append(run[i:j]) # @line L7
del run[i:j] # @line L7
merged = list(heapq.merge(*pieces)) # @line L8
p = bisect_left(self.final, (a,)) # @line L9
self.final[p:p] = merged # @line L9
self.stats["moved"] += len(merged)
self._cover(lo, hi) # @line L10
self.runs = [r for r in self.runs if r] # @line L10
i = bisect_left(self.final, (lo,)) # @line L11
j = bisect_left(self.final, (hi,)) # @line L11
return self.final[i:j] # @line L11
# ----- checks -----
def entries_left_in_runs(self) -> int:
return 0 if self.runs is None else sum(len(r) for r in self.runs)
def check(self) -> None:
"""Assert the invariant of the proof."""
if self.runs is None:
assert not self.final and not self.covered
return
everything = sorted(self.final + [e for r in self.runs for e in r])
assert everything == sorted((k, i) for i, k in enumerate(self.column))
assert self.final == sorted(self.final)
for r in self.runs:
assert r == sorted(r)
def is_covered(k):
return any(c <= k < d for c, d in self.covered)
assert all(is_covered(k) for k, _ in self.final)
assert not any(is_covered(k) for r in self.runs for k, _ in r)
for (c, d), (e, f) in zip(self.covered, self.covered[1:]):
assert c < d < e < f
def full_scan(column: Sequence[int], lo: int, hi: int) -> List[Entry]:
"""The reference: scan the whole column."""
return sorted((k, i) for i, k in enumerate(column) if lo <= k < hi)
test_adaptive_merging.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-merging/. The authors are listed in prov/4GVQ8M.jsonl.
import random
import unittest
from adaptive_merging import AdaptiveMergingIndex, full_scan
def keys(entries):
return [k for k, _ in entries]
class TestExample(unittest.TestCase):
def test_page_example(self):
col = [27, 3, 14, 8, 30, 19, 5, 22, 11]
ix = AdaptiveMergingIndex(col, 3)
self.assertIsNone(ix.runs)
self.assertEqual(keys(ix.range_query(10, 20)), [11, 14, 19])
self.assertEqual([keys(r) for r in ix.runs], [[3, 27], [8, 30], [5, 22]])
self.assertEqual(keys(ix.final), [11, 14, 19])
self.assertEqual(ix.stats["moved"], 3)
self.assertEqual(keys(ix.range_query(15, 25)), [19, 22])
self.assertEqual(ix.stats["moved"], 4) # only 22 was new
self.assertEqual(ix.covered, [(10, 25)])
self.assertEqual(keys(ix.range_query(0, 12)), [3, 5, 8, 11])
self.assertEqual([keys(r) for r in ix.runs], [[27], [30]])
self.assertEqual(keys(ix.final), [3, 5, 8, 11, 14, 19, 22])
self.assertEqual(ix.covered, [(0, 25)])
ix.check()
class TestAgainstFullScan(unittest.TestCase):
def test_random_queries(self):
for seed in range(8):
rng = random.Random(seed)
n = rng.randrange(1, 400)
col = [rng.randrange(200) for _ in range(n)] # many equal keys
ix = AdaptiveMergingIndex(col, rng.randrange(1, 50))
for _ in range(60):
lo = rng.randrange(-20, 220)
hi = lo + rng.randrange(0, 60)
self.assertEqual(ix.range_query(lo, hi), full_scan(col, lo, hi))
ix.check()
# each entry is moved from a run to the final partition at most once
self.assertEqual(ix.stats["moved"], len(ix.final))
self.assertLessEqual(ix.stats["moved"], n)
def test_whole_domain_ends_the_runs(self):
rng = random.Random(3)
col = [rng.randrange(10 ** 6) for _ in range(2000)]
ix = AdaptiveMergingIndex(col, 128)
ix.range_query(0, 10 ** 5)
self.assertEqual(len(ix.runs), 16)
self.assertEqual(ix.stats["sorted"], 2000)
self.assertEqual(keys(ix.range_query(0, 10 ** 6)), sorted(col))
self.assertEqual(ix.entries_left_in_runs(), 0)
self.assertEqual(ix.runs, [])
self.assertEqual(ix.stats["moved"], 2000)
self.assertEqual(ix.stats["sorted"], 2000) # the runs were made once
def test_repeat_query_does_no_merge_work(self):
rng = random.Random(4)
col = [rng.randrange(1000) for _ in range(500)]
ix = AdaptiveMergingIndex(col, 64)
first = ix.range_query(100, 300)
before = dict(ix.stats)
self.assertEqual(ix.range_query(100, 300), first)
self.assertEqual(ix.range_query(150, 200), full_scan(col, 150, 200))
self.assertEqual(ix.stats["moved"], before["moved"])
self.assertEqual(ix.stats["searches"], before["searches"])
def test_gaps_against_brute_force(self):
rng = random.Random(5)
for _ in range(200):
ix = AdaptiveMergingIndex([], 1)
for _ in range(rng.randrange(5)):
a = rng.randrange(30)
ix._cover(a, a + rng.randrange(1, 8))
lo = rng.randrange(-3, 35)
hi = lo + rng.randrange(0, 15)
got = [x for a, b in ix.gaps(lo, hi) for x in range(a, b)]
want = [x for x in range(lo, hi) if not any(c <= x < d for c, d in ix.covered)]
self.assertEqual(got, want)
for (a, b), (c, d) in zip(ix.gaps(lo, hi), ix.gaps(lo, hi)[1:]):
self.assertLess(b, c) # gaps are separated
if __name__ == "__main__":
unittest.main()
History
Goetz Graefe had proposed partitioned B-trees in 2003, B-trees with an artificial leading key column that hold several sorted partitions at once. Graefe and Harumi Kuno used them for adaptive merging at EDBT 2010, as an answer to database cracking (Idreos, Kersten and Manegold, 2007): like cracking, it builds the index as a side effect of queries, but with sorted runs and merges in place of quicksort partitioning. In 2011, Stratos Idreos, Stefan Manegold, Kuno and Graefe studied hybrids of the two methods in main-memory column stores.
References
- Goetz Graefe and Harumi Kuno, Self-selecting, self-tuning, incrementally optimized indexes, Proceedings of the 13th International Conference on Extending Database Technology (EDBT 2010), pp. 371 to 381, run generation by the first query, partitioned B-trees, the merge step of each query, and the comparison with database cracking
- Stratos Idreos, Stefan Manegold, Harumi Kuno and Goetz Graefe, Merging what's cracked, cracking what's merged: adaptive indexing in main-memory column-stores, PVLDB 4(9) (2011), pp. 586 to 597, the hybrids of cracking and adaptive merging and their measured comparison
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 4GVQ8M Edit this page History Report an error Markdown