Algorithm Search⌘K

Algorithmadvanced

Ripple join

Also called Haas-Hellerstein ripple join.

A join for online aggregation. It reads both inputs in random order, joins each new tuple with all tuples read from the other input, and scales the running sum into an unbiased estimate.

Time
O(n m) worstO(n + m + j) average
Space
O(n + m) extra
Where
j = the number of joining pairs among the tuples read; m = the number of tuples read from S; n = the number of tuples read from R
Properties
randomizednot exactnot externalnot in placeonlineiterative
Origin
Peter J. Haas, Joseph M. Hellerstein, 1999

A ripple join computes an aggregate such as SUM or COUNT over a join R⋈SR \bowtie S for online aggregation: it reports a running estimate with a confidence interval from the first tuples on, and the exact answer when it has read both inputs. It reads both inputs in random order, and at each step it adds a few tuples of each input and joins each new tuple with every tuple already read from the other input, so the pairs it has seen form a growing rectangle. The estimate is the running sum scaled by the fraction of the rectangle seen, and by linearity of expectation it is unbiased. The hash form is a symmetric hash join over random orders. Unlike a nested loops join, which must read all of the inner input for its first outer tuple, a ripple join samples both inputs at once. A wander join samples random paths through indexes instead.

In plain words

You want the total sales of all orders that match a customer in a promotion list, but both tables are large. Instead of waiting for the exact total, you want a good guess now and a better guess every second.

So you take orders and customers in a random order, a few of each at a time. Each new order is checked against the customers you already took, and each new customer against the orders you already took. You add up the sales of every match you find.

If you have taken a tenth of the orders and a tenth of the customers, you have checked about a hundredth of all pairs. So your total, multiplied by 100, is a fair guess of the full total. The guess gets better as you go, and it is exact when you have taken everything.

The problem

The input is two relations RR and SS with ∣R∣=N|R| = N and ∣S∣=M|S| = M, a join condition r.a=s.br.a = s.b (a NULL key never matches) and a value v(r,s)v(r, s) for each joining pair, for example a column of rr. The query asks for τ=∑v(r,s)\tau = \sum v(r, s) over the bag R⋈SR \bowtie S. COUNT is the case v=1v = 1, and AVG is SUM divided by COUNT.

The output is a sequence of estimates τ^1,τ^2,…\hat\tau_1, \hat\tau_2, \dots, one per step, each with a confidence interval, such that each estimate is unbiased and the last one equals τ\tau.

Cost model. The measure is the work per step in the real RAM, with expected O(1)O(1) time per hash table operation, and the quality of the estimate after nn tuples of RR and mm tuples of SS, measured by its variance. The orders of RR and SS must be independent and uniformly random, for example because the tables are stored in random order or read through a random permutation.

The algorithm

  1. RIPPLE-JOIN(R, S, v, β_R, β_S) ▷ v(r, s) is the value of a joining pair
  2. 1put R and S in independent random orders; R_t, S_t ← empty; Σ ← 0
  3. 2while some tuple of R or S is not read do
  4. 3for β_R new tuples r of R, as far as they last: Σ ← Σ + the sum of v(r, s) over s in S_t that join with r; add r to R_t
  5. 4for β_S new tuples s of S, as far as they last: Σ ← Σ + the sum of v(r, s) over r in R_t that join with s; add s to S_t
  6. 5τ̂ ← N M / (|R_t| |S_t|) · Σ
  7. 6h ← z · the square root of the estimated variance of τ̂
  8. 7report τ̂ ± h

The pair (βR,βS)(\beta_R, \beta_S) is the aspect ratio. The square ripple join has βR=βS=1\beta_R = \beta_S = 1. With βS=M\beta_S = M, the first step reads all of SS, and the ripple join becomes a nested loops join over a random order of RR. Lines L3 and L4 can scan the tuples read from the other input (the block or nested-loops form) or look up the key in a hash table on them (the hash form). Both forms add the same pairs, so they give the same estimates.

The variance in line L6 is the first-order part of the formula in the section on correctness, with the variances of the row and column means estimated from the sample. The number zz comes from the normal distribution, for example z=1.96z = 1.96 for a 95% interval.

Example

