Algorithm Search⌘K

Algorithmresearch

Eddies

Also called eddy operator, adaptive tuple routing.

An eddy sends each tuple through the filters and joins of a query in an order it chooses per tuple, from what it sees at run time. With timestamped SteMs, every order gives the same result.

Time
O(T m^2) expected
Space
O(T) extra
Where
T = the number of base and intermediate tuples built; m = the number of operators
Properties
randomizedexactnot greedyrandomizediterative
Origin
Ron Avnur, Joseph M. Hellerstein, 2000

An eddy is a query operator that decides, for each tuple, which operator of the query it visits next. Ron Avnur and Joseph M. Hellerstein gave it in 2000. A classic optimizer fixes one plan before the query starts, from estimates that can be wrong, and the plan stays fixed while data and costs change. An eddy sits between the operators of the query. Each operator returns its output to the eddy, and the eddy routes each tuple to an operator it has not yet visited. The routing policy can learn from what it sees, for example by sending tuples first to the filters that drop the most tuples. With state modules (SteMs) and timestamps, the result is the same for every routing choice and every arrival order, so the policy affects only the cost.

In plain words

Think of a mail room. Each letter must visit several desks, and the order of the desks does not change the letter at the end. But some desks throw away many letters, and some desks are slow. A clerk in the middle hands each letter to the next desk it still needs.

The clerk watches the desks. A desk that throws away many letters saves work for the desks after it, so the clerk sends letters there first. When a desk changes, the clerk changes the order for the next letters. No plan is fixed in advance.

For joins, each table keeps the rows it has seen in a store. A new row looks for partners in the stores of the other tables, in the order the clerk picks. A simple rule on arrival times makes sure that each answer comes out once.

The problem

The input is a query with joins of relations R1,…,RnR_1, \ldots, R_n and filters on single relations, and the tuples of the relations arrive over time, in any interleaving, at rates the system does not know in advance. The output is the join result, the same bag of rows as any static plan gives. The goal is to keep the work small (the number of operator calls and of intermediate results) when selectivities and costs are not known, or change while the query runs. A static plan can be bad for this input, and mid-query re-optimization can change the plan only at a few points.

The algorithm

Each base tuple, on arrival, gets a timestamp and is built into the SteM of its relation: a hash table of the tuples of that relation seen so far. Then a tuple in the eddy carries the set PP of base tuples joined so far, the set DD of filters it has passed, and the timestamp τ\tau of the arrival that started it. The paper keeps this state as bit vectors in the tuple. An operator is eligible for a tuple if it is a filter on a relation of PP that is not in DD, or the SteM of a relation not in PP that shares an attribute with PP.

  1. EDDY(arriving base tuples, filters, one SteM per relation, routing policy π)
  2. 1while base tuples arrive or tuples wait in the eddy do
  3. 2on the arrival of base tuple b of R_j: ts(b) ← the next timestamp; build b into SteM_j
  4. 3put (P = {b}, D = ∅, τ = ts(b)) into the eddy
  5. 4otherwise take a waiting tuple t = (P, D, τ)
  6. 5E ← the operators that are eligible for t
  7. 6if E is empty then output P (it joins every relation and passed every filter)
  8. 7else o ← π(E)
  9. 8if o is a filter: if t passes, put (P, D ∪ {o}, τ) back; else drop t
  10. 9if o is SteM_k: for each s in SteM_k with ts(s) < τ that joins with P, put (P ∪ {s}, D, τ) back

The lottery policy of the paper is in line L7. Each operator has tickets. An operator gets a ticket when the eddy gives it a tuple and loses a ticket for each tuple it returns, and the eddy picks among the eligible operators with probability proportional to their tickets. A filter that drops most of its input keeps most of its tickets, so it is picked more often. The paper adds a window to the ticket counts so that the policy forgets old behavior.

Example

