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
- Model
- Real RAM
- Properties
- randomizednot exactnot greedyrandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of its choices and returns , where 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 with optional selections, and an expression over the joined rows. The answer is over the join result ; COUNT is , 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 and a confidence interval that shrinks as more walks are done.
The algorithm
A walk order lists the relations so that each relation after the first shares attributes with an earlier one, its parent . 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.
WANDER-JOIN(walk order R_λ(1), ..., R_λ(k), indexes, expression v, number of walks W)- 1
for w ← 1 to W do - 2
pick t_1 uniformly from R_λ(1); p ← 1/|R_λ(1)| - 3
for i ← 2 to k do - 4
M ← the rows of R_λ(i) that join with t_η(i), found with the index - 5
if M is empty, or a selection fails, then X_w ← 0 and go to the next walk - 6
pick t_i uniformly from M; p ← p/|M| - 7
if the path fails a join condition outside the walk tree, or a selection, then X_w ← 0 else X_w ← v(path)/p - 8
return 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 is not fixed in advance.
Example
This is a small chain join with COUNT, like the example of Section 3.1 of the paper.
| relation | rows |
|---|---|
| , , | |
| , , | |
| , , |
The join has 6 rows: or , then , then one of the three rows of through or .
In the order , the walk starts at one of 3 rows. From it goes to , and has no row with , so the walk fails and returns 0. From or it has 2 choices in . Through there is 1 row in , so . Through there are 2 rows, so . The three values 0, 6 and 12 each have probability , so the mean is 6, the true count, and the variance is 24.
In the order , every row of has exactly one match in , and has two matches in . Every walk succeeds with , so every walk returns exactly 6 and the variance is 0. For SUM(D), the walks in this order return , or , 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 of the join can be reached by exactly one sequence of choices, with probability . So the successful walks and the join rows are in one-to-one correspondence, and
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 independent walks is unbiased with variance , and the interval of line L8 comes from the central limit theorem, so its coverage of 95 percent holds only as 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 , taken in the walk order, with a selection predicate on each (true if there is none) and an expression of the joined row. The join result is the set of tuples with , true for each , and and equal on the attributes they share, for each pair . The answer is ; COUNT is the case . The walk order has, for each , a parent that shares attributes with , and an index on for those shared attributes. For a row of , let be the set of rows of that agree with on those attributes. Every other pair of relations that share attributes is a check of step (line L7). For , let .
The walk. Line L2 picks uniformly from . For , lines L4 to L6 pick uniformly from , and the walk fails if this set is empty. The walk also fails if some fails or a check of line L7. A walk that does not fail is successful, and its estimate is , where
is the product of the probabilities of the choices (with read as ). A failed walk has estimate .
Lemma 1 (successful walks are the join result). The successful walks are exactly the tuples of , and the walk that ends with has probability .
Proof. Let a walk be successful and end with . Each holds, because the walk did not fail. Take a pair of relations that share attributes. If , then , so the two rows agree on all shared attributes; the key of step is the full set of attributes shared with the parent. Otherwise the pair is a check of step , and line L7 passed. So .
Now let . Then , and for each , agrees with on their shared attributes, so and this set is not empty. So the walk can choose in turn, and the probability of these choices is the product of the probabilities , that is . All predicates and checks hold for , so this walk is successful. Two walks with different choices end with different tuples, so each comes from exactly one sequence of choices.
Theorem 1 (unbiased). .
Proof. Failed walks add 0 to the expectation. By Lemma 1 the successful walks are the events "the walk ends with ", one for each ; they are disjoint and have probability . So
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 ; it changes only the distribution of . The code computes 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 be independent walks and their mean (line L8). Then and , where . The sample variance has .
Proof. The walk has finitely many outcomes, so is finite. Linearity of expectation gives , independence gives , and the statement on is the standard fact for independent samples with the same distribution.
The interval. By the central limit theorem, tends in distribution to a standard normal variable, and so does , because in probability. So with covers with probability that tends to 0.95 as grows. This is a large sample statement, not a bound for a fixed . For a bound that holds for every , Chebyshev's inequality gives , which needs or an upper bound on it.
Cost of a walk. A walk does at most 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 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 . The extra space is the current path, , and three running sums for and .
Choice of walk order. After time , a plan with mean time per walk has done about walks, so the variance of its estimate is about . Choosing the plan with the smallest estimated , 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 , , and COUNT. The join has 6 tuples. In the order , the walk fails with probability (from , the row has no match), gives with probability , and gives with probability . The mean is and the variance is . In the order , every walk succeeds with , so the estimate is always 6 and the variance is 0.
Complexity
A walk does at most index lookups and random choices. With hash indexes that keep each group of rows in an array, a walk costs expected time, and walks cost . With B-trees, each lookup costs , 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 , where 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 successful walks ( by default), and then picks the order with the smallest estimate of , 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.
# 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
- 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)
- A generalization of sampling without replacement from a finite universe, the estimator that divides each sampled value by its probability of selection
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SRQFRM Edit this page History Report an error Markdown