Algorithm Search⌘K

Algorithmresearch

Wander join

Also called random walk join sampling.

Estimate SUM or COUNT over a join by random walks through the indexes. Each walk is divided by its probability, so it is an unbiased estimate, and a failed walk counts as 0.

Time
O(k W) expected
Space
O(k) extra
Where
W = the number of walks; k = the number of relations in the join
Properties
randomizednot exactnot greedyrandomizediterative
Origin
Feifei Li, Bin Wu, Ke Yi, Zhuoyue Zhao, 2016

Wander join estimates an aggregate such as SUM or COUNT over a join without computing the join. Feifei Li, Bin Wu, Ke Yi and Zhuoyue Zhao gave it in 2016 for online aggregation, where the system shows an estimate and a confidence interval that improve while the query runs. One walk picks a random row of the first table, then follows the index of each next table to a random matching row. The walk keeps the probability pp of its choices and returns v/pv/p, where vv is the value of the expression on the joined row. If the walk reaches a row with no match, it returns 0. Each walk is an unbiased estimate of the answer, by the Horvitz-Thompson argument. Unlike ripple join, which joins independent samples of each table and finds few results when the join is selective, every successful walk is a join result.

In plain words

Suppose you want the total of a column over all rows of a join of three tables. Start at a random row of the first table. Use the index of the second table to list the rows that match it, and pick one at random. Do the same for the third table. If you reach a dead end, the walk counts as zero.

At the end, you know the chance of your path. A rare path stands for many paths you did not walk, so you multiply its value by one over its chance. On average, this gives the true total. Many walks give a good estimate, and their spread gives an error bar. The order in which you visit the tables does not change the average, but it changes the spread and the number of dead ends, so a good order makes the estimate converge faster.

The problem

The input is a join of relations R1,…,RkR_1, \ldots, R_k with optional selections, and an expression vv over the joined rows. The answer is Q=∑γ∈Jv(γ)Q = \sum_{\gamma \in J} v(\gamma) over the join result JJ; COUNT is v=1v = 1, the join size, and AVG is a ratio of two such sums. The model is that each relation after the first has an index on the attributes it shares with an earlier relation of the walk order, and that the index can return a uniform random row among the rows with a given key, together with their number. The output is an estimate Q^\hat Q and a confidence interval that shrinks as more walks are done.

The algorithm

A walk order λ\lambda lists the relations so that each relation Rλ(i)R_{\lambda(i)} after the first shares attributes with an earlier one, its parent Rη(i)R_{\eta(i)}. The edges from each relation to its parent form a spanning tree of the query graph. In a cyclic query, the edges outside the tree are checked at the end of the walk.

  1. WANDER-JOIN(walk order R_λ(1), ..., R_λ(k), indexes, expression v, number of walks W)
  2. 1for w ← 1 to W do
  3. 2pick t_1 uniformly from R_λ(1); p ← 1/|R_λ(1)|
  4. 3for i ← 2 to k do
  5. 4M ← the rows of R_λ(i) that join with t_η(i), found with the index
  6. 5if M is empty, or a selection fails, then X_w ← 0 and go to the next walk
  7. 6pick t_i uniformly from M; p ← p/|M|
  8. 7if the path fails a join condition outside the walk tree, or a selection, then X_w ← 0 else X_w ← v(path)/p
  9. 8return the mean of X_1, ..., X_W and the interval mean ± 1.96 · s/√W, where s is their standard deviation

The code checks selections and the conditions outside the tree as soon as the row of that step is chosen, which gives the same result as line L7 and stops failed walks earlier. In practice the walks run until the user stops the query or the interval is small enough, so WW is not fixed in advance.

Example

This is a small chain join R1(A,B)⋈R2(B,C)⋈R3(C,D)R_1(A, B) \bowtie R_2(B, C) \bowtie R_3(C, D) with COUNT, like the example of Section 3.1 of the paper.