Take R(a,b)R(a, b) with r1=(1,7)r_1 = (1, 7) and r2=(2,8)r_2 = (2, 8), and S(b,c)S(b, c) with s1=(7,3)s_1 = (7, 3) and s2=(7,4)s_2 = (7, 4). They arrive in the order r1,s1,r2,s2r_1, s_1, r_2, s_2, with timestamps 0 to 3, and each tuple is routed before the next one arrives.

step event result
1 r1r_1 arrives, is built into SteM(R), and probes SteM(S) SteM(S) is empty, nothing
2 s1s_1 arrives and probes SteM(R) for b=7b = 7 finds r1r_1 (timestamp 0 < 1), outputs (r1,s1)(r_1, s_1)
3 r2r_2 arrives and probes SteM(S) for b=8b = 8 no match
4 s2s_2 arrives and probes SteM(R) for b=7b = 7 finds r1r_1, outputs (r1,s2)(r_1, s_2)

Now let all four tuples arrive before any of them is routed, which can happen in a pipelined system. When the tuple of r1r_1 probes SteM(S), it sees s1s_1 and s2s_2, but both have later timestamps, so the probe returns nothing. The two results come from the probes of s1s_1 and s2s_2 as before. Without the timestamp test, r1r_1 would also find both and every result would come out twice. The code tests both cases.

For filters, take one relation with two filters: one passes 90 percent of the tuples, the other 10 percent, and both cost the same. The order "10 percent first" makes about 1+0.1=1.11 + 0.1 = 1.1 filter calls per tuple, and the other order about 1.91.9. On 3000 tuples, the lottery policy in the code makes 3318 calls, close to the 3288 of the better fixed order and far from the 5710 of the worse one. This is a measurement on one input, not a bound.

Correctness

The proof file proves that for every arrival order, every interleaving of arrivals with routing, and every routing policy, the eddy outputs each row of the filtered join exactly once. The invariant is that a tuple in the eddy is a consistent partial join row that passed the filters in DD, and that all its base tuples except the one that started it have smaller timestamps. If no operator is eligible, the tuple covers every relation (the join graph is connected) and passed every filter, so it is a result. A result γ\gamma is built from the routing of its base tuple with the largest timestamp, because every other tuple of γ\gamma is in its SteM by then, and each probe returns it. It is built only there, because a routing started by an earlier tuple of γ\gamma cannot see the later one. The routing choices form a tree, so γ\gamma is built once in that routing.

Proof: An eddy with timestamped SteMs outputs each row of the filtered join exactly once, for every arrival order and every routing policyfull

Setting. The query is a natural join of relations R1,…,RnR_1, \ldots, R_n with filters, each filter a predicate on one relation. The join graph has a node for each relation and an edge between two relations that share an attribute, and it is connected (the code rejects other queries). The answer is the bag AA of tuples γ=(r1,…,rn)\gamma = (r_1, \ldots, r_n), one base tuple rjr_j from each RjR_j, such that every filter holds on its tuple and rir_i and rjr_j agree on their shared attributes for each pair i,ji, j. Base tuples are distinct objects, so equal values in two tuples still give two results.

The base tuples arrive one at a time in an arbitrary order, and the mm-th arrival gets timestamp mm and is built into the SteM of its relation at once (line L2). Arrivals and routing steps interleave in an arbitrary way: at each step the eddy either takes the next arrival or routes one waiting tuple (lines L1 and L4), so tuples of earlier arrivals can still be in the eddy when later tuples arrive. A tuple in the eddy is a partial result t=(P,D,τ)t = (P, D, \tau): a set PP of base tuples from a set S(P)S(P) of relations, the set DD of filters it has passed, and the timestamp τ\tau of the base tuple whose arrival started it (line L3). An operator is eligible for tt (line L5) if it is a filter on a relation in S(P)S(P) that is not in DD, or the SteM of a relation Rj∉S(P)R_j \notin S(P) that shares an attribute with a relation in S(P)S(P). The routing policy may choose any eligible operator (line L7); it may use randomness and the whole history. A filter passes tt on with the filter added to DD, or drops it (line L8). A probe into the SteM of RjR_j returns the base tuples ss of RjR_j with timestamp less than τ\tau that agree with PP on the attributes RjR_j shares with S(P)S(P), and adds P∪{s}P \cup \{s\} for each such ss (line L9). A tuple with no eligible operator is output (line L6).

