Algorithm Search⌘K

Algorithmcore

Symmetric hash join

Also called pipelined hash join, double pipelined hash join.

Keep a hash table for each input; each arriving tuple is inserted in its own table and probes the other, producing results at once.

Time
O(n^2) worstO(n + T) average · best
Space
O(n) extra
Where
T = the number of output tuples so far; n = the number of tuples that have arrived from both inputs
Properties
deterministicexactnot externalnot in placeonlineiterative
Origin
Annita N. Wilschut, Peter M. G. Apers, 1991

The symmetric hash join computes the equi-join of two inputs RR and SS while both inputs are still arriving. It keeps one hash table on the join key for each input: an arriving tuple goes into the table of its own input and then probes the table of the other input, so each result is emitted as soon as its second tuple arrives. The classic hash join is different: it must read all of its build input before it can emit the first result, but it keeps only one table. The sliding window join is the same scheme with tuples that expire, and XJoin extends it to inputs that do not fit in memory.

In plain words

Two people read out names from two lists, one name at a time, in any order and at any speed. You keep two card boxes, one for each list. When you hear a name from the first list, you file a card for it in the first box, and then you look in the second box for cards with the same name. Each card that you find there is a match, and you call it out at once.

You never wait for a list to end. A match is called out at the moment that its second name is read. The cost is that you keep a card for every name you have heard, from both lists, because a name that comes later can match any of them.

The problem

The input is two relations RR and SS with the set JJ of common attributes, delivered as one sequence of arrivals. Each arrival is a tuple of RR or a tuple of SS, and the order and timing of the arrivals are not under the control of the join. The output is the natural join R⋈SR \bowtie S on JJ, as on the page relational join problem, under bag semantics: each pair of matching occurrences gives one output tuple. A NULL in a join attribute never matches, as in SQL.

The join must be pipelined: after each arrival, the output so far must be the join of the inputs seen so far. This matters when the inputs come over a slow network, when another pipelined operator produces them, or when a user wants the first answers early. A blocking join cannot do this, and the iterator model page and the page on pipelining and materialization explain why a hash join blocks on its build input.

The algorithm

  1. SYMMETRIC-HASH-JOIN(arrivals) ▷ each arrival is (side, t) with side R or S
  2. 1H_R ← an empty hash table; H_S ← an empty hash table
  3. 2for each arrival (side, t), in arrival order do
  4. 3(own, other) ← (H_R, H_S) if side = R, else (H_S, H_R)
  5. 4k ← t[J] ▷ the values of the join attributes
  6. 5if some value of k is NULL then go to the next arrival ▷ it can never match
  7. 6insert t into own under the key k
  8. 7for each tuple u in the bucket of k in other with u[J] = k do
  9. 8emit the combination of t and u

Line L6 inserts before line L7 probes, but the order of the two lines does not matter: the probe looks at the other table, and the tuple is put in its own table. Line L5 drops a tuple with a NULL key at once. An outer join could not do this, because it must still output such a tuple padded with NULLs.

The two inputs play the same role, which gives the join its name. There is no build phase and no probe phase. Every tuple is first a build tuple, for the tuples that come later from the other side, and then a probe tuple, for the tuples that came earlier.

Example

R(A,B)R(A, B) and S(B,C)S(B, C) join on BB. The arrivals come in this order.

step arrival stored in probes output of the step
1 RR: (1, 10) HRH_R HSH_S, empty none
2 SS: (10, p) HSH_S HRH_R, bucket 10 (1, 10, p)
3 RR: (2, 20) HRH_R HSH_S, bucket 20 empty none
4 SS: (10, q) HSH_S HRH_R, bucket 10 (1, 10, q)
5 RR: (3, 10) HRH_R HSH_S, bucket 10 (3, 10, p), (3, 10, q)
6 SS: (20, r) HSH_S HRH_R, bucket 20 (2, 20, r)

The steps emit 0, 1, 0, 1, 2 and 1 tuples, 5 in total, which is R⋈SR \bowtie S. After step 6 the tables hold all 6 tuples. A classic hash join with RR as the build input must read all of RR first, so it can emit nothing before step 5, when the last tuple of RR arrives.

Correctness