relation rows
R1(A,B)R_1(A, B) (a1,b1)(a_1, b_1), (a2,b1)(a_2, b_1), (a3,b2)(a_3, b_2)
R2(B,C)R_2(B, C) (b1,c1)(b_1, c_1), (b1,c2)(b_1, c_2), (b2,c3)(b_2, c_3)
R3(C,D)R_3(C, D) (c1,5)(c_1, 5), (c2,1)(c_2, 1), (c2,3)(c_2, 3)

The join has 6 rows: a1a_1 or a2a_2, then b1b_1, then one of the three rows of R3R_3 through c1c_1 or c2c_2.

In the order R1,R2,R3R_1, R_2, R_3, the walk starts at one of 3 rows. From a3a_3 it goes to (b2,c3)(b_2, c_3), and R3R_3 has no row with c3c_3, so the walk fails and returns 0. From a1a_1 or a2a_2 it has 2 choices in R2R_2. Through c1c_1 there is 1 row in R3R_3, so 1/p=3⋅2⋅1=61/p = 3 \cdot 2 \cdot 1 = 6. Through c2c_2 there are 2 rows, so 1/p=3⋅2⋅2=121/p = 3 \cdot 2 \cdot 2 = 12. The three values 0, 6 and 12 each have probability 1/31/3, so the mean is 6, the true count, and the variance is 24.

In the order R3,R2,R1R_3, R_2, R_1, every row of R3R_3 has exactly one match in R2R_2, and b1b_1 has two matches in R1R_1. Every walk succeeds with 1/p=3⋅1⋅2=61/p = 3 \cdot 1 \cdot 2 = 6, so every walk returns exactly 6 and the variance is 0. For SUM(D), the walks in this order return 6⋅56 \cdot 5, 6⋅16 \cdot 1 or 6⋅36 \cdot 3, with mean 18, the true sum.

Correctness

The proof file gives the full argument. A successful walk satisfies every join condition: the conditions with the parent hold because the index returns only matching rows, and the other conditions are checked in line L7. Conversely, every row γ\gamma of the join can be reached by exactly one sequence of choices, with probability p(γ)>0p(\gamma) > 0. So the successful walks and the join rows are in one-to-one correspondence, and

E[X]=∑γ∈Jp(γ)⋅v(γ)p(γ)=Q.E[X] = \sum_{\gamma \in J} p(\gamma) \cdot \frac{v(\gamma)}{p(\gamma)} = Q.

Failed walks add 0. This is why a failed walk must count as 0 and not be thrown away: rejecting it would divide by the unknown chance of success. The mean of WW independent walks is unbiased with variance Var[X]/W\mathrm{Var}[X]/W, and the interval of line L8 comes from the central limit theorem, so its coverage of 95 percent holds only as WW grows.

Proof: One wander join walk is an unbiased estimate of SUM(v) over the join, and the mean of W walks has variance Var[X]/Wfull

Setting. The query is a natural join of relations R1,…,RkR_1, \ldots, R_k, taken in the walk order, with a selection predicate θi\theta_i on each RiR_i (true if there is none) and an expression vv of the joined row. The join result JJ is the set of tuples γ=(t1,…,tk)\gamma = (t_1, \ldots, t_k) with ti∈Rit_i \in R_i, θi(ti)\theta_i(t_i) true for each ii, and tit_i and tjt_j equal on the attributes they share, for each pair i,ji, j. The answer is Q=∑γ∈Jv(γ)Q = \sum_{\gamma \in J} v(\gamma); COUNT is the case v=1v = 1. The walk order has, for each i≥2i \ge 2, a parent η(i)<i\eta(i) < i that shares attributes with RiR_i, and an index on RiR_i for those shared attributes. For a row tt of Rη(i)R_{\eta(i)}, let Mi(t)M_i(t) be the set of rows of RiR_i that agree with tt on those attributes. Every other pair j<ij < i of relations that share attributes is a check of step ii (line L7). For i=1i = 1, let M1=R1M_1 = R_1.