Let R=r1(1,3),r2(2,5),r3(1,2),r4(3,4)R = r_1(1, 3), r_2(2, 5), r_3(1, 2), r_4(3, 4), written as (key, price), and S=s1(1),s2(2),s3(1)S = s_1(1), s_2(2), s_3(1). The query is the SUM of the price over R⋈SR \bowtie S. The true answer is τ=3⋅2+5+2⋅2=15\tau = 3 \cdot 2 + 5 + 2 \cdot 2 = 15. Take the square ripple join, and let the random order be the order given.

step new tuples new joining pairs Σ\Sigma rectangle estimate 12nmΣ\frac{12}{n m} \Sigma
1 r1r_1, s1s_1 (r1,s1)(r_1, s_1): 3 3 1×11 \times 1 36
2 r2r_2, s2s_2 (r2,s2)(r_2, s_2): 5 8 2×22 \times 2 24
3 r3r_3, s3s_3 (r3,s1)(r_3, s_1): 2, (r1,s3)(r_1, s_3): 3, (r3,s3)(r_3, s_3): 2 15 3×33 \times 3 20
4 r4r_4 (SS is exhausted) none 15 4×34 \times 3 15

The estimate at step 3 is 20, although the sum already holds all 15. The ripple join cannot know that the unread tuple r4r_4 joins with nothing. Over all 4!⋅3!=1444! \cdot 3! = 144 orders, the mean of the estimate at each step is exactly 15.

A larger run. Let RR have 200 tuples with keys from 5 values and prices from 1 to 19, and SS have 200 tuples with keys from the same 5 values, all drawn with seed 5. The true SUM is 79718. Over 200 square ripple joins with different random orders:

tuples read from each input mean estimate standard deviation of the estimate median half width at 95% runs whose interval holds 79718
10 79962 22178 50722 193 of 200
25 79050 9254 22948 197 of 200
50 79466 5866 12656 195 of 200
100 80115 3150 6607 193 of 200

The exact standard deviation from the variance formula is 21904, 10393, 6039 and 3244 at these four steps. At 100 tuples of each input the ripple join has seen a quarter of the pairs, and the standard deviation of its estimate is about 4% of the answer. These numbers are measurements of this simulation.

Correctness

At each step the running sum is the sum of vv over all joining pairs in the rectangle Rt×StR_t \times S_t, because each pair is added once, when the later of its two tuples is read. A prefix of a random order is a uniform random subset, so a pair is in the rectangle with probability nN⋅mM\frac{n}{N} \cdot \frac{m}{M}, and the scaled sum has expectation τ\tau. The exact variance is

Var⁡(τ^)=N2M2((1−n/N)Sa2n+(1−m/M)Sb2m+(1−n/N)(1−m/M)Sg2nm),\operatorname{Var}(\hat\tau) = N^2 M^2 \left( \frac{(1 - n/N) S_a^2}{n} + \frac{(1 - m/M) S_b^2}{m} + \frac{(1 - n/N)(1 - m/M) S_g^2}{n m} \right),

where Sa2S_a^2 is the variance of the row means a(r)=1M∑sv(r,s)a(r) = \frac{1}{M} \sum_s v(r, s), Sb2S_b^2 the variance of the column means, and Sg2S_g^2 the variance of the rest. When both inputs are read, every factor 1−n/N1 - n/N and 1−m/M1 - m/M is 0 and the estimate is exact. The proofs are in the proof page.

The interval of line L6 uses an estimate of the first two terms and a central limit theorem, so its coverage is close to the nominal level only for large samples. A conservative interval from Hoeffding's inequality needs a bound on the values and is wider. See confidence interval for the general idea.

Proof: The ripple join estimate is unbiased at every step, with an exact variance formula, and it equals the answer when both inputs are readfull

We use the line numbers of the pseudocode. RR has NN tuples and SS has MM tuples, and each stored tuple is a distinct occurrence. For r∈Rr \in R and s∈Ss \in S let v(r,s)v(r, s) be the value of the pair when the keys are equal and not NULL, and v(r,s)=0v(r, s) = 0 otherwise. The query asks for τ=∑r∈R∑s∈Sv(r,s)\tau = \sum_{r \in R} \sum_{s \in S} v(r, s). COUNT is the case v=1v = 1 on joining pairs. After step tt the algorithm has read the sets RtR_t and StS_t of sizes n=∣Rt∣n = |R_t| and m=∣St∣m = |S_t|. These sizes depend only on tt, NN, MM and the aspect ratio (βR,βS)(\beta_R, \beta_S), not on the random order. The estimate of line L5 is

