Algorithm Search⌘K

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.

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
Properties
deterministicexactnot externalnot in placeofflineiterative
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 RR and SS in main memory, with nn and mm tuples, and the condition r.a=s.br.a = s.b. The output is the bag R⋈SR \bowtie S of the relational join problem: one tuple r⋅sr \cdot s for each matching pair, so a key that occurs xx times in RR and yy times in SS gives xyx y 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 MM words in lines of BB words. In the external memory model, the memory holds M/BM/B blocks; on this page the memory is the cache and a block is a cache line, so the cache holds M/BM/B lines. A tuple takes one word. The hash is h(k)=(k⋅2654435761) mod 232h(k) = (k \cdot 2654435761) \bmod 2^{32} on integer keys. Its low 4 bits are the low 4 bits of kk, because the multiplier is 1 modulo 16, so on small integers it acts like clustering on the key bits.

The algorithm

  1. RADIX-CLUSTER(X, h, b_1, ..., b_P) ▷ X is an array of n tuples
  2. 1b ← b_1 + ... + b_P; the clusters are [the whole of X]
  3. 2for p ← 1 to P do
  4. 3s ← b − (b_1 + ... + b_p) ▷ pass p uses bits s to s + b_p − 1 of h
  5. 4for each cluster C, in order do
  6. 5count[j] ← the number of x in C with digit (h(x.key) >> s) mod 2^b_p = j ▷ histogram
  7. 6start[j] ← start of C + count[0] + ... + count[j − 1] ▷ prefix sum
  8. 7for each x in C, in order: Y[start[j]] ← x and start[j] ← start[j] + 1, where j is the digit of x ▷ scatter
  9. 8X ← Y; the clusters are the pieces of all clusters, in order
  10. 9return X and the bounds of its 2^b clusters
  11. RADIX-JOIN(R, S, h, b_1, ..., b_P)
  12. 10cluster R and S with RADIX-CLUSTER(·, h, b_1, ..., b_P)
  13. 11for i ← 0 to 2^b − 1 do
  14. 12build a bucket-chained table on cluster i of R, indexed by the bits of h above bit b
  15. 13for 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
  16. 14return the output

Each pass is one step of an MSD radix sort on the low bb 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 bb bits, and each later pass splits each cluster again on the next bits, so after pass PP cluster ii holds the tuples with h(k) mod 2b=ih(k) \bmod 2^b = i. A pass with bpb_p bits writes to 2bp2^{b_p} 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 hh that the clustering did not use, because all tuples of a cluster share their low bb 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 bb: about log⁡2\log_2 of nn divided by the number of tuples that fit in the cache with their table.

Example

Let RR have the keys [3,1,4,1,5,9,2,6][3, 1, 4, 1, 5, 9, 2, 6] (tuples r0r_0 to r7r_7) and SS have the keys [1,4,1,8,5,9][1, 4, 1, 8, 5, 9] (s0s_0 to s5s_5). For these keys h(k) mod 4=k mod 4h(k) \bmod 4 = k \bmod 4. Take b=2b = 2 in two passes of one bit each.

step what happens to RR 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 [r1,r2,r3,r4,r5∣r0,r6,r7][r_1, r_2, r_3, r_4, r_5 \mid r_0, r_6, r_7]
pass 2, first cluster digit = bit 0: key 4 gives 0, keys 1, 1, 5, 9 give 1 [r2∣r1,r3,r4,r5][r_2 \mid r_1, r_3, r_4, r_5]
pass 2, second cluster keys 2, 6 give 0, key 3 gives 1 [r6,r7∣r0][r_6, r_7 \mid r_0]
L9 clusters 0 to 3 [r2∣r1,r3,r4,r5∣r6,r7∣r0][r_2 \mid r_1, r_3, r_4, r_5 \mid r_6, r_7 \mid r_0], bounds [0,1,5,7,8][0, 1, 5, 7, 8]

SS gives cluster 0 = [s1,s3][s_1, s_3] (keys 4 and 8) and cluster 1 = [s0,s2,s4,s5][s_0, s_2, s_4, s_5] (keys 1, 1, 5, 9); clusters 2 and 3 of SS are empty, so line L11 skips them. Cluster 0 gives r2⋅s1r_2 \cdot s_1, and s3s_3 finds only r2r_2 with key 4≠84 \ne 8 in its bucket. Cluster 1 gives 6 tuples: s0s_0 and s2s_2 each find r1r_1 and r3r_3, s4s_4 finds r4r_4 and s5s_5 finds r5r_5. The output has 7 tuples, the bag join, and the join phase makes 8 key comparisons. Each pass moved all 8 tuples of RR.