The walk. Line L2 picks t1t_1 uniformly from R1R_1. For i=2,…,ki = 2, \ldots, k, lines L4 to L6 pick tit_i uniformly from Mi(tη(i))M_i(t_{\eta(i)}), and the walk fails if this set is empty. The walk also fails if some tit_i fails θi\theta_i or a check of line L7. A walk that does not fail is successful, and its estimate is X=v(γ)/p(γ)X = v(\gamma)/p(\gamma), where

p(γ)=∏i=1k1∣Mi(tη(i))∣p(\gamma) = \prod_{i=1}^{k} \frac{1}{|M_i(t_{\eta(i)})|}

is the product of the probabilities of the choices (with M1(tη(1))M_1(t_{\eta(1)}) read as R1R_1). A failed walk has estimate X=0X = 0.

Lemma 1 (successful walks are the join result). The successful walks are exactly the tuples of JJ, and the walk that ends with γ∈J\gamma \in J has probability p(γ)>0p(\gamma) > 0.

Proof. Let a walk be successful and end with γ=(t1,…,tk)\gamma = (t_1, \ldots, t_k). Each θi(ti)\theta_i(t_i) holds, because the walk did not fail. Take a pair j<ij < i of relations that share attributes. If j=η(i)j = \eta(i), then ti∈Mi(tj)t_i \in M_i(t_j), so the two rows agree on all shared attributes; the key of step ii is the full set of attributes shared with the parent. Otherwise the pair is a check of step ii, and line L7 passed. So γ∈J\gamma \in J.

Now let γ=(t1,…,tk)∈J\gamma = (t_1, \ldots, t_k) \in J. Then t1∈R1t_1 \in R_1, and for each i≥2i \ge 2, tit_i agrees with tη(i)t_{\eta(i)} on their shared attributes, so ti∈Mi(tη(i))t_i \in M_i(t_{\eta(i)}) and this set is not empty. So the walk can choose t1,t2,…,tkt_1, t_2, \ldots, t_k in turn, and the probability of these choices is the product of the probabilities 1/∣Mi(tη(i))∣1/|M_i(t_{\eta(i)})|, that is p(γ)>0p(\gamma) > 0. All predicates and checks hold for γ\gamma, so this walk is successful. Two walks with different choices end with different tuples, so each γ\gamma comes from exactly one sequence of choices. □\square

Theorem 1 (unbiased). E[X]=QE[X] = Q.

Proof. Failed walks add 0 to the expectation. By Lemma 1 the successful walks are the events "the walk ends with γ\gamma", one for each γ∈J\gamma \in J; they are disjoint and have probability p(γ)p(\gamma). So

E[X]=∑γ∈Jp(γ)⋅v(γ)p(γ)=∑γ∈Jv(γ)=Q.■E[X] = \sum_{\gamma \in J} p(\gamma) \cdot \frac{v(\gamma)}{p(\gamma)} = \sum_{\gamma \in J} v(\gamma) = Q. \qquad \blacksquare

This is the Horvitz-Thompson argument: each unit of the population has a known probability of selection that is not zero, and its value is divided by that probability. A walk that fails is not rejected and walked again. If failed walks were thrown away, the estimate would be divided by the probability of success, which is not known, and the result would be biased. The walk order does not change E[X]E[X]; it changes only the distribution of XX. The code computes E[X]E[X] exactly as a fraction by going through every sequence of choices, and the tests compare it with a nested loop join, for chain, star and cyclic queries, with and without a selection, in every valid walk order.

Theorem 2 (the mean of W walks). Let X1,…,XWX_1, \ldots, X_W be independent walks and Xˉ\bar X their mean (line L8). Then E[Xˉ]=QE[\bar X] = Q and Var[Xˉ]=σ2/W\mathrm{Var}[\bar X] = \sigma^2 / W, where σ2=Var[X]\sigma^2 = \mathrm{Var}[X]. The sample variance s2=1W−1∑w(Xw−Xˉ)2s^2 = \frac{1}{W - 1} \sum_w (X_w - \bar X)^2 has E[s2]=σ2E[s^2] = \sigma^2.

Proof. The walk has finitely many outcomes, so σ2\sigma^2 is finite. Linearity of expectation gives E[Xˉ]=QE[\bar X] = Q, independence gives Var[Xˉ]=σ2/W\mathrm{Var}[\bar X] = \sigma^2/W, and the statement on s2s^2 is the standard fact for independent samples with the same distribution. □\square