The claim is that after each arrival, the bag of emitted tuples equals Rj⋈SjR_j \bowtie S_j, the join of the first jj arrivals. Lines L6 and L1 keep the invariant that each table holds exactly the tuples of its input seen so far with a key free of NULL. When a tuple tt of RR arrives, the join grows by exactly {t}⋈Sj−1\{t\} \bowtie S_{j-1}, because the bag join distributes over the union of bags, and this is what lines L7 and L8 emit. So every pair is emitted exactly once, at the arrival of the later of its two tuples, which is the earliest possible moment. The full proof is in the proof page.

Proof: The symmetric hash join emits the join of the prefixes, each pair oncefull

We use the line numbers of the pseudocode. The inputs are relations RR and SS with the set JJ of common attributes. We use bag semantics: every arriving tuple is a separate occurrence, and the join X⋈YX \bowtie Y of two bags holds one copy of the combined tuple r⋅sr \cdot s for each pair of occurrences r∈Xr \in X, s∈Ys \in Y with r[J]=s[J]r[J] = s[J] and no NULL in r[J]r[J] or s[J]s[J]. This is the SQL rule: NULL never matches.

The arrivals are a1,a2,…a_1, a_2, \dots. Let RjR_j and SjS_j be the bags of occurrences of RR and SS among a1,…,aja_1, \dots, a_j, and let OjO_j be the bag of tuples emitted by the first jj iterations of line L2. A tuple is storable if its key has no NULL.

Lemma 1 (tables). After iteration jj, HRH_R holds exactly the storable occurrences of RjR_j, each once, under their keys, and HSH_S holds exactly the storable occurrences of SjS_j.

Proof. By induction on jj. Before the first iteration both tables are empty (line L1). Iteration jj changes only the table of the side of aja_j, and only at line L6, which runs if and only if aja_j is storable (line L5). It appends aja_j to the bucket of its key and never removes an entry. □\square

Lemma 2 (one step). If aj=ta_j = t is an occurrence of RR, iteration jj emits exactly the bag {t}⋈Sj−1\{t\} \bowtie S_{j-1}. If aja_j is an occurrence of SS, it emits Rj−1⋈{t}R_{j-1} \bowtie \{t\}.

Proof. Take aj=ta_j = t in RR; the other case is symmetric. If tt is not storable, line L5 skips it and nothing is emitted; also {t}⋈Sj−1\{t\} \bowtie S_{j-1} is empty, because a NULL in t[J]t[J] matches nothing. Otherwise line L6 inserts tt into HRH_R, which does not change HSH_S. By Lemma 1 for j−1j - 1, the bucket of k=t[J]k = t[J] in HSH_S holds exactly the storable occurrences uu of Sj−1S_{j-1} with u[J]=ku[J] = k, each once. These are exactly the occurrences of Sj−1S_{j-1} that join with tt, because an occurrence that is not storable joins with nothing. Lines L7 and L8 emit t⋅ut \cdot u once for each of them. □\square

Theorem 1 (correctness). For every j≥0j \ge 0, Oj=Rj⋈SjO_j = R_j \bowtie S_j as bags.

Proof. By induction on jj. For j=0j = 0 both sides are empty. Suppose Oj−1=Rj−1⋈Sj−1O_{j-1} = R_{j-1} \bowtie S_{j-1} and aj=ta_j = t is in RR. Then Rj=Rj−1+{t}R_j = R_{j-1} + \{t\} and Sj=Sj−1S_j = S_{j-1}. The bag join distributes over the sum of bags:

Rj⋈Sj=(Rj−1⋈Sj−1)+({t}⋈Sj−1).R_j \bowtie S_j = (R_{j-1} \bowtie S_{j-1}) + (\{t\} \bowtie S_{j-1}).

By the induction hypothesis and Lemma 2, the right side is Oj−1O_{j-1} plus the tuples of iteration jj, which is OjO_j. The case aj∈Sa_j \in S is the same with the roles exchanged. ■\blacksquare

Corollary 1 (each pair once, at the earliest time). Let rr be the ii-th arrival and ss the jj-th arrival, with r∈Rr \in R, s∈Ss \in S and r[J]=s[J]r[J] = s[J] free of NULL. Then r⋅sr \cdot s is emitted for this pair exactly once, in iteration max⁡(i,j)\max(i, j).

Proof. If i<ji < j, the pair is in Rj−1⋈{s}R_{j-1} \bowtie \{s\}, which iteration jj emits by Lemma 2, and in no earlier iteration, because ss has not arrived. Later iterations emit only pairs that contain their own arriving tuple. The case j<ij < i is symmetric. No algorithm that reads the inputs in this order can emit the pair before iteration max⁡(i,j)\max(i, j), since one of the two tuples is not yet known. □\square