Simulated cache misses. The implementation can record every word it reads or writes and run the trace through a fully associative LRU cache. With n=m=200n = m = 200 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 RR on 6 bits in one pass (fan-out 64) 472
cluster RR on 6 bits in two passes of 3 bits (fan-out 8) 305
join phase without clustering (one table on all of RR) 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 RR 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 ii holds exactly the tuples with h(k) mod 2b=ih(k) \bmod 2^b = i: 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 RR and SS are bags and the join is the bag join: one copy of r⋅sr \cdot s for each pair of occurrences with r.a=s.br.a = s.b. Let b=b1+⋯+bPb = b_1 + \dots + b_P, let c(x)=h(x.key) mod 2bc(x) = h(x.\mathit{key}) \bmod 2^b be the cluster number of a tuple, and let sp=b−(b1+⋯+bp)s_p = b - (b_1 + \dots + b_p) be the shift of line L3 in pass pp, with s0=bs_0 = b.

Lemma 1 (one pass). Before pass pp, assume that XX is a permutation of the input and that it is cut into contiguous clusters, one for each value v<2b−sp−1v < 2^{b - s_{p-1}}, in increasing order of vv, where the cluster of vv holds the tuples with c(x)≫sp−1=vc(x) \gg s_{p-1} = v in input order. Then after pass pp, the same holds with sps_p in place of sp−1s_{p-1}.

Proof. Take one cluster CC with value vv (line L4). Its tuples have c(x)≫sp=v⋅2bp+jc(x) \gg s_p = v \cdot 2^{b_p} + j, where j=(h(x.key)≫sp) mod 2bpj = (h(x.\mathit{key}) \gg s_p) \bmod 2^{b_p} is the digit of line L5. Line L5 counts the tuples with each digit jj. Line L6 sets start[j]\mathit{start}[j] to the start of CC plus the number of tuples of CC with a smaller digit, so the ranges [start[j],start[j]+count[j])[\mathit{start}[j], \mathit{start}[j] + \mathit{count}[j]) for j=0,…,2bp−1j = 0, \dots, 2^{b_p} - 1 cut the range of CC into consecutive pieces in increasing order of jj. Line L7 visits CC in order and writes each tuple with digit jj to the next free place of piece jj. So piece jj receives exactly the tuples of CC with digit jj, in input order, and every place of the range of CC is written once. The pieces of CC have the values v⋅2bp+jv \cdot 2^{b_p} + j, which are increasing in jj and lie between the values of the pieces of the clusters before and after CC. Line L8 keeps this order. □\square

Lemma 2 (clustering). RADIX-CLUSTER returns a permutation of its input in which cluster ii, the range from bounds[i]\mathit{bounds}[i] to bounds[i+1]\mathit{bounds}[i+1], holds exactly the tuples xx with c(x)=ic(x) = i, in input order.

Proof. Before pass 1, s0=bs_0 = b, so c(x)≫b=0c(x) \gg b = 0 for every tuple, and the whole input is the single cluster of value 0. This is the hypothesis of Lemma 1 for p=1p = 1. By induction with Lemma 1, after pass PP the claim holds with sP=0s_P = 0, that is, with c(x)c(x) itself. □\square

Theorem 1 (correctness). RADIX-JOIN returns a list whose multiset of elements is R⋈SR \bowtie S (bag semantics, a NULL key never matches).

Proof. A pair (r,s)(r, s) with r.a=s.br.a = s.b has h(r.a)=h(s.b)h(r.a) = h(s.b), so c(r)=c(s)c(r) = c(s), and by Lemma 2 rr is in cluster i=c(r)i = c(r) of RR and ss in cluster ii of SS. 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 ii of RR once into a chained table: it prepends it to the chain of its bucket and never removes it. Line L13 meets each occurrence ss of cluster ii of SS once, walks the whole chain of the bucket of s.bs.b, which holds every occurrence of RiR_i with key s.bs.b (equal keys have equal hash and so equal bucket), and appends r⋅sr \cdot s exactly when r.a=s.br.a = s.b. So each matching pair gives exactly one output, and nothing else is appended. All loops run over finite ranges, so the algorithm stops. ■\blacksquare

Theorem 2 (work). In the word RAM, RADIX-CLUSTER does O(Pn+2b)O(P n + 2^b) steps on nn tuples. Under the simple uniform hashing assumption for the bucket bits (the bits of hh above the low bb bits), the expected work of RADIX-JOIN is O(P(n+m)+2b+T)O(P(n + m) + 2^b + T). Its worst case is O(P(n+m)+2b+nm)O(P(n + m) + 2^b + n m).

Proof. Pass pp handles each tuple twice (lines L5 and L7) and does O(2bp)O(2^{b_p}) work per cluster for lines L5 and L6. Before pass pp there are 2b1+⋯+bp−12^{b_1 + \dots + b_{p-1}} clusters, so the counters cost ∑p2b1+⋯+bp≤2⋅2b\sum_p 2^{b_1 + \dots + b_p} \le 2 \cdot 2^b in total. This gives O(Pn+2b)O(P n + 2^b). In the join phase, cluster ii gets a table with at least ∣Ri∣|R_i| buckets. A probe compares s.bs.b with the tuples of RiR_i in its bucket: those with key s.bs.b each give an output, and under the assumption each other key of RiR_i lands in the bucket with probability at most 1/∣Ri∣1/|R_i|, so the expected number of the other comparisons is at most 1 per probe. Summing over clusters gives O(n+m+T+2b)O(n + m + T + 2^b). In the worst case every probe walks a whole cluster, at most nmn m comparisons in total. ■\blacksquare