The interval. By the central limit theorem, (Xˉ−Q)/(σ/W)(\bar X - Q)/(\sigma/\sqrt W) tends in distribution to a standard normal variable, and so does (Xˉ−Q)/(s/W)(\bar X - Q)/(s/\sqrt W), because s→σs \to \sigma in probability. So Xˉ±z s/W\bar X \pm z\, s/\sqrt W with z=1.96z = 1.96 covers QQ with probability that tends to 0.95 as WW grows. This is a large sample statement, not a bound for a fixed WW. For a bound that holds for every WW, Chebyshev's inequality gives P(∣Xˉ−Q∣≥c σ/W)≤1/c2P(|\bar X - Q| \ge c\,\sigma/\sqrt W) \le 1/c^2, which needs σ\sigma or an upper bound on it.

Cost of a walk. A walk does at most k−1k - 1 index lookups (line L4), one uniform choice per step (line L6), and checks of the predicates and of the non tree pairs, so with hash indexes that store each group as an array, a walk takes O(k)O(k) expected time when the attributes per relation are bounded. A walk that fails early is cheaper. With a B-tree, a uniform choice in a range needs the size of the range, for example from counts in the inner nodes, and a lookup costs O(log⁡N)O(\log N). The extra space is the current path, O(k)O(k), and three running sums for Xˉ\bar X and s2s^2.

Choice of walk order. After time tt, a plan with mean time E[T]E[T] per walk has done about t/E[T]t/E[T] walks, so the variance of its estimate is about σ2E[T]/t\sigma^2 E[T]/t. Choosing the plan with the smallest estimated σ2E[T]\sigma^2 E[T], as the function choose_plan does, is a heuristic for speed; Theorem 1 holds for every order, so the choice does not add bias to walks done after it. Walks from the trial phase that are kept in the estimate were used to make the choice, so in theory they can add a small bias; the code does not reuse them.

Example. Take R1(A,B)={(a1,b1),(a2,b1),(a3,b2)}R_1(A, B) = \{(a_1, b_1), (a_2, b_1), (a_3, b_2)\}, R2(B,C)={(b1,c1),(b1,c2),(b2,c3)}R_2(B, C) = \{(b_1, c_1), (b_1, c_2), (b_2, c_3)\}, R3(C,D)={(c1,5),(c2,1),(c2,3)}R_3(C, D) = \{(c_1, 5), (c_2, 1), (c_2, 3)\} and COUNT. The join has 6 tuples. In the order R1,R2,R3R_1, R_2, R_3, the walk fails with probability 1/31/3 (from a3a_3, the row (b2,c3)(b_2, c_3) has no match), gives 1/p=3⋅2⋅1=61/p = 3 \cdot 2 \cdot 1 = 6 with probability 1/31/3, and gives 3⋅2⋅2=123 \cdot 2 \cdot 2 = 12 with probability 1/31/3. The mean is 66 and the variance is 2424. In the order R3,R2,R1R_3, R_2, R_1, every walk succeeds with 1/p=3⋅1⋅2=61/p = 3 \cdot 1 \cdot 2 = 6, so the estimate is always 6 and the variance is 0.

Complexity

A walk does at most k−1k - 1 index lookups and kk random choices. With hash indexes that keep each group of rows in an array, a walk costs O(k)O(k) expected time, and WW walks cost O(kW)O(kW). With B-trees, each lookup costs O(log⁡N)O(\log N), and a uniform choice in a range needs counts in the tree. The extra space is the current path and three running sums. The error falls as σ/W\sigma/\sqrt W, where σ2\sigma^2 is the variance of one walk, so halving the interval takes four times as many walks.

