Algorithmadvanced
XJoin
Also called XJoin algorithm.
A symmetric hash join for unreliable sources that spills partitions to disk and joins them while inputs are blocked.
- Solves
- Relational join problem
- Time
- O(n^2 h^2) worstO(n h + T h^2) averageO(n + T) best
- Space
- O(M) extra
- Where
- M = the memory limit in tuples; T = the number of output tuples; h = the number of stage 2 runs; n = the number of input tuples
- Model
- Word RAM
- Properties
- deterministicexactexternalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tolga Urhan, Michael J. Franklin, 2000
XJoin is a pipelined equi-join for inputs that arrive over a network at unpredictable rates and that may not fit in memory. It is a symmetric hash join whose two hash tables are split into partitions, as in the Grace hash join: when memory is full, a partition moves to disk, and the join of the disk parts is done later, partly while both inputs are blocked and partly at the end. The symmetric hash join has no such memory limit, and a hash join blocks until one input is complete. Timestamps on each tuple make sure that no result pair is emitted twice, although a pair can be met in memory, in a later disk run and again at the end.
In plain words
You are matching two piles of letters that the post brings in at random times. You keep two trays, each with a few slots, and you match a new letter with the letters in the other tray at once. When the trays are full, you put the contents of the fullest slot into a box in the cellar and write the time on each letter.
When no post comes for a while, you do not wait. You fetch one box from the cellar and match its letters with what is now in the trays. You note the time of this visit on the box. At the end of the day you match everything that is left. Before you write a match down, you check the times on both letters and on the box. They tell you if you have written this match down before.
The problem
The input is two relations and with the set of common attributes, delivered as a sequence of arrivals from either input. Between arrivals there can be long stalls. The output is the natural join on under bag semantics, as on the page relational join problem, with NULL keys never matching. Memory holds at most tuples. The join must emit results as early as it can, never emit a result twice, and emit all results by the end of both inputs.
There are three goals at once. A blocking join gives no early results. A plain symmetric hash join fails when memory is full. A join that spills to disk and joins the disk parts later can meet the same pair twice, once in memory before a spill and once from disk afterwards.
The algorithm
Both inputs are hashed into partitions on the join key with one hash function . Each partition of each input has a memory part and a disk part. Each stored tuple carries its arrival time and its departure time , the time at which it moved to disk, or while it is in memory. Each disk part keeps a history: the list of times at which stage 2 used it. One logical clock gives all times.
XJOIN(events, P, M) ▷ events: arrivals of R or S tuples, and "blocked" signals- 1
for each input X and partition p: mem[X][p] ← ∅; disk[X][p] ← ∅; hist[X][p] ← ∅; clock ← 0 - 2
for each event e, in order do - 3
clock ← clock + 1 - 4
if e is the arrival of tuple t on input X then ▷ stage 1 - 5
if t[J] has no NULL then p ← h(t[J]); t.ATS ← clock; t.DTS ← ∞; add t to mem[X][p] - 6
for each u in mem[Y][p] with u[J] = t[J] do emit (t, u) ▷ Y is the other input - 7
if memory holds more than M tuples then clock ← clock + 1; move the largest memory part to disk, with DTS ← clock - 8
else if e says that both inputs are blocked then ▷ stage 2 - 9
choose an input X and a partition p with disk[X][p] not empty; pt ← clock - 10
for each a in disk[X][p] and b in mem[Y][p] with a[J] = b[J] do - 11
if not DONE(a, b) then emit (a, b) - 12
append pt to hist[X][p] - 13
for each p, each a in mem[R][p] ∪ disk[R][p] and b in mem[S][p] ∪ disk[S][p] with a[J] = b[J] do ▷ stage 3 - 14
if not DONE(a, b) then emit (a, b) DONE(x, y) ▷ true if the pair was emitted before- 15
if x.ATS < y.DTS and y.ATS < x.DTS then return true ▷ both were in memory together - 16
for each (u, v) in ((x, y), (y, x)) and each pt in the history of the disk part of u do - 17
if u.DTS < pt and v.ATS < pt < v.DTS then return true ▷ u on disk and v in memory at pt return false
Stage 1 (lines L4 to L7) is the symmetric hash join on the memory parts. Stage 2 (lines L8 to L12) uses the time in which the join would otherwise wait: it reads one disk part and probes the memory part of the same partition of the other input. Stage 3 (lines L13 and L14) runs once both inputs have ended, and joins everything, in memory and on disk, that is not yet done.
The test of line L15 is exact for stage 1: two tuples met in memory if and only if their memory intervals overlap. The test of line L17 is exact for a stage 2 run at time : that run met exactly the pairs with one tuple already on disk and the other in memory at . So DONE needs no list of emitted pairs, only two numbers per tuple and one list per disk part.
Two choices are heuristics and do not affect correctness: which memory part goes to disk at line L7 (here the largest, which frees the most memory), and which disk part stage 2 uses at line L9 (here the largest). In the original operator, stage 2 also stops as soon as new input arrives, and it starts only when it is expected to produce enough new results. The code on this page runs one whole disk part for each "blocked" event.
Example
and join on , with one partition () and memory for tuples. All tuples have , so the join has results. tuples are named by , and tuples by .
| time | event | what happens | emitted |
|---|---|---|---|
| 1 | : 1 | memory {1} | none |
| 2 | : p | stage 1 meets 1 | (1, p) |
| 3 | : 2 | stage 1 meets p | (2, p) |
| 4, 5 | : 3 | stage 1 meets p; memory holds 4 tuples, so at time 5 the part {1, 2, 3} moves to disk with DTS 5 | (3, p) |
| 6 | blocked | stage 2: disk {1, 2, 3} against memory {p}. All three pairs pass line L15 (p.ATS = 2 < 5), so they are skipped. History of the disk part: [6] | none |
| 7 | : q | memory of is empty | none |
| 8 | blocked | stage 2: disk {1, 2, 3} against memory {p, q}. The pairs with q fail line L15 (q.ATS = 7 > 5) and the entry 6 (7 > 6). History: [6, 8] | (1, q), (2, q), (3, q) |
| 9 | : 4 | stage 1 meets p and q | (4, p), (4, q) |
| 10, 11 | : s | stage 1 meets 4; at time 11 the part {p, q, s} moves to disk with DTS 11 | (4, s) |
| 12 | end | stage 3: of the 12 pairs, only the pairs of s with 1, 2 and 3 pass no test (s.ATS = 10 is after DTS 5 and after both history entries) | (1, s), (2, s), (3, s) |
Stage 1 emits 6 results, stage 2 emits 3 and stage 3 emits 3, for 12 in total, each once. Six tuples go to disk. Without the tests of DONE, the stage 2 run at time 6 would emit (1, p), (2, p) and (3, p) a second time.
Correctness
The claim is that each result pair is emitted exactly once, and that every emitted tuple is a result of the inputs that have arrived. The clock gives distinct times to arrivals, moves to disk and stage 2 runs. A tuple is in memory exactly between its and its and never comes back from disk, so line L15 is true exactly for the pairs that stage 1 met, and line L17 for an entry is true exactly for the pairs that the run at met. These values do not change later. So DONE returns true exactly for pairs that were met before, each pair is emitted at its first meeting, and stage 3 emits the pairs that were never met. Memory never holds more than tuples after an event, because a move frees at least one tuple. The full proof is in the proof page.
Proof: XJoin emits every result pair exactly once, within its memory limitfull
We use the line numbers of the pseudocode on the page. The inputs are and with the set of common attributes, under bag semantics: every arrival is a separate occurrence. A pair is with an occurrence of , an occurrence of , , and no NULL in the key. The join has one result for each pair. A tuple with a NULL key is dropped at line L5 and is in no pair, so we only consider the other tuples. Two tuples with the same key are in the same partition , so all statements below are about one partition .
Clock. Line L3 advances the clock once for each event, and a move to disk at line L7 advances it once more before it sets the departure times. So the arrival time of each tuple, the time of each move to disk and the time of each stage 2 run are distinct integers, and the clock only grows. A tuple has until its part moves to disk; then is the time of the move. Every tuple satisfies .
Lemma 1 (place of a tuple). At a clock time that is not the arrival time of , a tuple that has arrived is in memory if and only if , and on disk if and only if . No tuple goes back from disk to memory.
Proof. Line L5 puts into memory at time . Only line L7 moves tuples, always from memory to disk, and it sets to the time of the move. Stages 2 and 3 read the disk parts but do not move them back.
We say that a pair is met in stage 1 if one of its tuples finds the other in memory at line L6, and met at if the stage 2 run at time examines it at line L10, so that one of its tuples is in the chosen disk part and the other is in the memory part of the other input.
Lemma 2 (stage 1). A pair is met in stage 1 if and only if and , the test of line L15. If it is met, it is met once, at the arrival of the later tuple.
Proof. Line L6 runs only at an arrival and probes only the other input, so the pair can be met only at the arrival of its later tuple, say , with . It is met if and only if is in memory at that moment, which by Lemma 1 means . The other inequality, , then holds anyway. If arrives later, exchange the roles.
Lemma 3 (stage 2). Let the stage 2 run at time use the disk part of input in partition , and let be the other input. A pair with from and from is met at if and only if and . This is the test of lines L16 and L17 for the entry of the history of .
Proof. Line L10 pairs exactly the tuples on disk in with the tuples in memory in at time . Apply Lemma 1 with , which is not an arrival time.
Lemma 4 (the tests are stable). Once both tuples of a pair have arrived, the value of the stage 1 test never changes. For an entry of a history, the value of its stage 2 test never changes after time .
Proof. The tests read only , which is fixed at arrival, and , which changes once, from to the time of a move. In the stage 1 test, if when arrives, the later value is larger than the current clock, so still holds. In the stage 2 test, if at time , a later move gives again. A finite never changes.
Lemma 5 (DONE). When DONE is called at time , it returns true if and only if the pair was met in stage 1 or at some .
Proof. The history of holds the times of the earlier stage 2 runs on that part, because line L12 appends after the run at ends. By Lemmas 2, 3 and 4, the tests of lines L15 to L17 evaluated at time have the same values that they had when each meeting could happen.
Theorem 1 (exactly once). At the end of stage 3, every pair has been emitted exactly once, and nothing else has been emitted. So the output is as a bag.
Proof. Every emission is of a pair, because lines L6, L10 and L13 compare the keys. Take a pair and look at the events that meet it, in clock order.
If it is met in stage 1, this is its first meeting: before the arrival of its later tuple, the pair cannot be met at all. Line L6 emits it without a test. Each later stage 2 run that meets it calls DONE, which returns true by Lemma 5, so line L11 does not emit it again, and stage 3 skips it for the same reason.
If it is not met in stage 1 but is met in stage 2, let be the first run that meets it. At , DONE returns false by Lemma 5, so line L11 emits it. Every later run and stage 3 call DONE after , which returns true.
If it is never met before stage 3, DONE returns false in stage 3, and line L14 emits it. Line L13 examines it, because it pairs all tuples of and in partition , in memory or on disk. Stage 3 examines each pair once.
In all three cases the pair is emitted exactly once.
Corollary 1 (safe early output). After each event, the bag of tuples emitted so far is a sub-bag of , the join of the inputs that have arrived.
Proof. Every emitted tuple comes from a pair of arrived tuples, and by Theorem 1 no pair is emitted twice.
Theorem 2 (memory). After each event, memory holds at most tuples.
Proof. Only line L5 adds a tuple to memory, one per event. If memory then holds tuples, line L7 moves the largest memory part to disk. That part holds at least one tuple, because memory is not empty, so at most tuples remain.
Termination. Every event does a finite amount of work, and stage 3 pairs finitely many tuples. The history of a part grows by one entry per stage 2 run, so each call of DONE is finite.
What the heuristics change. The choice of the part to move at line L7 and of the part to use at line L9 does not occur in any proof above. A different choice changes when each result appears and how many disk reads are needed, but not the final output.
Complexity
The costs are in the word RAM model, with input tuples, results, stage 2 runs and expected hash table operations. A real system would also count the disk part reads in pages, as in the external memory model.
- Stage 1 costs expected per arriving tuple, where is the number of results it emits, as in the symmetric hash join. A move to disk writes each tuple at most once, so all moves together write at most tuples.
- Stage 2 reads one disk part per run, at most tuples, so all runs read tuples. Each pair that a run meets costs one call of DONE.
- DONE costs , where is the length of the history of the part. A pair can be met at most times: in stage 1, in stage 2 runs and in stage 3. So the expected total is . With no overflow, nothing goes to disk, every history is empty, and the cost is . The worst case, when all keys collide in one bucket, is .
- Memory is at most tuples plus the history lists. Disk holds at most tuples.
These are worst case bounds over the arrival order, in expectation over the hash function. They are not amortized.
Properties
- Pipelined. Stage 1 emits results as fast as a symmetric hash join while memory lasts.
- Reactive. Stage 2 runs only when both inputs are blocked, so the time that a remote source stalls is used to produce results.
- Exact under bag semantics. Every result is emitted once, even with duplicate tuples, because DONE is about occurrences, not values.
- Bounded memory. At most tuples in memory after each event. A plain symmetric hash join needs all .
- Order of results. The final output does not depend on the heuristics or on the arrival order, but the time at which each result appears does.
Variants and improvements
- Tukwila. Ives et al. (1999) used a symmetric hash join in the Tukwila data integration system and gave strategies for memory overflow that move partitions of one or both inputs to disk. XJoin adds the use of blocked time and the timestamp test.
- Choice of the part to move and to read. The policies at lines L7 and L9 are heuristics. Any other policy keeps the output correct, because the proof does not use them, so a system can tune them to its workload.
- Windows. On unbounded streams, the sliding window join drops expired tuples instead of moving them to disk.
- Outside streams. XJoin is a general pipelined join for any plan with slow or bursty inputs, such as federated and distributed queries. It also gives early results for online aggregation and adaptive plans such as eddies.
When to use it
Use it for an equi-join of two inputs that arrive slowly or in bursts, when the user wants early results and the inputs may not fit in memory. If both inputs are on local disk, a Grace hash join or a hybrid hash join does less work. If both inputs fit in memory, a symmetric hash join is simpler.
Pitfalls
- Duplicates. A pair met in memory can be met again when its tuples are on disk. A test that checks only the stage (for example, "stage 3 joins only disk with disk") misses pairs or repeats them. Use the timestamps of both tuples and the history of the disk part.
- Equal times. The tests need strict inequalities between distinct times. If a move to disk shares its time with the arrival that caused it, a pair met at that arrival can fail line L15. The pseudocode gives the move its own clock tick.
- Stage 2 too often. Reading a whole disk part to find few new results wastes I/O. The original operator uses a threshold before it starts stage 2, which is a heuristic.
- Late data. XJoin has no windows and no watermarks: it waits for the end of both inputs, so a tuple that arrives late is still joined with everything. It handles delayed input, not out-of-order event times. A windowed stream join must decide separately how long to keep tuples for late data.
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)
xjoin.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/xjoin/. The authors are listed in prov/NRZ4EB.jsonl.
"""XJoin: a pipelined hash join with a memory limit, run as a one-thread simulation.
Both inputs are hashed into P partitions on the join key. Each partition of
each input has a part in memory and a part on disk. Memory holds at most M
tuples in total.
Stage 1 runs on each arrival: insert into the memory part of the own
partition and probe the memory part of the same partition of the other input.
When memory holds more than M tuples, the largest memory part (this choice is
a heuristic of this implementation) moves to disk.
Stage 2 runs when the driver reports that both inputs are blocked: the disk
part of one partition is joined with the memory part of the same partition of
the other input.
Stage 3 runs at the end of the input and joins everything that is left.
Duplicates are avoided with timestamps from one logical clock. Each tuple has
an arrival time ATS and a departure time DTS (when it moved to disk, or
infinity). Each disk part keeps the list of the times at which stage 2 used
it. DONE(a, b) decides from these alone whether a pair was already emitted.
Events are ("R", t), ("S", t) and ("block",). The join is the natural join
on the common attributes, under bag semantics; a NULL key never matches.
"""
import zlib
from collections.abc import Iterable, Sequence
R = "R"
S = "S"
BLOCK = "block"
INF = float("inf")
OTHER = {R: S, S: R}
class Rec:
"""One stored occurrence of a tuple with its timestamps."""
__slots__ = ("t", "key", "ats", "dts", "side")
def __init__(self, t: tuple, key: tuple, ats: int, side: str) -> None:
self.t = t
self.key = key
self.ats = ats
self.dts = INF
self.side = side
class XJoin:
def __init__(self, schema_r: Sequence[str], schema_s: Sequence[str],
partitions: int = 4, memory: int = 8, avoid_duplicates: bool = True) -> None:
if partitions < 1 or memory < 1:
raise ValueError("partitions and memory must be at least 1")
self.schema = {R: tuple(schema_r), S: tuple(schema_s)}
self.common = tuple(a for a in self.schema[R] if a in self.schema[S])
self.key_pos = {x: [self.schema[x].index(a) for a in self.common] for x in (R, S)}
self.rest_pos = [i for i, a in enumerate(self.schema[S]) if a not in self.common]
self.P = partitions
self.M = memory
self.avoid_duplicates = avoid_duplicates
self.mem = {x: [[] for _ in range(partitions)] for x in (R, S)} # @line L1
self.disk = {x: [[] for _ in range(partitions)] for x in (R, S)}
self.hist = {x: [[] for _ in range(partitions)] for x in (R, S)}
self.clock = 0
self.in_memory = 0
self.stats = {"stage1": 0, "stage2": 0, "stage3": 0, "disk_writes": 0, "disk_reads": 0}
# ------------------------------------------------------------ helpers
def part(self, key: tuple) -> int:
"""A stable hash of the key, independent of Python hash randomization."""
return zlib.crc32(repr(key).encode()) % self.P
def _combine(self, a: Rec, b: Rec) -> tuple:
r, s = (a, b) if a.side == R else (b, a)
return r.t + tuple(s.t[i] for i in self.rest_pos)
def done(self, a: Rec, b: Rec, p: int) -> bool:
"""True if the pair (a, b) was emitted before, by stage 1 or stage 2."""
if not self.avoid_duplicates:
return False
if a.ats < b.dts and b.ats < a.dts: # @line L15
return True
for x, y in ((a, b), (b, a)): # @line L16
for pt in self.hist[x.side][p]: # @line L17
if x.dts < pt and y.ats < pt < y.dts:
return True
return False
def _flush_largest(self) -> None:
sizes = [(len(self.mem[x][p]), x == S, p, x) for x in (R, S) for p in range(self.P)]
size, _, p, x = max(sizes, key=lambda v: (v[0], not v[1], -v[2]))
self.clock += 1
for rec in self.mem[x][p]:
rec.dts = self.clock
self.disk[x][p].extend(self.mem[x][p])
self.stats["disk_writes"] += size
self.in_memory -= size
self.mem[x][p] = []
# ------------------------------------------------------------ stages
def arrive(self, side: str, t: Sequence) -> list[tuple]:
"""Stage 1 for one arriving tuple. Returns the tuples it emits."""
t = tuple(t)
self.clock += 1 # @line L3
key = tuple(t[i] for i in self.key_pos[side])
if any(v is None for v in key):
return []
p = self.part(key)
rec = Rec(t, key, self.clock, side) # @line L5
self.mem[side][p].append(rec)
self.in_memory += 1
out = []
for u in self.mem[OTHER[side]][p]: # @line L6
if u.key == key:
out.append(self._combine(rec, u))
self.stats["stage1"] += len(out)
if self.in_memory > self.M: # @line L7
self._flush_largest()
return out
def blocked(self) -> list[tuple]:
"""Stage 2: both inputs are blocked. Join one disk part with memory."""
self.clock += 1
choices = [(len(self.disk[x][p]), x == R, -p, x, p)
for x in (R, S) for p in range(self.P) if self.disk[x][p]]
if not choices:
return []
_, _, _, x, p = max(choices) # @line L9
pt = self.clock
y = OTHER[x]
self.stats["disk_reads"] += len(self.disk[x][p])
out = []
for a in self.disk[x][p]: # @line L10
for b in self.mem[y][p]:
if a.key == b.key and not self.done(a, b, p): # @line L11
out.append(self._combine(a, b))
self.hist[x][p].append(pt) # @line L12
self.stats["stage2"] += len(out)
return out
def finish(self) -> list[tuple]:
"""Stage 3: the input has ended. Emit every pair that is not yet done."""
self.clock += 1
out = []
for p in range(self.P): # @line L13
left = self.mem[R][p] + self.disk[R][p]
right = self.mem[S][p] + self.disk[S][p]
self.stats["disk_reads"] += len(self.disk[R][p]) + len(self.disk[S][p])
for a in left:
for b in right:
if a.key == b.key and not self.done(a, b, p): # @line L14
out.append(self._combine(a, b))
self.stats["stage3"] += len(out)
return out
def xjoin(schema_r: Sequence[str], schema_s: Sequence[str], events: Iterable[tuple],
partitions: int = 4, memory: int = 8, avoid_duplicates: bool = True):
"""Run XJoin over the events. Returns (outputs per event plus a final entry for stage 3, join)."""
j = XJoin(schema_r, schema_s, partitions, memory, avoid_duplicates)
steps = []
for e in events: # @line L2
if e[0] == BLOCK: # @line L8
steps.append(j.blocked())
else: # @line L4
steps.append(j.arrive(e[0], e[1]))
steps.append(j.finish())
return steps, j
test_xjoin.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/xjoin/. The authors are listed in prov/NRZ4EB.jsonl.
import random
from collections import Counter
import dbrel
from xjoin import BLOCK, R, S, XJoin, xjoin
def oracle(schema_r, schema_s, r_rows, s_rows):
return dbrel.natural_join(dbrel.Relation(schema_r, r_rows), dbrel.Relation(schema_s, s_rows)).rows
def sub_bag(a: Counter, b: Counter) -> bool:
return all(b[t] >= c for t, c in a.items())
def random_events(rng, r_rows, s_rows, p_block):
tags = [R] * len(r_rows) + [S] * len(s_rows)
rng.shuffle(tags)
it = {R: iter(r_rows), S: iter(s_rows)}
events = []
for side in tags:
if rng.random() < p_block:
events.append((BLOCK,))
events.append((side, next(it[side])))
return events
def run_and_check(schema_r, schema_s, events, partitions, memory):
j = XJoin(schema_r, schema_s, partitions, memory)
seen = {R: [], S: []}
out = Counter()
for e in events:
if e[0] == BLOCK:
out.update(j.blocked())
else:
out.update(j.arrive(e[0], e[1]))
seen[e[0]].append(tuple(e[1]))
# Never a tuple that is not in the join of the prefixes, never twice.
assert sub_bag(out, oracle(schema_r, schema_s, seen[R], seen[S]))
assert j.in_memory <= memory
out.update(j.finish())
assert out == oracle(schema_r, schema_s, seen[R], seen[S])
return j, out
def test_page_example() -> None:
events = [(R, (1, 10)), (S, (10, "p")), (R, (2, 10)), (R, (3, 10)), (BLOCK,),
(S, (10, "q")), (BLOCK,), (R, (4, 10)), (S, (10, "s"))]
steps, j = xjoin(("A", "B"), ("B", "C"), events, partitions=1, memory=3)
assert [len(x) for x in steps] == [0, 1, 1, 1, 0, 0, 3, 2, 1, 3]
assert j.stats == {"stage1": 6, "stage2": 3, "stage3": 3, "disk_writes": 6, "disk_reads": 12}
assert steps[-1] == [(1, 10, "s"), (2, 10, "s"), (3, 10, "s")]
assert [r.dts for r in j.disk[R][0]] == [5, 5, 5] and j.hist[R][0] == [6, 8]
run_and_check(("A", "B"), ("B", "C"), events, 1, 3)
def test_large_memory_is_symmetric_hash_join() -> None:
rng = random.Random(3)
r_rows = dbrel.random_relation(rng, ("A", "B"), 20, 3).sorted_rows()
s_rows = dbrel.random_relation(rng, ("B", "C"), 20, 3).sorted_rows()
events = random_events(rng, r_rows, s_rows, 0.0)
j = XJoin(("A", "B"), ("B", "C"), 3, 1000)
seen = {R: [], S: []}
out = Counter()
for e in events:
out.update(j.arrive(e[0], e[1]))
seen[e[0]].append(e[1])
assert out == oracle(("A", "B"), ("B", "C"), seen[R], seen[S])
assert j.finish() == [] and j.stats["disk_writes"] == 0
def test_hand_cases() -> None:
# Empty input, one tuple, NULL keys, and all tuples with one key under tiny memory.
assert xjoin(("A", "B"), ("B", "C"), [])[0] == [[]]
assert xjoin(("A", "B"), ("B", "C"), [(R, (1, 2))])[0] == [[], []]
run_and_check(("A", "B"), ("B", "C"), [(R, (1, None)), (S, (None, 1)), (BLOCK,)], 2, 1)
events = [(R, (i, 0)) for i in range(5)] + [(BLOCK,)] + [(S, (0, k)) for k in range(4)] + [(BLOCK,)] * 3
j, out = run_and_check(("A", "B"), ("B", "C"), events, 2, 2)
assert sum(out.values()) == 20
def test_random_runs() -> None:
schemas = [(("A", "B"), ("B", "C")), (("A", "B", "C"), ("B", "C", "D")), (("A",), ("A",))]
used = Counter()
for seed in range(80):
rng = random.Random(seed)
schema_r, schema_s = schemas[seed % len(schemas)]
r_rows = dbrel.random_relation(rng, schema_r, rng.randrange(0, 22), 3, null_rate=0.05).sorted_rows()
s_rows = dbrel.random_relation(rng, schema_s, rng.randrange(0, 22), 3, null_rate=0.05).sorted_rows()
rng.shuffle(r_rows)
rng.shuffle(s_rows)
events = random_events(rng, r_rows, s_rows, rng.choice([0.0, 0.2, 0.5]))
j, _ = run_and_check(schema_r, schema_s, events, rng.randrange(1, 5), rng.randrange(1, 10))
for stage in ("stage1", "stage2", "stage3"):
used[stage] += j.stats[stage] > 0
# The random runs exercise all three stages.
assert all(used[s] > 10 for s in ("stage1", "stage2", "stage3"))
def test_without_timestamps_pairs_repeat() -> None:
# The duplicate test is needed: without it some pair is emitted twice.
repeated = 0
for seed in range(30):
rng = random.Random(seed)
r_rows = dbrel.random_relation(rng, ("A", "B"), 15, 3).sorted_rows()
s_rows = dbrel.random_relation(rng, ("B", "C"), 15, 3).sorted_rows()
events = random_events(rng, r_rows, s_rows, 0.3)
steps, _ = xjoin(("A", "B"), ("B", "C"), events, 2, 4, avoid_duplicates=False)
out = Counter(t for x in steps for t in x)
assert sub_bag(oracle(("A", "B"), ("B", "C"), r_rows, s_rows), out)
repeated += out != oracle(("A", "B"), ("B", "C"), r_rows, s_rows)
assert repeated > 20
History
Urhan and Franklin designed XJoin for queries over remote sources on a wide-area network, where the delays of a source are not known in advance and a source can stall for a long time. Their Data Engineering Bulletin paper of 2000 gives the three stages and the timestamp method. XJoin builds on the symmetric hash join of Wilschut and Apers (1991) and on the Tukwila work of Ives et al. (1999), which used a symmetric hash join for data integration and dealt with memory overflow.
References
- XJoin: a reactively-scheduled pipelined join operator, the three stages of XJoin, the arrival and departure timestamps, and the history list of stage 2 runs for duplicate avoidance
- An adaptive query execution system for data integration, the pipelined hash join of the Tukwila system and its strategies for memory overflow, the closest earlier design (the page numbers are not confirmed here)
- Dataflow query execution in a parallel main-memory environment, the pipelining hash-join that XJoin extends (the page numbers are not confirmed here)
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 NRZ4EB Edit this page History Report an error Markdown