The cache model. We use the external memory model for the cache: the cache holds MM words in M/BM/B lines of BB 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 M/BM/B blocks; on this page the memory is the cache and a block is a cache line, so the cache holds M/BM/B lines. Each tuple takes one word.

Theorem 3 (cache misses). Assume that every pass has a fan-out Fp=2bpF_p = 2^{b_p} with Fp(1+1/B)+3≤M/BF_p (1 + 1/B) + 3 \le M/B, and that every cluster of RR satisfies 4∣Ri∣+3B≤M4|R_i| + 3B \le M. Then RADIX-JOIN has O(P(n+m)/B+(n+m+T)/B+2b)O(P(n + m)/B + (n + m + T)/B + 2^b) cache misses.

Proof. Take one cluster CC of size ∣C∣|C| in pass pp. Line L5 reads CC in order and updates FpF_p counters that fill Fp/B+1F_p / B + 1 lines: keep these lines and one input line, which costs ∣C∣/B+Fp/B+3|C|/B + F_p/B + 3 misses. Line L7 reads CC again in order and writes to FpF_p output places, each of which moves forward one word at a time. Keep one line for the input, one line for each of the FpF_p output cursors and the lines of the counters. By the assumption these fit. Each output cursor misses once at its start and once per BB words, so the writes cost at most ∣C∣/B+2Fp|C|/B + 2 F_p misses, and the reads ∣C∣/B+2|C|/B + 2. Summed over the clusters of pass pp, this is O(n/B+2b1+⋯+bp)O(n/B + 2^{b_1 + \dots + b_p}), and over all passes O(Pn/B+2b)O(P n / B + 2^b). The same holds for SS.

In the join phase, cluster ii needs its ∣Ri∣|R_i| tuples, its head array of fewer than 2∣Ri∣2|R_i| words and its next array of ∣Ri∣|R_i| words, at most 4∣Ri∣4|R_i| words, plus one line for SiS_i and one line for the output. By the assumption they fit, so line L12 costs O(∣Ri∣/B+1)O(|R_i|/B + 1) misses, and line L13 then misses only on the lines of SiS_i and of the output: O((∣Si∣+Ti)/B+1)O((|S_i| + T_i)/B + 1), where TiT_i is the output of the cluster. The sum over the 2b2^b clusters is O((n+m+T)/B+2b)O((n + m + T)/B + 2^b). ■\blacksquare

The second assumption depends on the data. With bb radix bits and no heavy key, the clusters of RR have about n/2bn / 2^b tuples, so bb is chosen near log⁡2(4n/M)\log_2 (4 n / M). A key that occurs more than M/4M/4 times makes a cluster that does not fit, whatever bb is.

Without partitioning. Let the plain hash join build one table of W>MW > M words on all of RR, 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 MM words of the table are in the cache, so the probe misses with probability at least 1−M/W1 - M/W. So the expected number of misses is at least m(1−M/W)m(1 - M/W), which is close to one miss per probe when W≫MW \gg M, against O(1/B)O(1/B) 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 M/BM/B shows why the fan-out FpF_p 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 O(2bp)O(2^{b_p}) work per cluster for the counters, so the clustering costs O(P(n+m)+2b)O(P(n + m) + 2^b) steps. Under the simple uniform hashing assumption for the bucket bits, the join phase does expected O(n+m+T)O(n + m + T) work. The worst case, when every key of a cluster shares one bucket, is O(nm)O(n m) 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 RR with its table fits in the cache, the radix join has O(P(n+m)/B+(n+m+T)/B+2b)O(P(n + m)/B + (n + m + T)/B + 2^b) 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 mm misses.
  • TLB misses. The same count with a memory page in place of a line and the number of TLB entries in place of M/BM/B 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 n+mn + m tuples and 2bp2^{b_p} 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 2b2^b is below the number of cache lines and TLB entries. With more clusters, two passes are usually used. Choosing PP and the bpb_p is a tuning decision on measured hardware.
  • Partition the build side only. Some systems cluster only RR and probe the clusters with an unclustered SS, 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 bb 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.

dbrel.pyI0RawGitHub
# 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

  1. Cache conscious algorithms for relational query processing, the cache partitioning of the hash join (the partitions are sized to fit in the cache)
  2. Database architecture optimized for the new bottleneck: memory access, the radix-cluster algorithm with several passes and the partitioned hash join
  3. 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
  4. 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.

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