Lemma 1 (invariant). For every tuple (P,D,τ)(P, D, \tau) in the queue: the base tuples of PP agree on all shared attributes; every filter in DD holds on its tuple; PP contains the base tuple bb with timestamp τ\tau; and every other tuple of PP has timestamp less than τ\tau.

Proof. By induction on the steps. The tuple of line L3 is ({b},∅,ts(b))(\{b\}, \emptyset, \mathrm{ts}(b)). A filter adds itself to DD only when it holds. A probe adds a tuple ss that agrees with PP on all attributes it shares with S(P)S(P), and whose timestamp is less than τ\tau. □\square

Lemma 2 (output is complete). A tuple with no eligible operator has S(P)S(P) equal to all relations and DD equal to all filters, so by Lemma 1 it is a row of AA.

Proof. If some relation is not in S(P)S(P), then, because the join graph is connected, some relation outside S(P)S(P) shares an attribute with one inside, and its SteM is eligible. So S(P)S(P) is all relations, and then every filter not in DD is eligible. □\square

Theorem 1. For every arrival order and every routing policy, the eddy outputs every row of AA exactly once and nothing else.

Proof. By Lemma 2, every output is in AA. Now fix γ=(r1,…,rn)∈A\gamma = (r_1, \ldots, r_n) \in A, and let bb be its base tuple with the largest timestamp τ\tau.

At least once. When bb arrives, all other tuples of γ\gamma have arrived and are in their SteMs, with timestamps less than τ\tau, and they stay there. Follow the tuple ({b},∅,τ)(\{b\}, \emptyset, \tau) and, at each step, the one queued tuple whose PP is a subset of γ\gamma. When the policy chooses a filter, the filter holds on the part of γ\gamma it tests, so the tuple goes on. When it chooses the SteM of RjR_j, the tuple rjr_j of γ\gamma agrees with PP (because γ\gamma is a join row) and has timestamp less than τ\tau, so the probe returns it and queues P∪{rj}P \cup \{r_j\}. Each step adds a relation or a filter, so after finitely many steps the tuple has no eligible operator and has P=γP = \gamma; it is output.