Properties

  • Unbiased, proved. Each walk, and the mean of any number of walks, has expectation equal to the answer, for every walk order, for acyclic and cyclic queries and with selections.
  • Asymptotic intervals. The confidence interval is based on the central limit theorem, so it is valid in the limit, not for a fixed number of walks.
  • Index based. It needs an index for each step of the walk order. Without indexes, it cannot run.
  • Variance depends on the order. The walk order changes the variance and the rate of failed walks, as the example shows, but not the mean.
  • No blocking. Walks are independent, so the estimate can be shown and improved at any time, and walks can run in parallel.

Variants and improvements

  • Walk plan optimizer. Section 4 of the paper runs trial walks for each valid order in turn, until one order has τ\tau successful walks (τ=100\tau = 100 by default), and then picks the order with the smallest estimate of Var[X]⋅E[T]\mathrm{Var}[X] \cdot E[T], the variance after a fixed time. This is a heuristic, and the paper measures it.
  • Cyclic queries. Walk a spanning tree of the query graph and check the other edges at the end (Section 3.5 of the paper).
  • Selections and GROUP BY. A walk that hits a row that fails a selection returns 0. For GROUP BY, each walk adds its value to the estimate of its group, and the walks of one group are used for its interval.
  • Cardinality estimation. With COUNT, the walks estimate the size of a join, which an optimizer can use in place of an estimate built on independence. Later work on sampling for cardinality estimation uses the same idea.
  • Other estimators. The same walks can be weighted with other designs, for example to lower variance by importance sampling on the choices. This page proves only the uniform version.

When to use it

Use it for interactive queries over large joins, when an approximate answer with an error bar is good enough and the join attributes have indexes, as foreign keys in a star schema usually do. It does well when the join is selective, where ripple join finds few results. It is a poor choice when indexes are missing, when the aggregate depends on very rare rows (the variance is then large), or when an exact answer is needed.

Pitfalls

  • Throwing away failed walks. A failed walk must add 0 to the sum. Rejecting it and walking again gives a biased estimate.
  • Wrong probability. At each step, the probability must use the size of the set the row was picked from. If the walk picks from all matching rows and then checks the selection, it must divide by the number of matching rows, not by the number that pass the selection.
  • Missing a cycle edge. In a cyclic query, a walk that is not checked against the edges outside the walk tree counts rows that are not in the join.
  • Trusting early intervals. With few successful walks, the sample variance can be far from the true variance, and the interval can be much too narrow, for example when no rare heavy row has been seen yet.
  • Correlated walks. The interval assumes independent walks. Walks that share a random seed or that sample without replacement need a different variance formula.

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.

wander_join.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wander-join/. The authors are listed in prov/SRQFRM.jsonl.
"""Wander join (Li, Wu, Yi and Zhao, SIGMOD 2016): online aggregation over joins by random walks.

A query is a natural join of relations, each a list of rows (dicts), with
optional selection predicates and an expression v over the joined row. The
aggregate is SUM(v); COUNT is SUM(1). A walk plan is an order of the
relations in which each relation after the first shares attributes with an
earlier one, its parent, and has an index on those attributes.

One walk picks a row of the first relation uniformly, then, for each next
relation, a uniform row among those that join with the row of its parent.
If the walk reaches a row with no match, or a row that fails a selection or
a join condition with a relation other than its parent (a cycle edge), the
walk fails and its estimate is 0. Otherwise the estimate is v / p, where p
is the probability of the walk. By the Horvitz-Thompson argument every
walk is an unbiased estimate of SUM(v), and so is the mean of many walks.
"""

import math
from fractions import Fraction
from random import Random
from typing import Callable, Dict, List, Optional, Sequence, Tuple

Row = Dict[str, object]
Pred = Callable[[Row], bool]