Termination. Each iteration does a finite amount of work, because a bucket holds at most the number of earlier arrivals. So the join stops after a finite input, and for an infinite input each iteration ends.

Theorem 2 (memory). After iteration jj, the tables hold exactly the storable occurrences among a1,…,aja_1, \dots, a_j, at most jj tuples. With no NULL keys, this is exactly jj.

Proof. This is Lemma 1. ■\blacksquare

The memory bound is tight for an unbounded join: if every later tuple can match any stored tuple, no stored tuple can be dropped without losing output. A window or a punctuation that says that a key will not occur again is the only way to drop tuples, and then the join computes a different result, the window join.

Complexity

The costs are per arriving tuple, in the word RAM model, with nn the number of tuples that have arrived from both inputs.

  • Time. With a hash table of expected O(1)O(1) time per insertion and per bucket lookup, an arrival costs expected O(1+m)O(1 + m), where mm is the number of results it emits. Over nn arrivals the expected total is O(n+T)O(n + T) for TT results, which is optimal because each result must be written. This bound is in expectation over the hash function, not amortized. In the worst case, when all keys collide in one bucket, a probe compares with all stored tuples of the other side, and the total is O(n2)O(n^2) comparisons.
  • Memory. All nn tuples, minus those with NULL keys. A classic hash join keeps only the smaller input. An unbounded join cannot keep less in general, because a stored tuple can match any later tuple (see the end of the proof page).
  • With a window. If each input keeps only its last WW tuples, the memory is at most 2W2W tuples, and each arrival also removes the tuple that leaves its window in expected O(1)O(1) time. This is the sliding window join.

Properties

  • Pipelined and non-blocking. The first result comes out with the first matching pair. The join never waits for the end of an input.
  • Order independent. The final output does not depend on the order of the arrivals. Only the time at which each result appears does.
  • Exact under bag semantics. Duplicates multiply as in SQL, and NULL keys never match.
  • Symmetric. Neither input must be the smaller one, and the join does not need to know the sizes in advance.

Variants and improvements

  • Memory overflow. When the two tables do not fit in memory, a part of them must go to disk. XJoin partitions both tables by a hash of the key, moves whole partitions to disk, joins the disk parts while the inputs are blocked, and uses timestamps so that no pair is emitted twice. Ives et al. (1999) used the same join in the Tukwila data integration system and gave other strategies for overflow.
  • Windows and expiration. For unbounded streams, each tuple is kept only while it is inside a window, which gives the sliding window join.
  • Many inputs. The ripple join of online aggregation reads samples of both inputs in turn and joins each new sample with all earlier samples of the other input. Its hash form is a symmetric hash join. The eddies of adaptive query processing keep one hash index per input and route tuples between them, which generalizes the same idea to more than two inputs.
  • Outside streams. The join is also used in ordinary query plans: in parallel and distributed engines, where the inputs come from other nodes at different speeds, and in any plan where the user wants early results. It is not only a stream operator.

When to use it

Use it when both inputs arrive slowly or in bursts, when the first results matter more than the total time, or when neither input is known to be small. Use it on streams only with a window or another bound, because the memory grows without limit. Prefer a classic hash join when one input is small and fully available, since it keeps one table instead of two, and a Grace hash join when the inputs are large and on disk.

Pitfalls

  • Unbounded memory. On streams the tables grow forever unless tuples expire. Without a window or a punctuation that closes a key, the join will run out of memory.
  • Late data in windowed joins. In a window join, a tuple that arrives after the tuples it should match have expired misses those matches. A system must either keep tuples until a watermark says that no earlier data can come, or accept that late data loses results. Heuristic watermarks can be wrong, so this is a choice of the system and not a property of the join.
  • Outer joins. Line L5 drops a tuple with a NULL key. An outer join must keep and pad it, and it can emit an unmatched tuple only when it knows that no match will come, which needs the end of the other input or a punctuation.
  • Double counting in variants. Any variant that moves tuples to disk and joins them later can emit a pair twice, once from memory and once from disk. XJoin solves this with timestamps.

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)
symmetric_hash_join.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symmetric-hash-join/. The authors are listed in prov/2VN9MN.jsonl.

