Algorithmadvanced
Radix hash join
Also called radix-partitioned hash join, radix join.
Cluster both inputs on the low bits of a hash, in passes with a small fan-out, so that each cluster fits in the cache. Then join each pair of clusters with a small hash table.
- Solves
- Relational join problem
- Time
- O(P(n + m) + 2^b + n m) worstO(P(n + m) + 2^b + T) average · best
- Space
- O(n + m + 2^b) extra
- Counts
- io O(P(n + m)/B + (n + m + T)/B + 2^b) average
- Where
- B = the cache line size in words; M = the cache size in words; P = the number of clustering passes; T = the number of output tuples; b = the total number of radix bits; m = the number of tuples of S; n = the number of tuples of R
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter A. Boncz, Stefan Manegold, Martin L. Kersten, 1999
Radix hash join is a hash join for data in main memory that first splits both inputs into many small clusters on the low bits of a hash of the key, and then joins each pair of clusters with a hash table that fits in the CPU cache. The splitting is done in one or more passes, and each pass uses only a few bits, so that it writes to few places at a time and does not thrash the cache or the TLB (the cache of page translations). The Grace hash join uses the same idea one level up, to make the parts fit in the buffer pool instead of the cache, and it counts page I/Os. This page counts cache misses, and the speed-ups on real machines are measurements.
In plain words
You must match a large pile of order slips with a large pile of customer cards. Your desk is small. If you put all customer cards in one big filing box, you must walk to a different part of the box for each slip, and you lose time at each step.
So you first sort both piles into a few trays by the last digit of the customer number. You only use a few trays at a time, so they all fit on the desk. If you need more trays, you sort each tray again by the next digit. At the end, each tray of cards is small. You then take one tray of cards and the tray of slips with the same digits, and you match them on your desk with a small box. Each card and each slip is touched a few times, but always close at hand.
The problem
The input is two relations and in main memory, with and tuples, and the condition . The output is the bag of the relational join problem: one tuple for each matching pair, so a key that occurs times in and times in gives outputs. A NULL key never matches.
Cost model. There are two measures. The first is the number of steps in the word RAM. The second is the number of cache misses in the external memory model, with a cache of words in lines of words. In the external memory model, the memory holds blocks; on this page the memory is the cache and a block is a cache line, so the cache holds lines. A tuple takes one word. The hash is on integer keys. Its low 4 bits are the low 4 bits of , because the multiplier is 1 modulo 16, so on small integers it acts like clustering on the key bits.
The algorithm
RADIX-CLUSTER(X, h, b_1, ..., b_P) ▷ X is an array of n tuples- 1
b ← b_1 + ... + b_P; the clusters are [the whole of X] - 2
for p ← 1 to P do - 3
s ← b − (b_1 + ... + b_p) ▷ pass p uses bits s to s + b_p − 1 of h - 4
for each cluster C, in order do - 5
count[j] ← the number of x in C with digit (h(x.key) >> s) mod 2^b_p = j ▷ histogram - 6
start[j] ← start of C + count[0] + ... + count[j − 1] ▷ prefix sum - 7
for each x in C, in order: Y[start[j]] ← x and start[j] ← start[j] + 1, where j is the digit of x ▷ scatter - 8
X ← Y; the clusters are the pieces of all clusters, in order - 9
return X and the bounds of its 2^b clusters RADIX-JOIN(R, S, h, b_1, ..., b_P)- 10
cluster R and S with RADIX-CLUSTER(·, h, b_1, ..., b_P) - 11
for i ← 0 to 2^b − 1 do - 12
build a bucket-chained table on cluster i of R, indexed by the bits of h above bit b - 13
for each s in cluster i of S and each r in the bucket of s.b with r.a = s.b do output r · s - 14
return the output
Each pass is one step of an MSD radix sort on the low bits of the hash: a histogram (line L5), a prefix sum (line L6) and a stable scatter (line L7). Pass 1 uses the highest of the bits, and each later pass splits each cluster again on the next bits, so after pass cluster holds the tuples with . A pass with bits writes to places at once, its fan-out. More passes give a smaller fan-out per pass, at the cost of one more read and write of all tuples.
The table of line L12 must use bits of that the clustering did not use, because all tuples of a cluster share their low bits. The implementation keeps the table as an array of bucket heads and an array of next links, as in the radix join of Balkesen et al. The table and the cluster must fit in the cache, which fixes : about of divided by the number of tuples that fit in the cache with their table.
Example
Let have the keys (tuples to ) and have the keys ( to ). For these keys . Take in two passes of one bit each.
| step | what happens to | result |
|---|---|---|
| pass 1, L5 | digit = bit 1 of the hash: keys 1, 4, 1, 5, 9 give 0, keys 3, 2, 6 give 1 | count = [5, 3] |
| pass 1, L6 to L7 | scatter in input order | |
| pass 2, first cluster | digit = bit 0: key 4 gives 0, keys 1, 1, 5, 9 give 1 | |
| pass 2, second cluster | keys 2, 6 give 0, key 3 gives 1 | |
| L9 | clusters 0 to 3 | , bounds |
gives cluster 0 = (keys 4 and 8) and cluster 1 = (keys 1, 1, 5, 9); clusters 2 and 3 of are empty, so line L11 skips them. Cluster 0 gives , and finds only with key in its bucket. Cluster 1 gives 6 tuples: and each find and , finds and finds . The output has 7 tuples, the bag join, and the join phase makes 8 key comparisons. Each pass moved all 8 tuples of .
Simulated cache misses. The implementation can record every word it reads or writes and run the trace through a fully associative LRU cache. With tuples, keys drawn from 0 to 999 with seed 1, and a cache of 16 lines of 4 words, the counts are:
| run | cache misses |
|---|---|
| cluster on 6 bits in one pass (fan-out 64) | 472 |
| cluster on 6 bits in two passes of 3 bits (fan-out 8) | 305 |
| join phase without clustering (one table on all of ) | 808 |
| join phase after clustering on 4 bits | 147 |
| join phase after clustering on 6 bits | 105 |
A fan-out of 64 needs more lines than the cache has, so many scatter writes miss, and the two passes of fan-out 8 miss less although they move each tuple twice. The table on all of is far larger than the cache, so most probes miss, while the tables of small clusters stay in the cache. These are counts in this toy model, not timings of a real machine.
Correctness
After the last pass, cluster holds exactly the tuples with : each pass is a stable counting scatter of each cluster on the next digit. Two tuples with the same key have the same hash, so every matching pair lies in one pair of clusters with the same number, and the hash join of that pair finds it once. The full proof, with the bounds on work and on cache misses, is in the proof page.
Proof: Radix hash join returns the bag join, with O(P(n + m)/B + (n + m + T)/B + 2^b) cache misses when the clusters fitfull
We use the line numbers of the pseudocode. We treat each stored tuple as a distinct occurrence, so and are bags and the join is the bag join: one copy of for each pair of occurrences with . Let , let be the cluster number of a tuple, and let be the shift of line L3 in pass , with .
Lemma 1 (one pass). Before pass , assume that is a permutation of the input and that it is cut into contiguous clusters, one for each value , in increasing order of , where the cluster of holds the tuples with in input order. Then after pass , the same holds with in place of .
Proof. Take one cluster with value (line L4). Its tuples have , where is the digit of line L5. Line L5 counts the tuples with each digit . Line L6 sets to the start of plus the number of tuples of with a smaller digit, so the ranges for cut the range of into consecutive pieces in increasing order of . Line L7 visits in order and writes each tuple with digit to the next free place of piece . So piece receives exactly the tuples of with digit , in input order, and every place of the range of is written once. The pieces of have the values , which are increasing in and lie between the values of the pieces of the clusters before and after . Line L8 keeps this order.
Lemma 2 (clustering). RADIX-CLUSTER returns a permutation of its input in which cluster , the range from to , holds exactly the tuples with , in input order.
Proof. Before pass 1, , so for every tuple, and the whole input is the single cluster of value 0. This is the hypothesis of Lemma 1 for . By induction with Lemma 1, after pass the claim holds with , that is, with itself.
Theorem 1 (correctness). RADIX-JOIN returns a list whose multiset of elements is (bag semantics, a NULL key never matches).
Proof. A pair with has , so , and by Lemma 2 is in cluster of and in cluster of . So every matching pair lies in one pair of clusters with the same number, and in no other. Line L12 inserts each occurrence of cluster of once into a chained table: it prepends it to the chain of its bucket and never removes it. Line L13 meets each occurrence of cluster of once, walks the whole chain of the bucket of , which holds every occurrence of with key (equal keys have equal hash and so equal bucket), and appends exactly when . So each matching pair gives exactly one output, and nothing else is appended. All loops run over finite ranges, so the algorithm stops.
Theorem 2 (work). In the word RAM, RADIX-CLUSTER does steps on tuples. Under the simple uniform hashing assumption for the bucket bits (the bits of above the low bits), the expected work of RADIX-JOIN is . Its worst case is .
Proof. Pass handles each tuple twice (lines L5 and L7) and does work per cluster for lines L5 and L6. Before pass there are clusters, so the counters cost in total. This gives . In the join phase, cluster gets a table with at least buckets. A probe compares with the tuples of in its bucket: those with key each give an output, and under the assumption each other key of lands in the bucket with probability at most , so the expected number of the other comparisons is at most 1 per probe. Summing over clusters gives . In the worst case every probe walks a whole cluster, at most comparisons in total.
The cache model. We use the external memory model for the cache: the cache holds words in lines of words, a miss moves one line, and we may choose which lines to keep (an optimal replacement). In the external memory model, the memory holds blocks; on this page the memory is the cache and a block is a cache line, so the cache holds lines. Each tuple takes one word.
Theorem 3 (cache misses). Assume that every pass has a fan-out with , and that every cluster of satisfies . Then RADIX-JOIN has cache misses.
Proof. Take one cluster of size in pass . Line L5 reads in order and updates counters that fill lines: keep these lines and one input line, which costs misses. Line L7 reads again in order and writes to output places, each of which moves forward one word at a time. Keep one line for the input, one line for each of the output cursors and the lines of the counters. By the assumption these fit. Each output cursor misses once at its start and once per words, so the writes cost at most misses, and the reads . Summed over the clusters of pass , this is , and over all passes . The same holds for .
In the join phase, cluster needs its tuples, its head array of fewer than words and its next array of words, at most words, plus one line for and one line for the output. By the assumption they fit, so line L12 costs misses, and line L13 then misses only on the lines of and of the output: , where is the output of the cluster. The sum over the clusters is .
The second assumption depends on the data. With radix bits and no heavy key, the clusters of have about tuples, so is chosen near . A key that occurs more than times makes a cluster that does not fit, whatever is.
Without partitioning. Let the plain hash join build one table of words on all of , and let the probe keys be such that the bucket of each probe is uniform over the buckets and independent of the cache contents. At a probe, at most words of the table are in the cache, so the probe misses with probability at least . So the expected number of misses is at least , which is close to one miss per probe when , against per tuple for the radix join under the assumptions of Theorem 3.
Real caches. A hardware cache uses a fixed replacement rule such as LRU and is set associative, not the optimal replacement of the model. By the resource augmentation result for LRU of Sleator and Tarjan, LRU with twice the lines has at most about twice the misses of the optimal rule, so Theorem 3 holds for LRU with the fan-out and cluster limits halved. The translation lookaside buffer (TLB) is a small cache of page translations, and the same counting with a page in place of a line and the number of TLB entries in place of shows why the fan-out of one pass must stay below the number of TLB entries.
Complexity
- Work. Each pass reads every tuple twice and writes it once, and it does work per cluster for the counters, so the clustering costs steps. Under the simple uniform hashing assumption for the bucket bits, the join phase does expected work. The worst case, when every key of a cluster shares one bucket, is comparisons (a theorem in the word RAM).
- Cache misses. If every pass has a fan-out that fits in the cache with one line per output cursor, and every cluster of with its table fits in the cache, the radix join has misses (a theorem in the external memory model). A hash join with one table much larger than the cache misses on almost every probe, about misses.
- TLB misses. The same count with a memory page in place of a line and the number of TLB entries in place of limits the fan-out of a pass to about the number of TLB entries. This was the reason for several passes in Boncz et al. (1999) and Manegold et al. (2002).
- Space. The clustering needs a second array of tuples and counters. The join phase needs one table at a time.
- Measurements. Boncz, Manegold and Kersten (1999) and Manegold, Boncz and Kersten (2002) measured the radix join on the machines of their time and fitted models of the cache and TLB misses to the measured times. Balkesen et al. (2013) compared a tuned parallel radix join with a no-partitioning hash join on several multi-core machines, and the radix join was faster in most of their settings. These results depend on the hardware; this page does not repeat their numbers.
Properties
- Not pipelined. Both inputs must be fully clustered before the first output, so the operator is a pipeline breaker on both sides, unlike the probe side of a hash join.
- Stable clusters. Each cluster keeps the input order, because the scatter is stable.
- Output order. The output comes cluster by cluster, so it is grouped by the low bits of the hash, not by key order.
- Equality only. Like every hash join, it cannot answer a band or an inequality condition.
- Deterministic. With a fixed hash function, the clusters and the output order are fixed.
Variants and improvements
- Number of passes. One pass is best when is below the number of cache lines and TLB entries. With more clusters, two passes are usually used. Choosing and the is a tuning decision on measured hardware.
- Partition the build side only. Some systems cluster only and probe the clusters with an unclustered , which saves a pass but gives up the cache locality of the probes.
- Parallel radix join. Each thread builds a histogram of its part of the input, a global prefix sum gives each thread its own output ranges, and then the threads scatter without locks. Balkesen et al. (2013) tune this form, and morsel-driven parallelism schedules the work.
- Software write-combining buffers. The scatter can write each output cluster first into a small buffer of one cache line and copy the full line at once, which reduces TLB misses for larger fan-outs.
- Grace hash join. The Grace hash join is the disk form: it partitions until each part fits in the buffer pool, and counts page I/Os instead of cache misses. A hybrid hash join keeps one part in memory.
- Sort-merge instead. A radix sort of both inputs followed by a merge, as in sort-merge join, uses the same clustering steps and gives sorted output.
When to use it
Use it for a large equi-join in main memory when the smaller input is much larger than the cache, for example two tables of millions of rows in a column store. When the smaller input fits in the cache, a plain hash join is simpler and as fast. When the input does not fit in memory, partition it on disk first with a Grace hash join.
Pitfalls
- Too many clusters in one pass. A fan-out above the number of cache lines or TLB entries makes most writes of line L7 miss. Split the bits over several passes.
- Reusing the radix bits in the table. Line L12 must index the table with bits that line L5 did not use. Inside a cluster the low bits are equal, so a table on them puts every tuple in one bucket.
- A weak hash. The low bits of a multiplicative hash of small integers are the low bits of the key. Keys with a common pattern in their low bits, for example all even, fill only part of the clusters. Use a hash with good low bits when the keys are not uniform.
- Skew. A key with many tuples makes one cluster that no number of bits can split. Its table does not fit in the cache, and in a parallel join one thread gets most of the work (see data skew).
- Treating measured speed-ups as guarantees. The gain over a plain hash join depends on the cache size, the TLB, the tuple width and the number of threads. It is a measurement, not a theorem.
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
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Naive relations, operators by definition, SQL three-valued logic and a page-counting disk.
This is the reference that the tests of the databases pages compare against.
Every operator here follows its definition directly, with nested loops and no
index, hash table or sort of the input. Do not use it as a fast engine.
Relations
Relation(schema, rows, mode) holds a tuple of distinct attribute names and
a collections.Counter from tuples to positive counts. mode is "bag" (the
default, SQL semantics) or "set" (relational theory); in set mode every
count is 1. rows may be an iterable of tuples (duplicates add up) or a
mapping from tuples to counts. Two relations are equal when they have the
same attributes (in any column order) and the same count for each tuple.
The mode is not compared.
Operators (each returns a new Relation in the mode of its input)
select(rel, pred) keeps a row only when pred(row) is True
where(rel, pred) the same as select (the SQL WHERE filter)
project(rel, attrs) bag: counts add up; set: duplicates removed
rename(rel, mapping) mapping is {old: new}
union(r, s) bag: UNION ALL (counts add); set: union
difference(r, s) bag: monus max(0, m - n); set: r - s
intersection(r, s) bag: min(m, n); set: intersection
product(r, s) attributes must be disjoint; counts multiply
natural_join(r, s) nested loops on the common attributes
theta_join(r, s, pred) select(product(r, s), pred)
semijoin(r, s), antijoin(r, s)
distinct(rel) every count becomes 1
aggregate(rel, group_attrs, aggs)
aggs is a list of (func, attr, out) with func in
count_star, count, count_distinct, sum, avg, min, max
A predicate receives the row as a dict from attribute name to value. It may
return True, False or None (UNKNOWN). Only True keeps the row.
Nulls
NULL is None. Joins follow SQL: a common attribute that is None in either
row never matches. aggregate follows SQL: GROUP BY puts all nulls of a
column in one group, every aggregate except count_star skips nulls, and
sum, avg, min and max of no non-null value give None while count gives 0.
With no grouping attributes, aggregate returns one row even for an empty
input, as SQL does.
Expressions
evaluate(expr, db, mode) evaluates a tree of nested tuples:
("scan", name)
("select", pred, e) ("project", attrs, e)
("rename", mapping, e) ("distinct", e)
("union", e1, e2) ("difference", e1, e2)
("intersection", e1, e2) ("product", e1, e2)
("join", e1, e2) ("theta_join", pred, e1, e2)
("semijoin", e1, e2) ("antijoin", e1, e2)
("aggregate", group_attrs, aggs, e)
db maps a name to a Relation. Each scanned relation is first put in mode.
Three-valued logic
tv_and, tv_or and tv_not are the strong Kleene connectives on True, False
and None. cmp3(op, x, y) compares with op in =, <>, !=, <, <=, >, >= and
returns None when x or y is None.
Disk
Disk counts page reads and writes. load(rows, per_page) puts an existing
input on the disk without counting it. paginate(rows, per_page) splits a
list of rows into pages.
Random data
random_relation(rng, schema, n, domain, mode, null_rate) draws n rows.
"""
from collections import Counter
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from fractions import Fraction
from numbers import Number
import random
BAG = "bag"
SET = "set"
MODES = (BAG, SET)
# ---------------------------------------------------------------- ordering
def value_key(v: object) -> tuple:
"""A total order on the values of one column: None first, then numbers, then strings."""
if v is None:
return (0, 0)
if isinstance(v, Number):
return (1, v)
if isinstance(v, str):
return (2, v)
if isinstance(v, tuple):
return (3, tuple(value_key(x) for x in v))
return (4, repr(v))
def row_key(t: Sequence) -> tuple:
"""A total order on tuples that tolerates None. Use it to sort rows in tests."""
return tuple(value_key(v) for v in t)
# ---------------------------------------------------------------- relations
class Relation:
"""A relation: a schema (tuple of names), a Counter of tuples and a mode."""
__slots__ = ("schema", "rows", "mode")
def __init__(self, schema: Sequence[str], rows: Iterable | Mapping = (), mode: str = BAG) -> None:
if mode not in MODES:
raise ValueError("mode must be 'bag' or 'set'")
schema = tuple(schema)
if len(set(schema)) != len(schema):
raise ValueError("duplicate attribute in schema %r" % (schema,))
counts: Counter = Counter()
items = rows.items() if isinstance(rows, Mapping) else ((t, 1) for t in rows)
for t, c in items:
t = tuple(t)
if len(t) != len(schema):
raise ValueError("tuple %r does not fit schema %r" % (t, schema))
if c < 0:
raise ValueError("negative count for %r" % (t,))
if c:
counts[t] += c
if mode == SET:
counts = Counter({t: 1 for t in counts})
self.schema = schema
self.rows = counts
self.mode = mode
def index(self, attr: str) -> int:
return self.schema.index(attr)
def reorder(self, schema: Sequence[str]) -> "Relation":
"""The same relation with its columns in the order of schema."""
schema = tuple(schema)
if sorted(schema) != sorted(self.schema):
raise ValueError("schemas %r and %r differ" % (self.schema, schema))
pos = [self.schema.index(a) for a in schema]
return Relation(schema, {tuple(t[i] for i in pos): c for t, c in self.rows.items()}, self.mode)
def with_mode(self, mode: str) -> "Relation":
return Relation(self.schema, self.rows, mode)
def as_dict(self, t: Sequence) -> dict:
return dict(zip(self.schema, t))
def sorted_rows(self) -> list:
"""Every tuple, repeated by its count, in row_key order."""
out = []
for t in sorted(self.rows, key=row_key):
out.extend([t] * self.rows[t])
return out
def __iter__(self):
return iter(self.sorted_rows())
def __len__(self) -> int:
return sum(self.rows.values())
def __eq__(self, other: object) -> bool:
if not isinstance(other, Relation):
return NotImplemented
if sorted(self.schema) != sorted(other.schema):
return False
return self.rows == other.reorder(self.schema).rows
def __repr__(self) -> str:
body = ", ".join("%r: %d" % (t, self.rows[t]) for t in sorted(self.rows, key=row_key))
return "Relation(%r, {%s}, %r)" % (self.schema, body, self.mode)
def _mode2(r: Relation, s: Relation) -> str:
if r.mode != s.mode:
raise ValueError("operands have modes %r and %r" % (r.mode, s.mode))
return r.mode
def _same_schema(r: Relation, s: Relation) -> Relation:
"""s with its columns in the order of r; the attribute sets must be equal."""
if sorted(r.schema) != sorted(s.schema):
raise ValueError("union-incompatible schemas %r and %r" % (r.schema, s.schema))
return s.reorder(r.schema)
# ---------------------------------------------------------------- three-valued logic
def tv_and(a: bool | None, b: bool | None) -> bool | None:
if a is False or b is False:
return False
if a is None or b is None:
return None
return True
def tv_or(a: bool | None, b: bool | None) -> bool | None:
if a is True or b is True:
return True
if a is None or b is None:
return None
return False
def tv_not(a: bool | None) -> bool | None:
return None if a is None else not a
_CMP = {
"=": lambda x, y: x == y,
"<>": lambda x, y: x != y,
"!=": lambda x, y: x != y,
"<": lambda x, y: x < y,
"<=": lambda x, y: x <= y,
">": lambda x, y: x > y,
">=": lambda x, y: x >= y,
}
def cmp3(op: str, x: object, y: object) -> bool | None:
"""SQL comparison: None (UNKNOWN) if either side is NULL."""
if op not in _CMP:
raise ValueError("unknown comparison %r" % (op,))
if x is None or y is None:
return None
return bool(_CMP[op](x, y))
def is_true(v: bool | None) -> bool:
"""The WHERE test: only True passes; False and None (UNKNOWN) do not."""
return v is True
# ---------------------------------------------------------------- operators
def select(rel: Relation, pred: Callable[[dict], bool | None]) -> Relation:
out = {t: c for t, c in rel.rows.items() if pred(rel.as_dict(t)) is True}
return Relation(rel.schema, out, rel.mode)
where = select
def project(rel: Relation, attrs: Sequence[str]) -> Relation:
attrs = tuple(attrs)
pos = [rel.index(a) for a in attrs]
out: Counter = Counter()
for t, c in rel.rows.items():
out[tuple(t[i] for i in pos)] += c
return Relation(attrs, out, rel.mode)
def rename(rel: Relation, mapping: Mapping[str, str]) -> Relation:
for a in mapping:
if a not in rel.schema:
raise ValueError("no attribute %r to rename" % (a,))
return Relation(tuple(mapping.get(a, a) for a in rel.schema), rel.rows, rel.mode)
def union(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = Counter(r.rows)
out.update(s.rows)
return Relation(r.schema, out, mode)
def difference(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = {t: max(0, c - s.rows.get(t, 0)) for t, c in r.rows.items()}
return Relation(r.schema, out, mode)
def intersection(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = {t: min(c, s.rows.get(t, 0)) for t, c in r.rows.items()}
return Relation(r.schema, out, mode)
def product(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
common = [a for a in r.schema if a in s.schema]
if common:
raise ValueError("product needs disjoint schemas; common: %r" % (common,))
out: Counter = Counter()
for t, c in r.rows.items():
for u, d in s.rows.items():
out[t + u] += c * d
return Relation(r.schema + s.schema, out, mode)
def _matches(r: Relation, s: Relation, t: tuple, u: tuple, common: Sequence[str]) -> bool:
for a in common:
x, y = t[r.index(a)], u[s.index(a)]
if x is None or y is None or x != y:
return False
return True
def natural_join(r: Relation, s: Relation) -> Relation:
"""Nested loops over both inputs. With no common attribute it is the product."""
mode = _mode2(r, s)
common = [a for a in r.schema if a in s.schema]
rest = [a for a in s.schema if a not in common]
rest_pos = [s.index(a) for a in rest]
out: Counter = Counter()
for t, c in r.rows.items():
for u, d in s.rows.items():
if _matches(r, s, t, u, common):
out[t + tuple(u[i] for i in rest_pos)] += c * d
return Relation(r.schema + tuple(rest), out, mode)
def theta_join(r: Relation, s: Relation, pred: Callable[[dict], bool | None]) -> Relation:
return select(product(r, s), pred)
def semijoin(r: Relation, s: Relation) -> Relation:
"""Rows of r (with their counts) that join with at least one row of s."""
_mode2(r, s)
common = [a for a in r.schema if a in s.schema]
out = {t: c for t, c in r.rows.items() if any(_matches(r, s, t, u, common) for u in s.rows)}
return Relation(r.schema, out, r.mode)
def antijoin(r: Relation, s: Relation) -> Relation:
"""Rows of r (with their counts) that join with no row of s."""
_mode2(r, s)
common = [a for a in r.schema if a in s.schema]
out = {t: c for t, c in r.rows.items() if not any(_matches(r, s, t, u, common) for u in s.rows)}
return Relation(r.schema, out, r.mode)
def distinct(rel: Relation) -> Relation:
return Relation(rel.schema, {t: 1 for t in rel.rows}, rel.mode)
AGG_FUNCS = ("count_star", "count", "count_distinct", "sum", "avg", "min", "max")
def _avg(vals: list) -> object:
total = sum(vals)
if all(isinstance(v, (int, Fraction)) for v in vals):
return Fraction(total, 1) / len(vals)
return total / len(vals)
def agg_value(func: str, vals: list) -> object:
"""One SQL aggregate over a list of column values (with repeats). count_star counts all."""
if func == "count_star":
return len(vals)
nn = [v for v in vals if v is not None]
if func == "count":
return len(nn)
if func == "count_distinct":
seen: list = []
for v in nn:
if v not in seen:
seen.append(v)
return len(seen)
if not nn:
return None
if func == "sum":
return sum(nn)
if func == "avg":
return _avg(nn)
if func == "min":
return min(nn)
if func == "max":
return max(nn)
raise ValueError("unknown aggregate %r" % (func,))
def aggregate(rel: Relation, group_attrs: Sequence[str], aggs: Sequence[tuple]) -> Relation:
"""gamma_{G; f(A) -> B}(rel) by definition.
aggs is a list of (func, attr, out); attr is ignored for count_star and may
be None. For each distinct group key, in row_key order, the whole input is
scanned. Each result row has count 1 in either mode.
"""
group_attrs = tuple(group_attrs)
gpos = [rel.index(a) for a in group_attrs]
for func, attr, _ in aggs:
if func not in AGG_FUNCS:
raise ValueError("unknown aggregate %r" % (func,))
if func != "count_star":
rel.index(attr)
keys: list = []
for t in rel.rows:
k = tuple(t[i] for i in gpos)
if k not in keys:
keys.append(k)
if not group_attrs and not keys:
keys = [()]
out: Counter = Counter()
for k in sorted(keys, key=row_key):
row = list(k)
for func, attr, _ in aggs:
vals: list = []
for t, c in rel.rows.items():
if tuple(t[i] for i in gpos) == k:
vals.extend([None if func == "count_star" else t[rel.index(attr)]] * c)
row.append(agg_value(func, vals))
out[tuple(row)] = 1
schema = group_attrs + tuple(o for _, _, o in aggs)
return Relation(schema, out, rel.mode)
# ---------------------------------------------------------------- evaluation
def evaluate(expr: tuple, db: Mapping[str, Relation], mode: str = BAG) -> Relation:
"""Evaluate an expression tree of nested tuples over db, in mode."""
if mode not in MODES:
raise ValueError("mode must be 'bag' or 'set'")
op = expr[0]
ev = lambda e: evaluate(e, db, mode)
if op == "scan":
return db[expr[1]].with_mode(mode)
if op == "select":
return select(ev(expr[2]), expr[1])
if op == "project":
return project(ev(expr[2]), expr[1])
if op == "rename":
return rename(ev(expr[2]), expr[1])
if op == "distinct":
return distinct(ev(expr[1]))
if op == "aggregate":
return aggregate(ev(expr[3]), expr[1], expr[2])
if op == "theta_join":
return theta_join(ev(expr[2]), ev(expr[3]), expr[1])
binary = {
"union": union, "difference": difference, "intersection": intersection,
"product": product, "join": natural_join, "semijoin": semijoin, "antijoin": antijoin,
}
if op in binary:
return binary[op](ev(expr[1]), ev(expr[2]))
raise ValueError("unknown operator %r" % (op,))
# ---------------------------------------------------------------- disk
def paginate(rows: Sequence, per_page: int) -> list:
"""Split rows into pages of per_page rows; the last page may be shorter."""
if per_page < 1:
raise ValueError("per_page must be at least 1")
rows = list(rows)
return [rows[i:i + per_page] for i in range(0, len(rows), per_page)]
class Disk:
"""Pages on a simulated disk. Each read_page and write_page call costs one I/O."""
def __init__(self) -> None:
self.pages: dict = {}
self.reads = 0
self.writes = 0
self._next = 0
def alloc(self) -> int:
pid = self._next
self._next += 1
self.pages[pid] = ()
return pid
def write_page(self, pid: int, rows: Iterable) -> None:
if pid not in self.pages:
raise KeyError("page %r was not allocated" % (pid,))
self.pages[pid] = tuple(rows)
self.writes += 1
def read_page(self, pid: int) -> list:
self.reads += 1
return list(self.pages[pid])
def free(self, pid: int) -> None:
del self.pages[pid]
def load(self, rows: Sequence, per_page: int) -> list:
"""Store an input file without counting I/O; return its page ids in order."""
ids = []
for page in paginate(rows, per_page):
pid = self.alloc()
self.pages[pid] = tuple(page)
ids.append(pid)
return ids
def io(self) -> int:
return self.reads + self.writes
def reset_counters(self) -> None:
self.reads = 0
self.writes = 0
# ---------------------------------------------------------------- random data
def random_relation(rng: random.Random, schema: Sequence[str], n: int,
domain: int | Sequence | Mapping = 4, mode: str = BAG,
null_rate: float = 0.0) -> Relation:
"""n rows drawn with rng. domain is a size k (values 0 to k - 1), a list of
values, or a dict from attribute to either. Each value is None with
probability null_rate. In set mode duplicates collapse, so there may be
fewer than n rows."""
schema = tuple(schema)
def values(a: str) -> list:
d = domain[a] if isinstance(domain, Mapping) else domain
return list(range(d)) if isinstance(d, int) else list(d)
doms = [values(a) for a in schema]
rows = []
for _ in range(n):
t = []
for d in doms:
if null_rate and rng.random() < null_rate:
t.append(None)
else:
t.append(rng.choice(d))
rows.append(tuple(t))
return Relation(schema, rows, mode)
radix_hash_join.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/radix-hash-join/. The authors are listed in prov/Y1EV4Y.jsonl.
"""Radix hash join: multi-pass radix clustering, then one small hash join per cluster.
A relation is a list of tuples, and the join key is the column r_col of R and
s_col of S. The hash of an integer key is h(k) = (k * 2654435761) mod 2^32.
The radix bits are the low b bits of h(k), where b = b_1 + ... + b_P and pass p
uses b_p of them, most significant first. After the last pass, cluster i holds
the tuples with h(k) mod 2^b = i, in their input order.
The join of cluster i of R with cluster i of S uses a bucket-chained hash table
(an array of bucket heads and an array of next links), indexed by the bits of h
above the low b bits, because the low b bits are equal inside a cluster.
An optional trace list records the memory addresses that the algorithm touches,
one per word, and count_misses runs them through a fully associative LRU cache.
"""
from collections import OrderedDict
from collections.abc import Sequence
MASK32 = (1 << 32) - 1
# Base addresses of the arrays in the traced address space.
BASE = {"x0": 0, "x1": 1 << 20, "count": 2 << 20, "r": 3 << 20, "s": 4 << 20, "head": 5 << 20, "next": 6 << 20}
def h(key: int) -> int:
"""Multiplicative hash of an integer key, 32 bits."""
return (key * 2654435761) & MASK32
def radix_cluster(rows: Sequence[tuple], col: int, passes: Sequence[int], trace: list | None = None):
"""Cluster rows on the low sum(passes) bits of h(row[col]).
Returns (out, bounds, moves): out is the clustered list, cluster i is
out[bounds[i]:bounds[i + 1]], and moves[p] is the number of tuples that
pass p copied.
"""
x = list(rows)
n = len(x)
b = sum(passes) # @line L1
clusters = [(0, n)]
moves = []
src, dst = "x0", "x1"
done = 0
for bp in passes: # @line L2
done += bp
shift = b - done # @line L3
fan = 1 << bp
y = [None] * n
new_clusters = []
moved = 0
for lo, hi in clusters: # @line L4
count = [0] * fan
for i in range(lo, hi):
j = (h(x[i][col]) >> shift) & (fan - 1)
count[j] += 1 # @line L5
if trace is not None:
trace += [BASE[src] + i, BASE["count"] + j]
start = [0] * fan
pos = lo
for j in range(fan):
start[j] = pos # @line L6
new_clusters.append((pos, pos + count[j]))
pos += count[j]
for i in range(lo, hi):
j = (h(x[i][col]) >> shift) & (fan - 1)
y[start[j]] = x[i] # @line L7
if trace is not None:
trace += [BASE[src] + i, BASE["count"] + j, BASE[dst] + start[j]]
start[j] += 1
moved += 1
x, clusters = y, new_clusters # @line L8
src, dst = dst, src
moves.append(moved)
bounds = [lo for lo, _ in clusters] + [n]
return x, bounds, moves # @line L9
def _pow2_at_least(m: int) -> int:
size = 1
while size < m:
size *= 2
return size
def radix_join(r_rows: Sequence[tuple], s_rows: Sequence[tuple], r_col: int, s_col: int,
passes: Sequence[int], trace: list | None = None):
"""Equi-join R and S on r[r_col] == s[s_col]. Output rows are r + s.
passes lists the radix bits per pass; an empty list gives the plain hash
join with one table on all of R. Returns (out, stats) with the moves of
each relation per pass and the number of key comparisons. A NULL key
(None) never matches, so those rows are dropped before the clustering.
"""
r_rows = [r for r in r_rows if r[r_col] is not None]
s_rows = [s for s in s_rows if s[s_col] is not None]
rc, rb, rmoves = radix_cluster(r_rows, r_col, passes) # @line L10
sc, sb, smoves = radix_cluster(s_rows, s_col, passes)
b = sum(passes)
out = []
compares = 0
for i in range(1 << b): # @line L11
rlo, rhi = rb[i], rb[i + 1]
slo, shi = sb[i], sb[i + 1]
if rlo == rhi or slo == shi:
continue
size = _pow2_at_least(rhi - rlo)
head = [-1] * size
nxt = [-1] * (rhi - rlo)
for t in range(rlo, rhi): # @line L12
j = (h(rc[t][r_col]) >> b) & (size - 1)
nxt[t - rlo] = head[j]
head[j] = t - rlo
if trace is not None:
trace += [BASE["r"] + t, BASE["head"] + j, BASE["next"] + t - rlo]
for u in range(slo, shi): # @line L13
s = sc[u]
j = (h(s[s_col]) >> b) & (size - 1)
t = head[j]
if trace is not None:
trace += [BASE["s"] + u, BASE["head"] + j]
while t != -1:
compares += 1
r = rc[rlo + t]
if trace is not None:
trace += [BASE["r"] + rlo + t, BASE["next"] + t]
if r[r_col] == s[s_col]:
out.append(r + s)
t = nxt[t]
stats = {"r_moves": rmoves, "s_moves": smoves, "compares": compares}
return out, stats # @line L14
def count_misses(trace: Sequence[int], lines: int, line_size: int) -> int:
"""Misses of a fully associative LRU cache with `lines` lines of `line_size` words."""
cache: OrderedDict = OrderedDict()
misses = 0
for addr in trace:
line = addr // line_size
if line in cache:
cache.move_to_end(line)
else:
misses += 1
cache[line] = None
if len(cache) > lines:
cache.popitem(last=False)
return misses
test_radix_hash_join.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/radix-hash-join/. The authors are listed in prov/Y1EV4Y.jsonl.
import random
from collections import Counter
from dbrel import Relation, evaluate
from radix_hash_join import count_misses, h, radix_cluster, radix_join
PASSES = ([], [1], [2], [1, 1], [3, 2], [2, 2, 2], [6])
def oracle(r_rows, s_rows):
"""The bag join by dbrel, with the columns in the order (k, a, k, b)."""
db = {"R": Relation(("k", "a"), r_rows), "S": Relation(("k", "b"), s_rows)}
res = evaluate(("join", ("scan", "R"), ("scan", "S")), db).reorder(("k", "a", "b"))
return Counter({(k, a, k, b): c for (k, a, b), c in res.rows.items()})
def test_example() -> None:
r = [(k, f"r{i}") for i, k in enumerate([3, 1, 4, 1, 5, 9, 2, 6])]
s = [(k, f"s{i}") for i, k in enumerate([1, 4, 1, 8, 5, 9])]
x, bounds, moves = radix_cluster(r, 0, [1, 1])
assert [t[1] for t in x] == ["r2", "r1", "r3", "r4", "r5", "r6", "r7", "r0"]
assert bounds == [0, 1, 5, 7, 8] and moves == [8, 8]
out, stats = radix_join(r, s, 0, 0, [1, 1])
assert Counter(out) == oracle(r, s) and len(out) == 7
assert stats["compares"] == 8
def test_cluster_property() -> None:
rng = random.Random(3)
for passes in PASSES:
rows = [(rng.randrange(50), i) for i in range(rng.randrange(0, 120))]
x, bounds, moves = radix_cluster(rows, 0, passes)
b = sum(passes)
assert len(bounds) == (1 << b) + 1 and Counter(x) == Counter(rows)
assert moves == [len(rows)] * len(passes)
for i in range(1 << b):
part = x[bounds[i]:bounds[i + 1]]
assert all(h(t[0]) % (1 << b) == i for t in part)
# The clustering is stable: the input order is kept inside a cluster.
assert [t[1] for t in part] == sorted(t[1] for t in part)
def test_random_against_oracle() -> None:
rng = random.Random(7)
for trial in range(60):
dom = rng.choice([3, 5, 40])
r = [(rng.randrange(dom), f"a{i}") for i in range(rng.randrange(0, 60))]
s = [(rng.randrange(dom), f"b{i}") for i in range(rng.randrange(0, 60))]
want = oracle(r, s)
for passes in PASSES:
out, _ = radix_join(r, s, 0, 0, passes)
assert Counter(out) == want
def test_edges_and_nulls() -> None:
assert radix_join([], [], 0, 0, [2])[0] == []
assert radix_join([(1, "x")], [], 0, 0, [2])[0] == []
same_r = [(7, i) for i in range(5)]
same_s = [(7, i) for i in range(4)]
out, _ = radix_join(same_r, same_s, 0, 0, [2, 1])
assert len(out) == 20
r = [(None, "x"), (1, "y"), (None, "z")]
s = [(None, "u"), (1, "v")]
out, _ = radix_join(r, s, 0, 0, [1])
assert out == [(1, "y", 1, "v")]
def test_cache_misses_in_lru_model() -> None:
# 200 tuples per input, a cache of 16 lines of 4 words.
rng = random.Random(1)
r = [(rng.randrange(1000), i) for i in range(200)]
s = [(rng.randrange(1000), i) for i in range(200)]
misses = {}
for passes in ([6], [3, 3]):
trace = []
radix_cluster(r, 0, passes, trace)
misses[tuple(passes)] = count_misses(trace, 16, 4)
assert misses[(6,)] == 472 and misses[(3, 3)] == 305
join_misses = {}
for passes in ([], [4], [3, 3]):
trace = []
radix_join(r, s, 0, 0, passes, trace)
join_misses[tuple(passes)] = count_misses(trace, 16, 4)
assert join_misses == {(): 808, (4,): 147, (3, 3): 105}
def test_lru_simulator() -> None:
assert count_misses([0, 1, 2, 3], 1, 4) == 1
assert count_misses([0, 4, 0, 4], 1, 4) == 4
assert count_misses([0, 4, 0, 4], 2, 4) == 2
assert count_misses([0, 4, 8, 0], 2, 4) == 4
History
Shatdal, Kant and Naughton (1994) studied cache-conscious algorithms for query processing and partitioned the hash join so that each part fits in the cache. Boncz, Manegold and Kersten (1999) showed that on the machines of that time a single-pass partitioning with many parts was limited by TLB misses, and they introduced the radix-cluster algorithm with several passes, each with a small fan-out, in the Monet system. Manegold, Boncz and Kersten (2002) gave detailed cost models of cache and TLB misses for these algorithms. Blanas, Li and Patel (2011) argued that a simple hash join without partitioning is competitive on multi-core machines, and Balkesen, Teubner, Alonso and Özsu (2013) showed that a radix join tuned to the hardware is faster in most of their measured cases.
References
- Cache conscious algorithms for relational query processing, the cache partitioning of the hash join (the partitions are sized to fit in the cache)
- Database architecture optimized for the new bottleneck: memory access, the radix-cluster algorithm with several passes and the partitioned hash join
- Stefan Manegold, Peter A. Boncz and Martin L. Kersten, Optimizing main-memory join on modern hardware, IEEE Transactions on Knowledge and Data Engineering 14(4), 2002, pages 709 to 730, the radix-cluster and partitioned hash join algorithms and their cost models of cache and TLB misses
- Cagri Balkesen, Jens Teubner, Gustavo Alonso and M. Tamer Özsu, Main-memory hash joins on multi-core CPUs: tuning to the underlying hardware, ICDE 2013, pages 362 to 373, the parallel radix join and its comparison with the no-partitioning hash join (measurements)
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 Y1EV4Y Edit this page History Report an error Markdown