class WalkPlan:
    """A walk order with an index on the join attributes of each step."""

    def __init__(self, relations: Dict[str, List[Row]], order: Sequence[str],
                 predicates: Optional[Dict[str, Pred]] = None):
        self.relations = relations
        self.order = list(order)
        self.predicates = predicates or {}
        if sorted(self.order) != sorted(relations):
            raise ValueError("the order must name each relation once")
        attrs = {name: set(rows[0]) if rows else set() for name, rows in relations.items()}
        self.parent: Dict[str, str] = {}
        self.key: Dict[str, Tuple[str, ...]] = {}
        self.checks: Dict[str, List[Tuple[str, Tuple[str, ...]]]] = {}
        self.index: Dict[str, Dict[tuple, List[Row]]] = {}
        for i, name in enumerate(self.order[1:], start=1):
            earlier = self.order[:i]
            linked = [e for e in earlier if attrs[e] & attrs[name]]
            if not linked:
                raise ValueError("relation %s shares no attribute with an earlier one" % name)
            par = linked[0]
            self.parent[name] = par
            self.key[name] = tuple(sorted(attrs[par] & attrs[name]))
            # attributes shared with earlier relations other than the parent are checked after the step
            self.checks[name] = [(e, tuple(sorted(attrs[e] & attrs[name]))) for e in linked[1:]]
            idx: Dict[tuple, List[Row]] = {}
            for row in relations[name]:
                idx.setdefault(tuple(row[a] for a in self.key[name]), []).append(row)
            self.index[name] = idx

    def _ok(self, name: str, row: Row) -> bool:
        pred = self.predicates.get(name)
        return pred is None or bool(pred(row))

    def walk(self, rng: Random, value: Callable[[Row], float]) -> Tuple[float, int]:
        """One random walk. Returns (the estimate, the number of index lookups)."""
        first = self.relations[self.order[0]]
        if not first:
            return 0.0, 0
        t = {self.order[0]: first[rng.randrange(len(first))]}  # @line L2
        p_inv = len(first)
        if not self._ok(self.order[0], t[self.order[0]]):
            return 0.0, 0
        lookups = 0
        for name in self.order[1:]:  # @line L3
            par = t[self.parent[name]]
            matches = self.index[name].get(tuple(par[a] for a in self.key[name]), [])  # @line L4
            lookups += 1
            if not matches:  # @line L5
                return 0.0, lookups
            row = matches[rng.randrange(len(matches))]  # @line L6
            p_inv *= len(matches)
            if not self._ok(name, row):
                return 0.0, lookups
            for other, attrs in self.checks[name]:  # @line L7
                if any(t[other][a] != row[a] for a in attrs):
                    return 0.0, lookups
            t[name] = row
        joined: Row = {}
        for row in t.values():
            joined.update(row)
        return value(joined) * p_inv, lookups

    def exact_expectation(self, value: Callable[[Row], object]) -> Fraction:
        """The expected value of one walk: the sum, over every outcome of the
        random choices, of its probability times the estimate of `walk`.
        Failed walks have estimate 0 and are left out of the sum."""
        first = self.relations[self.order[0]]
        total = Fraction(0)

        def rec(i: int, t: Dict[str, Row], prob: Fraction, p_inv: int) -> Fraction:
            if i == len(self.order):
                joined: Row = {}
                for row in t.values():
                    joined.update(row)
                return prob * Fraction(value(joined)) * p_inv
            name = self.order[i]
            par = t[self.parent[name]]
            matches = self.index[name].get(tuple(par[a] for a in self.key[name]), [])
            s = Fraction(0)
            for row in matches:
                if not self._ok(name, row):
                    continue
                if any(t[o][a] != row[a] for o, attrs in self.checks[name] for a in attrs):
                    continue
                t2 = dict(t)
                t2[name] = row
                s += rec(i + 1, t2, prob / len(matches), p_inv * len(matches))
            return s

        for row in first:
            if self._ok(self.order[0], row):
                total += rec(1, {self.order[0]: row}, Fraction(1, len(first)), len(first))
        return total


def wander_join(plan: WalkPlan, value: Callable[[Row], float], walks: int, rng: Random,
                z: float = 1.96) -> Tuple[float, float]:
    """Run `walks` random walks. Returns (the estimate of SUM(value), the half-width of a z interval)."""
    xs = [plan.walk(rng, value)[0] for _ in range(walks)]  # @line L1
    mean = sum(xs) / walks  # @line L8
    if walks < 2:
        return mean, math.inf
    var = sum((x - mean) ** 2 for x in xs) / (walks - 1)
    return mean, z * math.sqrt(var / walks)