τ^t=NMnmΣt,Σt=the running sum.\hat\tau_t = \frac{N M}{n m} \Sigma_t, \qquad \Sigma_t = \text{the running sum}.

Lemma 1 (the running sum covers the rectangle). After step tt, Σt=∑r∈Rt∑s∈Stv(r,s)\Sigma_t = \sum_{r \in R_t} \sum_{s \in S_t} v(r, s).

Proof. Line L3 adds a tuple rr to RtR_t and adds v(r,s)v(r, s) for every ss already in StS_t. Line L4 adds a tuple ss and adds v(r,s)v(r, s) for every rr already in RtR_t, including the tuples of RR added in the same step. So each pair (r,s)(r, s) of Rt×StR_t \times S_t is added once, when the later of its two tuples is added, and no pair outside the rectangle is added. The hash form looks up only the tuples with the same key, which are exactly the pairs with v(r,s)v(r, s) possibly nonzero, so both forms give the same sum. □\square

Theorem 1 (unbiased). If the orders of RR and SS are independent and uniformly random, then E[τ^t]=τE[\hat\tau_t] = \tau at every step tt with n,m≥1n, m \ge 1.

Proof. A prefix of length nn of a uniformly random order of RR is a uniformly random subset of size nn, so P(r∈Rt)=n/NP(r \in R_t) = n / N for each rr, and in the same way P(s∈St)=m/MP(s \in S_t) = m / M. The two orders are independent, so P(r∈Rt and s∈St)=nm/(NM)P(r \in R_t \text{ and } s \in S_t) = n m / (N M). By Lemma 1 and linearity of expectation,

E[τ^t]=NMnm∑r,sv(r,s) P(r∈Rt,s∈St)=∑r,sv(r,s)=τ.■E[\hat\tau_t] = \frac{N M}{n m} \sum_{r, s} v(r, s) \, P(r \in R_t, s \in S_t) = \sum_{r, s} v(r, s) = \tau. \qquad \blacksquare

The estimate of AVG is the ratio of the SUM and COUNT estimates. A ratio of unbiased estimates is not unbiased in general, so the AVG estimate is only consistent.

Theorem 2 (exact variance). Let μ=τ/(NM)\mu = \tau / (N M), a(r)=1M∑sv(r,s)a(r) = \frac{1}{M} \sum_s v(r, s), b(s)=1N∑rv(r,s)b(s) = \frac{1}{N} \sum_r v(r, s) and g(r,s)=v(r,s)−a(r)−b(s)+μg(r, s) = v(r, s) - a(r) - b(s) + \mu. Let fR=n/Nf_R = n / N and fS=m/Mf_S = m / M, and let

Sa2=∑r(a(r)−μ)2N−1,Sb2=∑s(b(s)−μ)2M−1,Sg2=∑r,sg(r,s)2(N−1)(M−1).S_a^2 = \frac{\sum_r (a(r) - \mu)^2}{N - 1}, \quad S_b^2 = \frac{\sum_s (b(s) - \mu)^2}{M - 1}, \quad S_g^2 = \frac{\sum_{r, s} g(r, s)^2}{(N - 1)(M - 1)}.

Then, with a term read as 0 when its factor 1−fR1 - f_R or 1−fS1 - f_S is 0,

Var⁡(τ^t)=N2M2((1−fR)Sa2n+(1−fS)Sb2m+(1−fR)(1−fS)Sg2nm).\operatorname{Var}(\hat\tau_t) = N^2 M^2 \left( \frac{(1 - f_R) S_a^2}{n} + \frac{(1 - f_S) S_b^2}{m} + \frac{(1 - f_R)(1 - f_S) S_g^2}{n m} \right).

Proof. Write v(r,s)=μ+(a(r)−μ)+(b(s)−μ)+g(r,s)v(r, s) = \mu + (a(r) - \mu) + (b(s) - \mu) + g(r, s) and sum over the rectangle. With aˉ\bar a the mean of aa over RtR_t and bˉ\bar b the mean of bb over StS_t,