"""Symmetric hash join: a pipelined equi-join that keeps one hash table per input.

The join is the natural join of R and S on their common attributes, under bag
semantics. Tuples arrive one at a time from either input, in any order. Each
arriving tuple is inserted into the table of its own input and probes the
table of the other input, so every result pair is emitted as soon as its
second tuple arrives. A tuple with NULL (None) in a join attribute never
matches, as in SQL, so it is not stored at all.

The output tuple has the attributes of R followed by the attributes of S that
are not in R, the order that dbrel.natural_join uses.
"""

from collections.abc import Iterable, Sequence

R = "R"
S = "S"


class SymmetricHashJoin:
    """The state of one symmetric hash join: two hash tables on the join key."""

    def __init__(self, schema_r: Sequence[str], schema_s: Sequence[str]) -> None:
        self.schema_r = tuple(schema_r)
        self.schema_s = tuple(schema_s)
        self.common = tuple(a for a in self.schema_r if a in self.schema_s)
        self.key_pos = {
            R: [self.schema_r.index(a) for a in self.common],
            S: [self.schema_s.index(a) for a in self.common],
        }
        self.rest_pos = [i for i, a in enumerate(self.schema_s) if a not in self.common]
        self.out_schema = self.schema_r + tuple(self.schema_s[i] for i in self.rest_pos)
        self.tables: dict[str, dict[tuple, list[tuple]]] = {R: {}, S: {}}  # @line L1
        self.stored = 0
        self.probes = 0

    def _key(self, side: str, t: tuple) -> tuple:
        return tuple(t[i] for i in self.key_pos[side])

    def _combine(self, r: tuple, s: tuple) -> tuple:
        return r + tuple(s[i] for i in self.rest_pos)

    def insert(self, side: str, t: Sequence) -> list[tuple]:
        """Process one arriving tuple and return the result tuples it completes."""
        if side not in (R, S):
            raise ValueError("side must be 'R' or 'S'")
        t = tuple(t)
        own, other = (R, S) if side == R else (S, R)  # @line L3
        k = self._key(side, t)  # @line L4
        if any(v is None for v in k):  # @line L5
            return []
        self.tables[own].setdefault(k, []).append(t)  # @line L6
        self.stored += 1
        out = []
        for u in self.tables[other].get(k, ()):  # @line L7
            self.probes += 1
            out.append(self._combine(t, u) if side == R else self._combine(u, t))  # @line L8
        return out

    def memory(self) -> int:
        """The number of tuples held in the two tables."""
        return self.stored


def symmetric_hash_join(schema_r: Sequence[str], schema_s: Sequence[str],
                        arrivals: Iterable[tuple[str, Sequence]]) -> list[list[tuple]]:
    """Run the join over a sequence of (side, tuple) arrivals.

    Returns one list per arrival: the result tuples emitted at that step.
    """
    join = SymmetricHashJoin(schema_r, schema_s)
    steps = []
    for side, t in arrivals:  # @line L2
        steps.append(join.insert(side, t))
    return steps
test_symmetric_hash_join.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symmetric-hash-join/. The authors are listed in prov/2VN9MN.jsonl.

import random
from collections import Counter

import dbrel
from symmetric_hash_join import R, S, SymmetricHashJoin, symmetric_hash_join


def oracle(schema_r, schema_s, r_rows, s_rows):
    rel = dbrel.natural_join(dbrel.Relation(schema_r, r_rows), dbrel.Relation(schema_s, s_rows))
    return rel.rows


def run_and_check(schema_r, schema_s, arrivals):
    """After every arrival, the output so far must equal the join of the prefixes."""
    join = SymmetricHashJoin(schema_r, schema_s)
    seen_r, seen_s, out = [], [], Counter()
    for side, t in arrivals:
        out.update(join.insert(side, t))
        (seen_r if side == R else seen_s).append(tuple(t))
        assert out == oracle(schema_r, schema_s, seen_r, seen_s)
    assert join.out_schema == dbrel.natural_join(
        dbrel.Relation(schema_r, []), dbrel.Relation(schema_s, [])).schema
    return join, out


def interleave(rng, r_rows, s_rows):
    tags = [R] * len(r_rows) + [S] * len(s_rows)
    rng.shuffle(tags)
    it = {R: iter(r_rows), S: iter(s_rows)}
    return [(side, next(it[side])) for side in tags]