def choose_plan(plans: Sequence[WalkPlan], value: Callable[[Row], float], rng: Random,
                tau: int = 100, max_rounds: int = 100000) -> int:
    """Pick a walk plan by trial walks, as in Section 4 of the paper.

    Walk the plans round robin until one has tau successful walks. Among the
    plans with at least tau / 2 successes, return the index of the one with
    the smallest (sample variance of one walk) * (mean number of lookups).
    """
    xs: List[List[float]] = [[] for _ in plans]
    cost: List[int] = [0 for _ in plans]
    ok = [0 for _ in plans]
    for _ in range(max_rounds):
        for i, plan in enumerate(plans):
            x, c = plan.walk(rng, value)
            xs[i].append(x)
            cost[i] += c + 1
            ok[i] += x != 0
        if max(ok) >= tau:
            break
    best, best_score = -1, math.inf
    for i in range(len(plans)):
        if ok[i] < tau / 2:
            continue
        m = sum(xs[i]) / len(xs[i])
        var = sum((x - m) ** 2 for x in xs[i]) / max(1, len(xs[i]) - 1)
        score = var * cost[i] / len(xs[i])
        if score < best_score:
            best, best_score = i, score
    return best
test_wander_join.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wander-join/. The authors are listed in prov/SRQFRM.jsonl.

import itertools
import math
import unittest
from fractions import Fraction
from random import Random

from wander_join import WalkPlan, choose_plan, wander_join


def brute_force_sum(relations, value, predicates=None):
    """SUM(value) over the natural join, by nested loops over all relations."""
    predicates = predicates or {}
    names = sorted(relations)
    total = Fraction(0)
    for combo in itertools.product(*(relations[n] for n in names)):
        joined = {}
        good = True
        for name, row in zip(names, combo):
            if name in predicates and not predicates[name](row):
                good = False
                break
            for a, x in row.items():
                if a in joined and joined[a] != x:
                    good = False
                    break
                joined[a] = x
            if not good:
                break
        if good:
            total += Fraction(value(joined))
    return total


def valid_orders(relations):
    attrs = {n: set(rows[0]) for n, rows in relations.items()}
    for order in itertools.permutations(sorted(relations)):
        if all(any(attrs[order[j]] & attrs[order[i]] for j in range(i)) for i in range(1, len(order))):
            yield order


def page_example():
    R1 = [{"A": "a1", "B": "b1"}, {"A": "a2", "B": "b1"}, {"A": "a3", "B": "b2"}]
    R2 = [{"B": "b1", "C": "c1"}, {"B": "b1", "C": "c2"}, {"B": "b2", "C": "c3"}]
    R3 = [{"C": "c1", "D": 5}, {"C": "c2", "D": 1}, {"C": "c2", "D": 3}]
    return {"R1": R1, "R2": R2, "R3": R3}


def random_instance(rng, shape):
    dom = rng.randint(2, 4)

    def rel(schema, n):
        return [{a: rng.randrange(dom) for a in schema} | {"w": rng.randint(1, 9)} for _ in range(n)]

    if shape == "chain":
        rels = {"R": rel("ab", 5), "S": rel("bc", 5), "T": rel("cd", 5)}
    elif shape == "star":
        rels = {"R": rel("ab", 5), "S": rel("bc", 4), "T": rel("bd", 4), "U": rel("de", 3)}
    else:
        rels = {"R": rel("ab", 5), "S": rel("bc", 5), "T": rel("ca", 5)}
    # the weight column w is private to each relation
    for name, rows in rels.items():
        for row in rows:
            row["w_" + name] = row.pop("w")
    return rels


def weight_product(joined):
    return math.prod(x for a, x in joined.items() if a.startswith("w_"))