At most once. An output of γ\gamma comes from a tuple started by some base tuple b′b' of γ\gamma (Lemma 1). If b′≠bb' \ne b, then bb is in PP with timestamp τ>ts(b′)\tau > \mathrm{ts}(b'), which contradicts Lemma 1. So every output of γ\gamma comes from the routing that started at the arrival of bb. In that routing, each queued tuple is routed to exactly one operator, and each operator queues each successor at most once: a filter queues one tuple, and a probe queues one tuple for each distinct matching SteM entry. So the queued tuples form a tree under the parent relation "was produced from", and the tuples whose PP is a subset of γ\gamma form a single path from the root, because a probe into RjR_j produces at most one tuple whose new part is rjr_j. So γ\gamma is output at most once. ■\blacksquare

Why the timestamps matter. Take R(a,b)={r1}R(a, b) = \{r_1\} and S(b,c)={s1}S(b, c) = \{s_1\} with r1r_1 and s1s_1 equal on bb, and let r1r_1 and then s1s_1 arrive before any routing step. Without the test ts(s)<τ\mathrm{ts}(s) < \tau, the tuple of r1r_1 probes the SteM of SS and finds s1s_1, and the tuple of s1s_1 probes the SteM of RR and finds r1r_1, so the result is output twice. With the test, only the tuple of s1s_1, the later arrival, finds its partner. The tests of the code show this case and also random cases where results repeat without timestamps. If each arrival is routed to the end before the next one arrives, the test never removes anything, because a SteM then holds only earlier tuples; it is needed because a pipelined eddy keeps old tuples in flight.

Termination and work. Each routing step adds a relation or a filter to the tuple, so a tuple is routed at most n+fn + f times, where ff is the number of filters. Each probe returns finitely many tuples, so the tuples started by one arrival form a finite tree, and the run ends after all arrivals have come and the eddy is empty. The total number of probe results over the run is the number of partial join results the chosen orders build, and this is the quantity a good policy keeps small.

The lottery policy. The lottery policy gives an operator a ticket when it receives a tuple and takes one away for each tuple it returns, and draws among the eligible operators with probability proportional to the tickets. A filter that drops a fraction 1−σ1 - \sigma of its input gains about (1−σ)(1 - \sigma) tickets per tuple, so the most selective filters gain tickets fastest and are tried first. This is a heuristic: Theorem 1 holds for every policy, but no bound on the work of the lottery policy is proved here. The tests measure it on a two filter query, where it does close to the work of the better fixed order.

Complexity

Let TT be the number of tuples the eddy builds (base tuples, tuples after each filter, and partial join results) and mm the number of operators. Each built tuple is routed once, and finding the eligible operators costs O(m)O(m) attribute checks, so the routing costs O(Tm2)O(T m^2) in the worst case of this simple code; a real eddy keeps bit vectors and makes this O(m)O(m) word operations per routing. A probe of a SteM is a hash lookup, O(1)O(1) expected plus the matches. The SteMs keep every base tuple, and the eddy keeps the waiting tuples, so the space is O(T)O(T). TT depends on the routing: a good policy keeps the number of intermediate results small, as a good static plan does. The routing decision for each tuple is the overhead of an eddy against a fixed plan, and the paper measures it as small in its prototype.

Properties

  • Correct for every policy, proved. The output bag does not depend on the routing policy or on the arrival order.
  • Adaptive per tuple. Two tuples of the same relation can take different orders. The order can change at any time, not only at points fixed in advance.
  • Heuristic routing. The lottery policy has no proved bound on its work. Its benefit is measured.
  • Pipelined. Results come out while the input arrives, as with a symmetric hash join, which suits streams and remote sources.
  • Memory heavy. SteMs keep every base tuple, so the memory is that of a symmetric hash join on every relation.

Variants and improvements

  • Binary join operators. The original eddy routed tuples among fixed pipelined join operators, such as ripple joins and index joins, and could reorder only at moments of symmetry, when a join can take input from either side. SteMs (Raman, Deshpande and Hellerstein, 2003) split each join into its two hash tables, so the eddy also chooses the join order and the access method for each tuple.
  • Back-pressure. The paper first routes by the queue lengths of the operators, so that fast operators get more tuples, and then adds lottery tickets to learn selectivity.
  • Continuous queries. Eddies were used in the Telegraph project for continuous queries over streams, where many queries share one eddy and one set of SteMs.
  • Routing as learning. Choosing the next operator for many tuples is close to a multi-armed bandit problem, and later work used ideas from learning for the routing policy.
  • Plan switching. Mid-query re-optimization changes the plan a few times at checkpoints; eddies go to the other end and decide for every tuple.

When to use it

Use an eddy when the inputs are streams or remote sources with unknown and changing rates and selectivities, when statistics are missing, or when a query runs long enough for the data to change. For short queries over local tables with good statistics, a static plan from a cost-based optimizer is usually cheaper, because it pays no routing cost per tuple and it can use blocking operators such as sort and hash join builds.

Pitfalls

  • Duplicate results. If tuples of earlier arrivals can still probe after later tuples are built, some results are found twice. The timestamp test of line L9, or an equivalent rule, is required.
  • Forgetting filters of joined tuples. A tuple from a SteM joins a partial result before its own filters have run. The eddy must route the new tuple through those filters too, or it outputs rows that fail them.
  • Cross products. If the policy probes a SteM that shares no attribute with the tuple, it builds a cross product. Allow only connected probes when the join graph is connected.
  • Slow adaptation. Ticket counts that are never aged keep a policy on an old order after the data changes.
  • Routing overhead. A routing decision per tuple costs more than a fixed pipeline, so for cheap filters the overhead can be larger than the saving.

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.

eddies.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eddies/. The authors are listed in prov/CC4NGE.jsonl.
"""An eddy (Avnur and Hellerstein, SIGMOD 2000) with one SteM per relation.

The query is a natural join of relations with selection filters on single
relations. Base tuples arrive one at a time, in any interleaving of the
relations. Each arriving tuple gets a timestamp and is built into the SteM
(state module, an index of the tuples seen so far) of its relation. Then the
eddy routes the tuple, one operator at a time, through the filters of the
relations it covers and through probes into the SteMs of the other relations.
A routing policy chooses the next operator for each tuple separately, and
routing steps interleave with new arrivals, as in a pipelined system.

A probe returns only SteM entries with a smaller timestamp than the base
tuple that started the routing. So each result is built only from the base
tuple of the result that arrived last, and each result is output exactly
once, for every arrival order and every routing policy.
"""

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

Row = Dict[str, object]


class SteM:
    """A state module: the tuples of one relation seen so far, with hash indexes built on demand."""

    def __init__(self) -> None:
        self.rows: List[Tuple[int, Row]] = []
        self.idx: Dict[Tuple[str, ...], Dict[tuple, List[Tuple[int, Row]]]] = {}

    def build(self, ts: int, row: Row) -> None:
        self.rows.append((ts, row))
        for attrs, d in self.idx.items():
            d.setdefault(tuple(row[a] for a in attrs), []).append((ts, row))

    def probe(self, attrs: Tuple[str, ...], key: tuple, before: int) -> List[Row]:
        if attrs not in self.idx:
            d: Dict[tuple, List[Tuple[int, Row]]] = {}
            for ts, row in self.rows:
                d.setdefault(tuple(row[a] for a in attrs), []).append((ts, row))
            self.idx[attrs] = d
        return [row for ts, row in self.idx[attrs].get(key, []) if ts < before]


class FixedPolicy:
    """Always choose the first eligible operator in a fixed priority list."""

    def __init__(self, priority: Sequence[str]):
        self.rank = {op: i for i, op in enumerate(priority)}

    def choose(self, eligible: List[str], rng: Random) -> str:
        return min(eligible, key=lambda op: self.rank.get(op, len(self.rank)))

    def feedback(self, op: str, returned: int) -> None:
        pass


class RandomPolicy:
    """Choose an eligible operator uniformly at random."""

    def choose(self, eligible: List[str], rng: Random) -> str:
        return eligible[rng.randrange(len(eligible))]

    def feedback(self, op: str, returned: int) -> None:
        pass


class LotteryPolicy:
    """Lottery scheduling: an operator gets a ticket for each tuple it receives
    and loses one for each tuple it returns. The eddy draws an eligible operator
    with probability proportional to its tickets (at least 1)."""

    def __init__(self) -> None:
        self.tickets: Dict[str, int] = {}

    def choose(self, eligible: List[str], rng: Random) -> str:
        weights = [max(1, self.tickets.get(op, 1)) for op in eligible]
        x = rng.randrange(sum(weights))
        for op, w in zip(eligible, weights):
            if x < w:
                break
            x -= w
        self.tickets[op] = self.tickets.get(op, 1) + 1
        return op

    def feedback(self, op: str, returned: int) -> None:
        self.tickets[op] = max(1, self.tickets.get(op, 1) - returned)


class Eddy:
    """A natural join of `schemas` (relation name to attribute names) with
    `filters` (filter name to (relation name, predicate))."""

    def __init__(self, schemas: Dict[str, Sequence[str]],
                 filters: Optional[Dict[str, Tuple[str, Callable[[Row], bool]]]] = None,
                 costs: Optional[Dict[str, float]] = None):
        self.schemas = {r: set(a) for r, a in schemas.items()}
        self.filters = filters or {}
        self.costs = costs or {}
        names = list(self.schemas)
        reached = {names[0]} if names else set()
        grow = True
        while grow:
            grow = False
            for r in names:
                if r not in reached and any(self.schemas[r] & self.schemas[q] for q in reached):
                    reached.add(r)
                    grow = True
        if len(reached) != len(names):
            raise ValueError("the join graph is not connected")
        self.stems = {r: SteM() for r in names}
        self.work: Dict[str, float] = {}

    def _eligible(self, parts: Dict[str, Row], done: frozenset) -> List[str]:
        ops = [f for f, (rel, _) in self.filters.items() if rel in parts and f not in done]
        for r in self.schemas:
            if r not in parts and any(self.schemas[r] & self.schemas[q] for q in parts):
                ops.append("stem:" + r)
        return ops

    def run(self, arrivals: Sequence[Tuple[str, Row]], policy, rng: Random,
            p_route: float = 0.5, use_timestamps: bool = True) -> List[Dict[str, Row]]:
        """Process the arrivals in order. Returns the results, each a dict from relation to row.

        Arrivals and routing steps interleave: while tuples wait in the eddy,
        the next step routes one of them, chosen at random, with probability
        p_route, and otherwise takes the next arrival. With p_route = 1, each
        arrival is routed to the end before the next one. use_timestamps =
        False turns off the timestamp test of the probes, to show why it is
        needed."""
        out: List[Dict[str, Row]] = []
        waiting: List[Tuple[Dict[str, Row], frozenset, int]] = []
        nxt = 0
        while nxt < len(arrivals) or waiting:  # @line L1
            if nxt < len(arrivals) and (not waiting or rng.random() >= p_route):
                rel, row = arrivals[nxt]
                self.stems[rel].build(nxt, row)  # @line L2
                waiting.append(({rel: row}, frozenset(), nxt))  # @line L3
                nxt += 1
                continue
            i = rng.randrange(len(waiting))
            waiting[i], waiting[-1] = waiting[-1], waiting[i]
            parts, done, tau = waiting.pop()  # @line L4
            eligible = self._eligible(parts, done)  # @line L5
            if not eligible:  # @line L6
                out.append(parts)
                continue
            op = policy.choose(eligible, rng)  # @line L7
            self.work[op] = self.work.get(op, 0) + self.costs.get(op, 1)
            if not op.startswith("stem:"):  # @line L8
                frel, pred = self.filters[op]
                if pred(parts[frel]):
                    waiting.append((parts, done | {op}, tau))
                    policy.feedback(op, 1)
                else:
                    policy.feedback(op, 0)
                continue
            target = op[5:]
            attrs = tuple(sorted(set().union(*(self.schemas[target] & self.schemas[q] for q in parts))))
            key = []
            for a in attrs:
                key.append(next(parts[q][a] for q in parts if a in self.schemas[q]))
            before = tau if use_timestamps else len(arrivals)
            matches = self.stems[target].probe(attrs, tuple(key), before)  # @line L9
            for m in matches:
                p2 = dict(parts)
                p2[target] = m
                waiting.append((p2, done, tau))
            policy.feedback(op, len(matches))
        return out


def random_arrivals(relations: Dict[str, List[Row]], rng: Random) -> List[Tuple[str, Row]]:
    """All base tuples of all relations, in a uniform random order of arrival."""
    seq = [(r, row) for r, rows in relations.items() for row in rows]
    rng.shuffle(seq)
    return seq
test_eddies.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eddies/. The authors are listed in prov/CC4NGE.jsonl.

import itertools
import unittest
from collections import Counter
from random import Random

from eddies import Eddy, FixedPolicy, LotteryPolicy, RandomPolicy, random_arrivals


def canon(parts):
    return tuple(sorted((r, id(row)) for r, row in parts.items()))


def brute_force(schemas, relations, filters):
    """The bag of results of the filtered natural join, by nested loops."""
    names = sorted(schemas)
    out = Counter()
    for combo in itertools.product(*(relations[n] for n in names)):
        parts = dict(zip(names, combo))
        if any(not pred(parts[rel]) for rel, pred in filters.values()):
            continue
        ok = all(parts[a][x] == parts[b][x]
                 for a, b in itertools.combinations(names, 2)
                 for x in set(schemas[a]) & set(schemas[b]))
        if ok:
            out[canon(parts)] += 1
    return out


SHAPES = {
    "chain": {"R": "ab", "S": "bc", "T": "cd"},
    "star": {"R": "ab", "S": "bc", "T": "bd", "U": "de"},
    "cycle": {"R": "ab", "S": "bc", "T": "ca"},
    "single": {"R": "ab"},
}


def instance(rng, shape):
    # the attribute w_<relation> is private to one relation, so it is not a join attribute
    schemas = {r: list(a) + ["w_" + r] for r, a in SHAPES[shape].items()}
    dom = rng.randint(2, 3)
    relations = {r: [{a: rng.randrange(dom) for a in schema} for _ in range(rng.randint(3, 7))]
                 for r, schema in schemas.items()}
    # rows are distinct objects even when their values repeat, so the join is a bag join
    filters = {}
    if rng.random() < 0.7:
        filters["f1"] = ("R", lambda row: row["w_R"] != 0)
    if rng.random() < 0.5:
        last = sorted(schemas)[-1]
        attr = schemas[last][0]
        filters["f2"] = (last, lambda row: row[attr] != 1)
    return schemas, relations, filters


def policies(names, filters):
    ops = list(filters) + ["stem:" + r for r in names]
    return [LotteryPolicy(), RandomPolicy(), FixedPolicy(ops), FixedPolicy(ops[::-1])]


class TestResults(unittest.TestCase):
    def test_same_bag_for_every_policy_and_order(self):
        rng = Random(1)
        for trial in range(60):
            shape = ["chain", "star", "cycle", "single"][trial % 4]
            schemas, relations, filters = instance(rng, shape)
            truth = brute_force(schemas, relations, filters)
            for policy in policies(list(schemas), filters):
                for p_route in (0.2, 0.6, 1.0):
                    eddy = Eddy(schemas, filters)
                    out = eddy.run(random_arrivals(relations, rng), policy, rng, p_route=p_route)
                    got = Counter(canon(p) for p in out)
                    self.assertEqual(got, truth, (shape, type(policy).__name__, p_route))
                    self.assertTrue(all(c == 1 for c in got.values()))

    def test_without_timestamps_results_repeat(self):
        rng = Random(5)
        repeated = 0
        for trial in range(40):
            schemas, relations, filters = instance(rng, ["chain", "star", "cycle"][trial % 3])
            truth = brute_force(schemas, relations, filters)
            out = Eddy(schemas, filters).run(random_arrivals(relations, rng), RandomPolicy(), rng,
                                             p_route=0.3, use_timestamps=False)
            got = Counter(canon(p) for p in out)
            # every result is still found, but some are found more than once
            self.assertEqual(set(got), set(truth))
            repeated += sum(got.values()) > sum(truth.values())
        self.assertGreater(repeated, 0)

    def test_one_relation_at_a_time(self):
        # all of R arrives first, then all of S, then all of T: the plan of a static pipeline
        rng = Random(2)
        schemas, relations, filters = instance(rng, "chain")
        arrivals = [(r, row) for r in ["R", "S", "T"] for row in relations[r]]
        got = Counter(canon(p) for p in Eddy(schemas, filters).run(arrivals, LotteryPolicy(), rng))
        self.assertEqual(got, brute_force(schemas, relations, filters))

    def test_example_of_the_page(self):
        schemas = {"R": ["a", "b"], "S": ["b", "c"]}
        r1, r2 = {"a": 1, "b": 7}, {"a": 2, "b": 8}
        s1, s2 = {"b": 7, "c": 3}, {"b": 7, "c": 4}
        arrivals = [("R", r1), ("S", s1), ("R", r2), ("S", s2)]
        out = Eddy(schemas).run(arrivals, RandomPolicy(), Random(0), p_route=1.0)
        # (r1, s1) is built when s1 arrives, and (r1, s2) when s2 arrives; r2 joins nothing
        self.assertEqual([(p["R"], p["S"]) for p in out], [(r1, s1), (r1, s2)])
        # all four tuples arrive before any routing: r1 must not probe S, or both results repeat
        out = Eddy(schemas).run(arrivals, RandomPolicy(), Random(0), p_route=0.0)
        self.assertEqual(sorted((p["S"]["c"]) for p in out), [3, 4])
        out = Eddy(schemas).run(arrivals, RandomPolicy(), Random(0), p_route=0.0, use_timestamps=False)
        self.assertEqual(sorted((p["S"]["c"]) for p in out), [3, 3, 4, 4])

    def test_disconnected_query(self):
        with self.assertRaises(ValueError):
            Eddy({"R": ["a"], "S": ["b"]})


class TestAdaptivity(unittest.TestCase):
    def run_filters(self, policy, seed):
        rng = Random(seed)
        rows = [{"x": rng.random(), "y": rng.random()} for _ in range(3000)]
        filters = {"cheap_pass": ("R", lambda r: r["x"] < 0.9), "rare_pass": ("R", lambda r: r["y"] < 0.1)}
        eddy = Eddy({"R": ["x", "y"]}, filters)
        out = eddy.run([("R", r) for r in rows], policy, rng)
        return len(out), sum(eddy.work.values())

    def test_lottery_learns_the_selective_filter(self):
        n_good, w_good = self.run_filters(FixedPolicy(["rare_pass", "cheap_pass"]), 3)
        n_bad, w_bad = self.run_filters(FixedPolicy(["cheap_pass", "rare_pass"]), 3)
        n_lot, w_lot = self.run_filters(LotteryPolicy(), 3)
        self.assertEqual(n_good, n_bad)
        self.assertEqual(n_good, n_lot)
        # about 3300 and 5700 filter calls for the two fixed orders
        self.assertLess(w_good, 3500)
        self.assertGreater(w_bad, 5400)
        self.assertLess(w_lot, w_good + 400)

    def test_lottery_tickets(self):
        policy = LotteryPolicy()
        self.run_filters(policy, 4)
        self.assertGreater(policy.tickets["rare_pass"], 10 * policy.tickets["cheap_pass"])


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

History

Adaptive query processing grew from the observation that static plans fail when estimates are wrong or when data comes from slow or changing sources. Query scrambling and mid-query re-optimization changed plans at a few points. Ron Avnur and Joseph M. Hellerstein proposed the eddy in 2000 in the Telegraph project at Berkeley, which went to the other end and made the order a decision for each tuple, with a lottery policy borrowed from operating system scheduling. Raman, Deshpande and Hellerstein added SteMs in 2003, which let the eddy also choose join orders and access methods, and later Telegraph work used eddies for shared continuous queries over streams.

References

  1. Eddies: continuously adaptive query processing, the eddy operator, moments of symmetry, the done and ready bits of a tuple, and routing by lottery scheduling
  2. Using state modules for adaptive query processing, SteMs, which let the eddy choose the join order for each tuple, and the timestamp rule against duplicate results

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
  • at least three sources
  • a scene preset for the example