τ^tNM=Σtnm=μ+(aˉ−μ)+(bˉ−μ)+G,G=1nm∑r∈Rt∑s∈Stg(r,s).\frac{\hat\tau_t}{N M} = \frac{\Sigma_t}{n m} = \mu + (\bar a - \mu) + (\bar b - \mu) + G, \qquad G = \frac{1}{n m} \sum_{r \in R_t} \sum_{s \in S_t} g(r, s).

The function gg has zero row sums and zero column sums: ∑sg(r,s)=Ma(r)−Ma(r)−Mμ+Mμ=0\sum_s g(r, s) = M a(r) - M a(r) - M \mu + M \mu = 0, and the same for columns.

The three terms are uncorrelated. aˉ\bar a depends only on RtR_t and bˉ\bar b only on StS_t, which are independent. Given RtR_t, each ss is in StS_t with probability m/Mm / M, so E[G∣Rt]=1nM∑r∈Rt∑sg(r,s)=0E[G \mid R_t] = \frac{1}{n M} \sum_{r \in R_t} \sum_s g(r, s) = 0. So Cov⁡(aˉ,G)=E[(aˉ−μ)E[G∣Rt]]=0\operatorname{Cov}(\bar a, G) = E[(\bar a - \mu) E[G \mid R_t]] = 0, and in the same way Cov⁡(bˉ,G)=0\operatorname{Cov}(\bar b, G) = 0.

The first two terms. aˉ\bar a is the mean of a simple random sample of size nn without replacement from the NN values a(r)a(r), so its variance is (1−fR)Sa2/n(1 - f_R) S_a^2 / n, and the same holds for bˉ\bar b.

The third term. E[G]=0E[G] = 0. For r≠r′r \ne r' in RR, P(r,r′∈Rt)=qR=n(n−1)N(N−1)P(r, r' \in R_t) = q_R = \frac{n(n - 1)}{N(N - 1)}, and P(r∈Rt)=pR=n/NP(r \in R_t) = p_R = n / N; the same with qSq_S and pSp_S for SS. Then

E[G2]=1n2m2∑r,r′∑s,s′g(r,s)g(r′,s′) P(r,r′∈Rt) P(s,s′∈St).E[G^2] = \frac{1}{n^2 m^2} \sum_{r, r'} \sum_{s, s'} g(r, s) g(r', s') \, P(r, r' \in R_t) \, P(s, s' \in S_t).