class TestExample(unittest.TestCase):
    def test_walks_of_the_page(self):
        rels = page_example()
        D = lambda j: j["D"]
        self.assertEqual(brute_force_sum(rels, D), 18)
        plan = WalkPlan(rels, ["R1", "R2", "R3"])
        self.assertEqual(plan.exact_expectation(D), 18)
        self.assertEqual(plan.exact_expectation(lambda j: 1), 6)
        rev = WalkPlan(rels, ["R3", "R2", "R1"])
        self.assertEqual(rev.exact_expectation(D), 18)
        # In the reverse order every walk succeeds and has probability 1/6.
        rng = Random(1)
        self.assertEqual({rev.walk(rng, lambda j: 1)[0] for _ in range(200)}, {6})
        seen = {plan.walk(rng, lambda j: 1)[0] for _ in range(400)}
        self.assertEqual(seen, {0, 6, 12})

    def test_choose_plan_prefers_the_reverse_order(self):
        rels = page_example()
        plans = [WalkPlan(rels, ["R1", "R2", "R3"]), WalkPlan(rels, ["R3", "R2", "R1"])]
        self.assertEqual(choose_plan(plans, lambda j: 1, Random(2), tau=50), 1)


class TestUnbiased(unittest.TestCase):
    def test_exact_expectation_equals_the_join(self):
        rng = Random(3)
        for trial in range(30):
            shape = ["chain", "star", "cycle"][trial % 3]
            rels = random_instance(rng, shape)
            preds = {}
            if trial % 2:
                preds = {"S": lambda row: row["w_S"] % 3 != 0}
            for value in (lambda j: 1, weight_product):
                truth = brute_force_sum(rels, value, preds)
                for order in valid_orders(rels):
                    plan = WalkPlan(rels, order, preds)
                    self.assertEqual(plan.exact_expectation(value), truth, (shape, order))

    def test_monte_carlo_mean(self):
        rng = Random(4)
        covered = 0
        runs = 0
        for trial in range(12):
            rels = random_instance(rng, ["chain", "star", "cycle"][trial % 3])
            truth = float(brute_force_sum(rels, weight_product))
            order = next(iter(valid_orders(rels)))
            plan = WalkPlan(rels, order)
            for _ in range(5):
                est, half = wander_join(plan, weight_product, 600, rng)
                runs += 1
                if abs(est - truth) <= half:
                    covered += 1
                # four standard errors
                self.assertLessEqual(abs(est - truth), 4 * half / 1.96 + 1e-9)
        # the 95 percent intervals should cover the truth in most runs
        self.assertGreaterEqual(covered / runs, 0.8)

    def test_mean_of_many_walks(self):
        rels = page_example()
        plan = WalkPlan(rels, ["R1", "R2", "R3"])
        rng = Random(5)
        est, half = wander_join(plan, lambda j: j["D"], 20000, rng)
        self.assertLess(abs(est - 18), 0.6)
        self.assertLess(half, 0.6)

    def test_bad_order(self):
        rels = page_example()
        with self.assertRaises(ValueError):
            WalkPlan(rels, ["R1", "R3", "R2"])


if __name__ == "__main__":
    unittest.main()

History

Online aggregation was proposed by Hellerstein, Haas and Wang in 1997, and Haas and Hellerstein gave ripple join for joins in 1999. Ripple join samples each table on its own, so it needs many samples before two of them join when the join is selective. Feifei Li, Bin Wu, Ke Yi and Zhuoyue Zhao noted in 2016 that the indexes a database already has let a sampler follow the join, and called the result wander join. Its estimate is the estimator of Horvitz and Thompson from 1952. Later work used the same kind of walks to estimate join sizes for query optimizers.

References

  1. Wander join: online aggregation via random walks, Section 3.1 (chain joins, the join data graph and the estimate v/p), Section 3.2 (acyclic queries and walk orders), Section 3.3 (confidence intervals), Section 3.4 (selections and GROUP BY), Section 3.5 (cyclic queries), Section 4 (the walk plan optimizer and trial walks)
  2. A generalization of sampling without replacement from a finite universe, the estimator that divides each sampled value by its probability of selection
  3. Peter J. Haas and Joseph M. Hellerstein, Ripple joins for online aggregation, Proceedings of ACM SIGMOD 1999, 287 to 298, the earlier online aggregation method for joins that wander join is compared with

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