def test_page_example() -> None:
    arrivals = [(R, (1, 10)), (S, (10, "p")), (R, (2, 20)), (S, (10, "q")), (R, (3, 10)), (S, (20, "r"))]
    steps = symmetric_hash_join(("A", "B"), ("B", "C"), arrivals)
    assert [len(x) for x in steps] == [0, 1, 0, 1, 2, 1]
    assert steps[4] == [(3, 10, "p"), (3, 10, "q")]
    run_and_check(("A", "B"), ("B", "C"), arrivals)


def test_hand_cases() -> None:
    # Empty inputs and one tuple.
    assert symmetric_hash_join(("A", "B"), ("B", "C"), []) == []
    assert symmetric_hash_join(("A", "B"), ("B", "C"), [(S, (1, 2))]) == [[]]
    # All tuples with the same key: every pair once, n * m in total.
    arr = [(R, (i, 0)) for i in range(4)] + [(S, (0, j)) for j in range(3)]
    join, out = run_and_check(("A", "B"), ("B", "C"), arr)
    assert sum(out.values()) == 12 and join.memory() == 7
    # Duplicates multiply.
    join, out = run_and_check(("A", "B"), ("B", "C"), [(R, (1, 5)), (R, (1, 5)), (S, (5, 7)), (S, (5, 7))])
    assert out == Counter({(1, 5, 7): 4})
    # NULL keys never match and are not stored.
    join, out = run_and_check(("A", "B"), ("B", "C"), [(R, (1, None)), (S, (None, 2)), (S, (3, 4))])
    assert not out and join.memory() == 1
    # No common attribute: the product.
    join, out = run_and_check(("A",), ("C",), [(R, (1,)), (S, (2,)), (R, (3,))])
    assert out == Counter({(1, 2): 1, (3, 2): 1})


def test_random_interleavings() -> None:
    schemas = [(("A", "B"), ("B", "C")), (("A", "B", "C"), ("B", "C", "D")), (("A",), ("A",))]
    for seed in range(60):
        rng = random.Random(seed)
        schema_r, schema_s = schemas[seed % len(schemas)]
        r_rel = dbrel.random_relation(rng, schema_r, rng.randrange(0, 25), 3, null_rate=0.1)
        s_rel = dbrel.random_relation(rng, schema_s, rng.randrange(0, 25), 3, null_rate=0.1)
        r_rows = r_rel.sorted_rows()
        s_rows = s_rel.sorted_rows()
        rng.shuffle(r_rows)
        rng.shuffle(s_rows)
        join, out = run_and_check(schema_r, schema_s, interleave(rng, r_rows, s_rows))
        # Memory holds every tuple whose key has no NULL.
        k_r = [schema_r.index(a) for a in join.common]
        k_s = [schema_s.index(a) for a in join.common]
        keep = sum(all(t[i] is not None for i in k_r) for t in r_rows)
        keep += sum(all(t[i] is not None for i in k_s) for t in s_rows)
        assert join.memory() == keep
        # The probes that find a match are exactly the output pairs.
        assert join.probes == sum(out.values())


def test_order_does_not_change_the_result() -> None:
    rng = random.Random(7)
    r_rows = dbrel.random_relation(rng, ("A", "B"), 20, 4).sorted_rows()
    s_rows = dbrel.random_relation(rng, ("B", "C"), 20, 4).sorted_rows()
    results = set()
    for _ in range(10):
        steps = symmetric_hash_join(("A", "B"), ("B", "C"), interleave(rng, r_rows, s_rows))
        results.add(frozenset(Counter(t for x in steps for t in x).items()))
    assert len(results) == 1

History

Wilschut and Apers (1991) described this join for dataflow query execution in a parallel main-memory database system. A hash join with one table pipelines only its probe input, and they wanted both inputs of a join to be pipelined so that a whole tree of joins could run at once. Ives, Florescu, Friedman, Levy and Weld (1999) used it in the Tukwila system for data integration over the network, where remote sources are slow and unpredictable, and added ways to handle memory overflow. Urhan and Franklin (2000) took it as the base of XJoin, which spills partitions to disk and uses the time that the inputs are blocked.

References

  1. Dataflow query execution in a parallel main-memory environment, the pipelining hash-join and its comparison with the simple hash-join (the page numbers are not confirmed here)
  2. An adaptive query execution system for data integration, the pipelined hash join of the Tukwila system and its strategies for memory overflow (the page numbers are not confirmed here)
  3. XJoin: a reactively-scheduled pipelined join operator, the description of the symmetric hash join as the starting point of XJoin, and its memory problem

Where this leads

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.average
  • a full proof of time.best
  • a full proof of time.worst
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