For fixed s,s′s, s', the sum over r≠r′r \ne r' of g(r,s)g(r′,s′)g(r, s) g(r', s') equals (∑rg(r,s))(∑r′g(r′,s′))−∑rg(r,s)g(r,s′)=−∑rg(r,s)g(r,s′)(\sum_r g(r, s))(\sum_{r'} g(r', s')) - \sum_r g(r, s) g(r, s') = -\sum_r g(r, s) g(r, s'). So the sum over r,r′r, r' is (pR−qR)∑rg(r,s)g(r,s′)(p_R - q_R) \sum_r g(r, s) g(r, s'). Doing the same over s,s′s, s' gives

E[G2]=(pR−qR)(pS−qS)n2m2∑r,sg(r,s)2.E[G^2] = \frac{(p_R - q_R)(p_S - q_S)}{n^2 m^2} \sum_{r, s} g(r, s)^2.

Since pR−qR=nN⋅N−nN−1p_R - q_R = \frac{n}{N} \cdot \frac{N - n}{N - 1}, this is (1−fR)(1−fS)nmSg2\frac{(1 - f_R)(1 - f_S)}{n m} S_g^2. Adding the three variances and multiplying by N2M2N^2 M^2 gives the formula. When N=1N = 1 the sample is all of RR, fR=1f_R = 1, and the terms with 1−fR1 - f_R vanish. ■\blacksquare

The third term falls like 1/(nm)1 / (n m), faster than the first two, so for large samples the variance is close to the first two terms. The implementation estimates Sa2S_a^2 by the sample variance of 1m∑s∈Stv(r,s)\frac{1}{m} \sum_{s \in S_t} v(r, s) over r∈Rtr \in R_t, and Sb2S_b^2 in the same way, and uses τ^t±zVar⁡^\hat\tau_t \pm z \sqrt{\widehat{\operatorname{Var}}} as the interval. That the interval has coverage close to the nominal level rests on a central limit theorem for large samples. It is an approximation, not a bound for a given nn.

Theorem 3 (the end is exact, and termination). Each step reads at least one tuple while some tuple is unread, so after at most N+MN + M steps Rt=RR_t = R and St=SS_t = S. Then τ^t=NMNMτ=τ\hat\tau_t = \frac{N M}{N M} \tau = \tau by Lemma 1, and every term of the variance has a zero factor. ■\blacksquare

Theorem 4 (work). Let jtj_t be the number of joining pairs in Rt×StR_t \times S_t. With hash tables in expected O(1)O(1) time per operation, the hash form does expected O(n+m+jt)O(n + m + j_t) work up to step tt, plus O(1)O(1) per step for the estimate if the sums ∑rA(r)2\sum_r A(r)^2 and ∑sB(s)2\sum_s B(s)^2 of the squared row and column sums are kept up to date. The nested-loops form does Θ(nm)\Theta(n m) comparisons.

Proof. Each read costs one insert and one lookup. Each joining pair is met once (Lemma 1) and changes one row sum A(r)A(r) and one column sum B(s)B(s) by vv, and ∑A(r)2\sum A(r)^2 changes by 2A(r)v+v22 A(r) v + v^2, computed in O(1)O(1). The sample variances follow from these sums and Σt\Sigma_t. The nested form compares each new tuple with every tuple read from the other input, which gives nmn m comparisons for the rectangle. ■\blacksquare

The implementation recomputes the sample variances at each step in O(n+m)O(n + m) time, which is simpler and does not change the results.

Complexity

  • Work. The hash form does expected O(1)O(1) work per tuple read and per joining pair found, so the work up to the rectangle n×mn \times m is expected O(n+m+j)O(n + m + j). The block form does nmn m comparisons for the same rectangle. The variance can be kept up to date in O(1)O(1) per pair with running sums of squares.
  • Variance. For a fixed aspect ratio the variance falls like 1/n1/n in the number of tuples read from each input, plus a term in 1/(nm)1/(n m) that matters only for small samples. A ratio that reads more from the input whose row means vary more gives a smaller variance for the same work.
  • Space. All tuples read stay in memory, O(n+m)O(n + m), because a later tuple of the other input may join with any of them.

Properties

  • Online. An estimate is available after each step, and the user may stop the query at any time.
  • Unbiased at every step for SUM and COUNT, when the orders are uniformly random. AVG is a ratio of two estimates and is only consistent.
  • Exact at the end. After both inputs are read, the estimate is the answer and the interval has width 0.
  • Randomized. The estimates depend on the random orders. With a fixed seed they are repeatable.
  • Any join condition. The block form works for any predicate, not only for equality, but it needs nmn m comparisons.

Variants and improvements

  • Adaptive aspect ratio. Haas and Hellerstein choose the aspect ratio during the run, from the estimated variances of the two inputs, to make the interval shrink fastest for the work done.
  • Index ripple join. If SS has an index on the key, each new tuple of RR looks up all its matches in SS at once. This is the case βS=M\beta_S = M done through the index, and the estimate is then a mean over a random sample of RR only.
  • Hash ripple join out of memory. Luo, Ellmann, Haas and Naughton (2002) extend the hash ripple join to the case where the tuples read no longer fit in memory, by partitioning them to disk in the manner of a Grace hash join.
  • More than two inputs. The same idea works for kk inputs: each step extends a hyper-rectangle, and the estimate scales the sum by the product of the sampling fractions.
  • Wander join. A wander join does not read the inputs in order: it walks a random path through indexes from one tuple to a matching tuple, and weights each path by the inverse of its probability.

When to use it

Use a ripple join when a user wants a fast approximate answer to an aggregate over a join of large tables and is ready to stop early, and the tables can be read in random order. It works best when the join has many results, so that a small rectangle already contains many joining pairs. For a join with very few results, most of the early rectangle contains nothing and the interval stays wide for a long time.

Pitfalls

  • Input that is not in random order. If the tables are sorted or clustered, a prefix is not a random sample and the estimate is biased. The orders must also be independent of each other.
  • Selective joins. When few pairs join, the variance is large compared with τ2\tau^2, and the interval from the central limit theorem can be too narrow for small samples.
  • Reusing the interval at every step. A 95% interval at each step does not give 95% confidence that all intervals hold at once. A user who stops when the interval looks good needs an interval that holds over all steps.
  • Memory. The memory grows with the tuples read, as in a symmetric hash join.
  • AVG. The AVG estimate is biased for small samples, and its interval needs the delta method for the ratio.

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.

ripple_join.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ripple-join/. The authors are listed in prov/NQMZP0.jsonl.

"""Ripple join: an online estimate of SUM(value) over the equi-join of R and S.

The tuples of R and S are read in a random order (or in the given order when
rng is None, so that a caller can pass its own permutation). Each step reads
beta_R new tuples of R and beta_S new tuples of S, as far as they last, and
joins each new tuple with every tuple already read from the other input. After
step t the running sum covers exactly the pairs of the rectangle R_n x S_n of
the tuples read so far, and the estimate is

    |R| |S| / (n_R n_S) * (sum of value(r, s) over the joining pairs in R_n x S_n).

COUNT is SUM with value 1. The half width of the confidence interval uses the
first-order (delta method) variance

    |R|^2 |S|^2 ((1 - n_R/|R|) v_R / n_R + (1 - n_S/|S|) v_S / n_S),

where v_R is the sample variance over r in R_n of the mean value of r against
S_n, and v_S is the same for S. It is an approximation for large samples.

method "hash" keeps a hash table on the key of each input and probes it;
method "nested" compares the new tuple with every tuple read from the other
input. Both give the same running sums. A NULL key (None) never matches.
"""

import math
import random
from collections.abc import Callable, Sequence
from fractions import Fraction


def _sample_var(xs: list) -> float:
    if len(xs) < 2:
        return 0.0
    m = sum(xs) / len(xs)
    return sum((x - m) ** 2 for x in xs) / (len(xs) - 1)


def exact_variance(r_rows: Sequence[tuple], s_rows: Sequence[tuple], rkey: Callable, skey: Callable,
                   value: Callable, n_r: int, n_s: int) -> Fraction:
    """The exact variance of the estimate after reading n_r tuples of R and n_s of S.

    With v(r, s) the value of a joining pair (0 otherwise), a(r) and b(s) the
    row and column means, mu the overall mean and g = v - a - b + mu:

    Var = |R|^2 |S|^2 ((1 - f_R) S_a / n_r + (1 - f_S) S_b / n_s + (1 - f_R)(1 - f_S) S_g / (n_r n_s)),

    where f_R = n_r / |R|, S_a = sum (a - mu)^2 / (|R| - 1), and the same for
    b, and S_g = sum g^2 / ((|R| - 1)(|S| - 1)). A term with a zero factor
    (1 - f) is 0, also when |R| = 1 or |S| = 1.
    """
    big_r, big_s = len(r_rows), len(s_rows)

    def v(r, s):
        kr, ks = rkey(r), skey(s)
        return Fraction(value(r, s)) if kr is not None and ks is not None and kr == ks else Fraction(0)

    mat = [[v(r, s) for s in s_rows] for r in r_rows]
    mu = sum(map(sum, mat)) / (big_r * big_s)
    a = [sum(row) / big_s for row in mat]
    b = [sum(mat[i][j] for i in range(big_r)) / big_r for j in range(big_s)]
    fr, fs = Fraction(n_r, big_r), Fraction(n_s, big_s)
    var = Fraction(0)
    if fr != 1:
        var += (1 - fr) * sum((x - mu) ** 2 for x in a) / (big_r - 1) / n_r
    if fs != 1:
        var += (1 - fs) * sum((x - mu) ** 2 for x in b) / (big_s - 1) / n_s
    if fr != 1 and fs != 1:
        sg = sum((mat[i][j] - a[i] - b[j] + mu) ** 2 for i in range(big_r) for j in range(big_s))
        var += (1 - fr) * (1 - fs) * sg / ((big_r - 1) * (big_s - 1)) / (n_r * n_s)
    return (big_r * big_s) ** 2 * var


def ripple_join(r_rows: Sequence[tuple], s_rows: Sequence[tuple], rkey: Callable, skey: Callable,
                value: Callable, aspect: tuple = (1, 1), rng: random.Random | None = None,
                method: str = "hash", z: float = 1.96) -> list:
    """Run the ripple join to the end and return one snapshot per step.

    A snapshot is a dict with n_r, n_s, sum (exact, over the rectangle read),
    estimate (a Fraction), half_width (a float) and pairs (pairs that joined).
    """
    if method not in ("hash", "nested"):
        raise ValueError("method must be 'hash' or 'nested'")
    big_r, big_s = len(r_rows), len(s_rows)
    r_order, s_order = list(r_rows), list(s_rows)
    if rng is not None:
        rng.shuffle(r_order)  # @line L1
        rng.shuffle(s_order)
    seen = ([], [])
    tables = ({}, {})
    rowsum = ([], [])  # rowsum[0][i]: sum of value(r_i, s) over s read so far
    total = 0
    pairs = 0
    n = [0, 0]
    snaps = []
    keyf = (rkey, skey)
    orders = (r_order, s_order)
    if big_r == 0 or big_s == 0:
        return [{"n_r": 0, "n_s": 0, "sum": 0, "estimate": Fraction(0), "half_width": 0.0, "pairs": 0}]

    def add(side: int, t: tuple) -> None:
        nonlocal total, pairs
        other = 1 - side
        k = keyf[side](t)
        mine = 0
        if method == "hash":
            matches = tables[other].get(k, ()) if k is not None else ()
        else:
            matches = [j for j, u in enumerate(seen[other])
                       if k is not None and keyf[other](u) is not None and keyf[other](u) == k]
        for j in matches:
            u = seen[other][j]
            v = value(t, u) if side == 0 else value(u, t)
            mine += v
            rowsum[other][j] += v
            pairs += 1
        total += mine
        idx = len(seen[side])
        seen[side].append(t)
        rowsum[side].append(mine)
        if k is not None:
            tables[side].setdefault(k, []).append(idx)
        n[side] += 1

    while n[0] < big_r or n[1] < big_s:  # @line L2
        for _ in range(aspect[0]):
            if n[0] < big_r:
                add(0, orders[0][n[0]])  # @line L3
        for _ in range(aspect[1]):
            if n[1] < big_s:
                add(1, orders[1][n[1]])  # @line L4
        if n[0] == 0 or n[1] == 0:
            continue
        est = Fraction(big_r * big_s * total, n[0] * n[1])  # @line L5
        v_r = _sample_var([x / n[1] for x in rowsum[0]])
        v_s = _sample_var([x / n[0] for x in rowsum[1]])
        var = (big_r * big_s) ** 2 * ((1 - n[0] / big_r) * v_r / n[0] + (1 - n[1] / big_s) * v_s / n[1])
        half = z * math.sqrt(max(var, 0.0))  # @line L6
        snaps.append({"n_r": n[0], "n_s": n[1], "sum": total, "estimate": est,
                      "half_width": half, "pairs": pairs})  # @line L7
    return snaps
test_ripple_join.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ripple-join/. The authors are listed in prov/NQMZP0.jsonl.

import itertools
import random
from fractions import Fraction

from ripple_join import exact_variance, ripple_join

KEY = lambda t: t[0]
PRICE = lambda r, s: r[2]
ONE = lambda r, s: 1


def exact(r_rows, s_rows, value):
    return sum(value(r, s) for r in r_rows for s in s_rows
               if r[0] is not None and s[0] is not None and r[0] == s[0])


R_EX = [(1, "r1", 3), (2, "r2", 5), (1, "r3", 2), (3, "r4", 4)]
S_EX = [(1, "s1", 0), (2, "s2", 0), (1, "s3", 0)]


def test_example() -> None:
    snaps = ripple_join(R_EX, S_EX, KEY, KEY, PRICE)
    assert [(x["n_r"], x["n_s"]) for x in snaps] == [(1, 1), (2, 2), (3, 3), (4, 3)]
    assert [x["sum"] for x in snaps] == [3, 8, 15, 15]
    assert [x["estimate"] for x in snaps] == [36, 24, 20, 15]
    assert exact(R_EX, S_EX, PRICE) == 15 and snaps[-1]["half_width"] == 0.0


def test_unbiased_over_all_orders() -> None:
    # The mean of the estimate over all orders of R and S equals the true value at every step.
    s_null = S_EX + [(None, "s4", 0)]
    for s_rows, value in ((S_EX, PRICE), (s_null, ONE), (s_null, PRICE)):
        truth = exact(R_EX, s_rows, value)
        for aspect in ((1, 1), (2, 1), (1, 2), (3, 2)):
            total = None
            count = 0
            for pr in itertools.permutations(R_EX):
                for ps in itertools.permutations(s_rows):
                    est = [x["estimate"] for x in ripple_join(list(pr), list(ps), KEY, KEY, value, aspect)]
                    total = est if total is None else [a + b for a, b in zip(total, est)]
                    count += 1
            assert all(Fraction(t, count) == truth for t in total)


def test_exact_variance_over_all_orders() -> None:
    s_null = S_EX + [(None, "s4", 0)]
    for s_rows, value in ((S_EX, PRICE), (s_null, PRICE), (s_null, ONE)):
        truth = exact(R_EX, s_rows, value)
        for aspect in ((1, 1), (2, 1)):
            sq = None
            count = 0
            for pr in itertools.permutations(R_EX):
                for ps in itertools.permutations(s_rows):
                    snaps = ripple_join(list(pr), list(ps), KEY, KEY, value, aspect)
                    dev = [(x["estimate"] - truth) ** 2 for x in snaps]
                    sq = dev if sq is None else [a + b for a, b in zip(sq, dev)]
                    count += 1
            for x, total in zip(snaps, sq):
                want = exact_variance(R_EX, s_rows, KEY, KEY, value, x["n_r"], x["n_s"])
                assert Fraction(total, count) == want


def test_hash_equals_nested() -> None:
    rng = random.Random(2)
    for trial in range(30):
        dom = rng.choice([3, 4, 5])
        keys = list(range(dom)) + [None]
        r = [(rng.choice(keys), i, rng.randrange(10)) for i in range(rng.randrange(0, 40))]
        s = [(rng.choice(keys), i, 0) for i in range(rng.randrange(0, 40))]
        aspect = rng.choice([(1, 1), (2, 1), (1, 3)])
        a = ripple_join(r, s, KEY, KEY, PRICE, aspect, random.Random(trial), "hash")
        b = ripple_join(r, s, KEY, KEY, PRICE, aspect, random.Random(trial), "nested")
        assert a == b
        assert a[-1]["estimate"] == exact(r, s, PRICE)
        assert a[-1]["pairs"] == exact(r, s, ONE)


def test_empty_inputs() -> None:
    assert ripple_join([], S_EX, KEY, KEY, PRICE)[-1]["estimate"] == 0
    assert ripple_join(R_EX, [], KEY, KEY, PRICE)[-1]["estimate"] == 0


def test_mean_and_coverage() -> None:
    rng = random.Random(5)
    r = [(rng.randrange(5), i, rng.randrange(1, 20)) for i in range(200)]
    s = [(rng.randrange(5), i, 0) for i in range(200)]
    truth = exact(r, s, PRICE)
    runs = 120
    for step in (25, 50):
        ests = []
        covered = 0
        for t in range(runs):
            x = ripple_join(r, s, KEY, KEY, PRICE, rng=random.Random(1000 + t))[step - 1]
            ests.append(x["estimate"])
            covered += abs(x["estimate"] - truth) <= x["half_width"]
        assert abs(sum(ests) / runs - truth) <= 0.03 * truth
        assert covered >= 0.85 * runs

History

Hellerstein, Haas and Wang (1997) proposed online aggregation for single-table queries in a relational system, with running estimates and confidence intervals. Haas and Hellerstein (1999) introduced ripple joins to extend online aggregation to joins, as a family that includes block, index and hash ripple joins, and they gave confidence intervals based on a central limit theorem and a rule for choosing the aspect ratio during the run. Luo, Ellmann, Haas and Naughton (2002) made the hash ripple join scale beyond memory. Later work, such as wander join, sampled join paths through indexes instead of rectangles.

References

  1. Peter J. Haas and Joseph M. Hellerstein, Ripple joins for online aggregation, SIGMOD 1999, pages 287 to 298, the ripple join family (block, index and hash ripple joins), the aspect ratios and their adaptive choice, and the confidence intervals based on a central limit theorem
  2. Joseph M. Hellerstein, Peter J. Haas and Helen J. Wang, Online aggregation, SIGMOD 1997, pages 171 to 182, the online aggregation interface with running estimates and confidence intervals for single-table queries
  3. Gang Luo, Curt J. Ellmann, Peter J. Haas and Jeffrey F. Naughton, A scalable hash ripple join algorithm, SIGMOD 2002, pages 252 to 262, the hash ripple join when the tuples read no longer fit in memory

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.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