Algorithm Search⌘K

Algorithmadvanced

Cascades optimization framework

Also called Cascades optimizer, memo-based top-down optimization, Cascades search.

A rule-driven top-down optimizer that explores groups of equivalent expressions in a memo with tasks, promises and branch-and-bound pruning.

Time
O(4^n) explorationO(3^n) search without pruning
Space
O(3^n) memo
Where
n = the number of relations in the join model of this page
Properties
deterministicexactiterative
Origin
Goetz Graefe, 1995

Cascades is a framework for query optimizers that Goetz Graefe described in 1995 as the successor of the Volcano optimizer generator. Like Volcano, it keeps equivalent logical expressions in groups of a memo and searches top down for the cheapest plan of a group with a required physical property, with memoization and a cost limit. The difference is the control of the search. Volcano applies all transformation rules first and only then searches for plans. Cascades works with a stack of small tasks: it explores a group only when a goal needs it, applies the rules of each expression in the order of their promise, and optimizes an input group only with an upper bound that comes from the best plan so far. Rules, enforcers and promises are objects that the builder of an optimizer supplies. Many industrial optimizers follow this design.

In plain words

An optimizer must pick a cheap way to run a query among many equivalent ones. Cascades keeps a notebook: on each page it writes a group of query parts that give the same result, and the best known way to compute that group with the needed sort order.

The work is a to-do list. A typical item says: find the best way to compute this group, sorted, for less than this cost. To do it, the optimizer first writes all equivalent forms of the group into the notebook, then tries each method, starting with the one that looks most promising, and adds new items for the inputs. If the inputs already cost more than the best answer so far, it drops the method. When all items for the group are done, it writes the winner, or notes that nothing was cheap enough.

The problem

The input is a logical query and a required physical property; the output is a physical plan of least cost that gives the property. A goal is a pair of a group and a required property, with an upper bound on the cost. A winner of a goal is its best plan; a failure records that no plan is below a bound.

The code of this page uses the join model of the Volcano page. Relations R0,…,Rn−1R_0, \ldots, R_{n-1} share one join attribute kk, a group is a set of relations, and the rules are join commutativity and associativity. The property is the sort order on kk. The algorithms are TableScan, IndexScan (sorted, if RR has an index on kk), HashJoin, MergeJoin (both inputs sorted, output sorted) and NestedLoop (keeps the order of the outer input), and the enforcer is Sort. Their local costs are in the code.

The algorithm

  1. CASCADES(query, required property p)
  2. 1put the query in the memo and push O_GROUP(the group of the query, p, ∞)
  3. 2while the stack is not empty, pop the top task and run it
  4. 3return the plan of the winner of (the group of the query, p)
  1. O_GROUP(S, p, limit)
  2. 1if (S, p) has a winner, or a failure with a bound of at least limit, return
  3. 2if S is not explored, push O_GROUP(S, p, limit) again and E_GROUP(S) on top of it, and return
  4. 3make a context (S, p, limit); push FINISH(context), then O_EXPR(context, e) for each expression e of S, and the enforcer move for p
  5. E_GROUP(S)
  6. 4if S is explored or being explored, return; else push MARK_EXPLORED(S), then E_EXPR(S, e) for each expression e of S
  7. E_EXPR(S, e)
  8. 5for each rule not yet applied to e: mark it, push APPLY_RULE(S, e, rule), and on top push E_GROUP of each input group that the pattern of the rule looks into
  9. APPLY_RULE(S, e, rule)
  10. 6add the new expressions to their groups, and push E_EXPR(S, f) for each new expression f of S
  11. O_EXPR(context, e)
  12. 7push O_INPUTS(context, move) for each algorithm that implements e and gives p, so that the most promising move runs first
  13. O_INPUTS(context, move), which can stop and resume
  14. 8while the move has an input goal (G, q) left do
  15. 9if total ≥ context.limit, or (G, q) failed with a bound of at least context.limit - total, drop the move and return
  16. 10if (G, q) has a winner, add its cost to total and go to the next input
  17. 11push this task again, push O_GROUP(G, q, context.limit - total) on top of it, and return
  18. 12if total < context.limit, make the move the best of the context and set context.limit ← total
  19. FINISH(context)
  20. 13store the best move as the winner of (S, p), or store a failure with the first limit of the context
  21. MARK_EXPLORED(S)
  22. 14mark S as explored

Line L5 is exploration on demand: a group is explored only when a goal needs it. Line L8 pushes E_GROUP above APPLY_RULE, so the input group of a pattern is explored before the rule binds it, as associativity needs all expressions of its left input. Line L14 shows the branch and bound: an input goal gets only the part of the limit that is left. The promise in this code is the local cost of a move, so cheap moves run first and set a low limit early. In this toy model the transformation rules are applied during exploration and the algorithms during optimization; in the framework both kinds of rule are objects with a pattern, a promise and a condition.

Example

Take the data of the Volcano page: ∣R0∣=200|R_0| = 200, ∣R1∣=100|R_1| = 100, ∣R2∣=50|R_2| = 50, with 100, 50 and 10 distinct values of kk, and an index on R0.kR_0.k only, so ∣R1⋈R2∣=100|R_1 \bowtie R_2| = 100 and the result has 200 rows. Ask for any order. These are the first steps for the goal of the whole query.

step move input goals and their limits result limit after
1 MergeJoin(R0R1R_0 R_1, R2R_2), local 250 sorted R0R1R_0 R_1 and sorted R2R_2, limit ∞\infty 1400 1400
2 HashJoin(R0R1R_0 R_1, R2R_2), local 300 winners exist: 700 and 50 1050 1050
3 MergeJoin(R0R_0, R1R2R_1 R_2), local 300 sorted R0R_0 costs 400; sorted R1R2R_1 R_2 gets the limit 350 fails 1050
4 HashJoin(R0R_0, R1R2R_1 R_2), local 400 R0R_0 costs 200; R1R2R_1 R_2 (any order) gets the limit 450 and wins with 350 950 950

Inside step 3, the goal "sorted R1R2R_1 R_2 below 350" tries its Sort move, whose local cost is 200, so it asks for "R1R2R_1 R_2 in any order below 150". That goal fails, and its failure is stored with the bound 150. In step 4 the same group is asked again with the higher limit 450, so the search runs again and finds the hash join at 350. No later move beats 950. Later, the merge join of R0R2R_0 R_2 and R1R_1, with local cost 200, asks for "sorted R0R2R_0 R_2 below 750"; its optimum is exactly 750, so it fails, and that failure stays in the memo at the end. The plan is HashJoin(R0R_0, HashJoin(R1R_1, R2R_2)) at 950, as with Volcano. For sorted output the result is MergeJoin(IndexScan R0R_0, Sort(HashJoin(R1R_1, R2R_2))) at 1250.

In this model, pruning does not reduce the number of tasks: the example runs 231 tasks, against 178 without pruning, because goals that fail are optimized again with higher limits.

Correctness

The tasks run in last-in, first-out order, so a goal that a task asks for, with all its own tasks, ends before the asking task resumes, and a task only asks for smaller groups, or for the same group with a weaker property. Exploration is complete: every expression of a group gets each rule once, after the input group of the pattern is explored, so the expressions of an explored group are closed under the rules, which in this model gives every ordered split. The search is then correct by induction over the goals, as for Volcano: a move reaches line L15 with its true cost exactly when that cost is below the current limit, a failure is a lower bound, and a winner is the optimum. The proof file has the details, with the termination.

Proof: The task-based Cascades search on the join model explores each needed group completely and returns a cheapest physical plan for the required sort orderfull

Setting. The model is the one of the code. The relations R0,…,Rn−1R_0, \ldots, R_{n-1} share one join attribute, a group is a set of relations, a join expression of a group SS is an ordered split (L,R)(L, R) of SS, and the leaf group {i}\{i\} holds the expression GET(Ri)(R_i). The rules are commutativity and associativity, as on the Volcano page. A goal is a pair (S,p)(S, p) of a group and a property in {any,sorted}\{\text{any}, \text{sorted}\}. For a goal, the moves are the algorithms of the code on each expression of SS and, if pp is sorted, the enforcer Sort with the input goal (S,any)(S, \text{any}). A physical plan for a goal is a move with a plan for each input goal; its cost is the local cost plus the costs of the input plans, and opt(S,p)\mathrm{opt}(S, p) is the least cost of a plan. All local costs are nonnegative. The tasks are kept on a stack, and the main loop of lines L1 to L3 pops and runs the top task until the stack is empty. A task T is a descendant of a task U if U pushed T, or pushed a task of which T is a descendant.

Lemma 1 (stack order). Let a task U run. Every descendant of U runs before every task that was on the stack below U when U was popped.

Proof. The tasks below U stay below every task that U or its descendants push, and the stack is last in, first out. □\square

So the goal O_GROUP(G,q,λ)(G, q, \lambda) that an O_INPUTS task pushes at line L14, with all its descendants, runs before the copy of O_INPUTS that line L14 pushed under it.

Lemma 2 (descendants stay inside). The descendants of E_GROUP(S)(S) change only the groups that are subsets of SS, and they push E_GROUP only for proper subsets of SS. The descendants of O_GROUP(S,p)(S, p) push O_GROUP only for goals (G,q)(G, q) with G⊊SG \subsetneq S, or for (S,any)(S, \text{any}) when pp is sorted, and the descendants of O_GROUP(S,any)(S, \text{any}) never push O_GROUP(S,⋅)(S, \cdot).

Proof. An E_EXPR or APPLY_RULE task of a group TT adds expressions to TT and to B∪R⊊TB \cup R \subsetneq T, and pushes E_GROUP only for the left group L⊊TL \subsetneq T of an expression of TT. A join move of TT asks for goals of its two sides, which are proper subsets of TT; a scan asks for nothing; the Sort move of (T,sorted)(T, \text{sorted}) asks for (T,any)(T, \text{any}). Induction over the descendants gives the claim. □\square

By Lemmas 1 and 2, when a task asks for E_GROUP(L)(L) or O_GROUP(G,q)(G, q), the group LL is not being explored and the goal (G,q)(G, q) is not being optimized by a task below. So the assertions of the code hold, and E_GROUP returns early at line L7 only for an explored group.

Lemma 3 (exploration). When MARK_EXPLORED(S)(S) runs at line L17, the group SS holds every ordered split of SS. Later, no new expression is added to SS. Each rule is applied to each expression at most once.

Proof. By induction on ∣S∣|S|. The rule marks of line L8 are set before the rule is applied, so each rule runs at most once on each expression. Line L7 pushes E_EXPR for every expression that SS has when its exploration starts. During the exploration, by Lemma 2, only APPLY_RULE tasks of SS add expressions to SS, and line L9 pushes E_EXPR for each new one. By Lemma 1 all of these tasks run before MARK_EXPLORED(S)(S). So at that time both rules were applied to every expression of SS. For associativity on (L,R)(L, R), line L8 pushes E_GROUP(L)(L) above the APPLY_RULE task, so LL is explored when the rule runs, and by induction LL holds all its ordered splits. So the expressions of SS are closed under commutativity and under associativity with all splits of the left side. The argument of Lemma 2 on the Volcano page then gives every ordered split: from any expression, associativity and commutativity give ({a},S−{a})(\{a\}, S - \{a\}) and (S−{a},{a})(S - \{a\}, \{a\}), and associativity on the second with all splits of S−{a}S - \{a\}, followed by commutativity, gives the rest. A later addition to SS is an ordered split of SS by soundness of the rules, so it is already there. □\square

Line L5 explores a group before its first optimization, so every group that is optimized holds all its ordered splits, and the moves of a goal are all moves of the model.

Lemma 4 (goals). A winner of a goal always costs opt\mathrm{opt} of the goal, and a failure stored with the bound bb means opt≥b\mathrm{opt} \ge b. After O_GROUP(S,p,λ)(S, p, \lambda) and its descendants have run, the goal has a winner, or it has a failure with a bound at least λ\lambda.

Proof. By induction over the goals, smaller groups first and (S,any)(S, \text{any}) before (S,sorted)(S, \text{sorted}), which by Lemma 2 is the order of the requests. If line L4 returns, the claim holds by the invariant. Otherwise line L6 makes a context with the limit ℓ=λ\ell = \lambda (or ∞\infty without pruning) and pushes FINISH below the move tasks, so FINISH runs after all of them.

Fix a move mm with input goals (G1,q1),…,(Gr,qr)(G_1, q_1), \ldots, (G_r, q_r) and let cm=local(m)+∑iopt(Gi,qi)c_m = \mathrm{local}(m) + \sum_i \mathrm{opt}(G_i, q_i). The O_INPUTS tasks of mm form a chain: each one either ends or pushes its next copy under a child goal. The limit ℓ\ell of the context changes only at line L15 of a move of this context, and by Lemmas 1 and 2 no such move runs while the chain of mm waits for a child goal. So ℓ\ell is constant along the chain. Let tt be the total before input ii, with t<ℓt < \ell. If the goal (Gi,qi)(G_i, q_i) failed with a bound at least ℓ−t\ell - t, then cm≥t+opt(Gi,qi)≥ℓc_m \ge t + \mathrm{opt}(G_i, q_i) \ge \ell, so dropping mm at line L12 loses nothing. If it has a winner, line L13 adds opt(Gi,qi)\mathrm{opt}(G_i, q_i). Otherwise line L14 asks for the goal with the limit ℓ−t\ell - t; by Lemma 1 it ends first, and by induction the goal then has a winner or a failure with a bound at least ℓ−t\ell - t, which the next copy handles at lines L12 and L13. So mm reaches line L15 with the total cmc_m exactly when cm<ℓc_m < \ell, and then it becomes the best move of the context and ℓ\ell becomes cmc_m. Over all moves, the best move at FINISH is one with the least cmc_m if that is below λ\lambda, and there is none otherwise. Since the moves are all moves of the model, the least cmc_m is opt(S,p)\mathrm{opt}(S, p). Line L16 stores a winner of cost opt(S,p)\mathrm{opt}(S, p), or a failure with the bound λ\lambda and opt(S,p)≥λ\mathrm{opt}(S, p) \ge \lambda. A winner is never replaced, because line L4 returns for a goal with a winner. □\square

Termination. Each group is explored once, and each exploration adds finitely many expressions. A goal is optimized again only with a limit above its stored failure bound. By induction over the goal order, only finitely many limits can reach a goal, because each limit is a limit of a parent goal minus a sum of local costs and winner costs. So the main loop ends.

Theorem. CASCADES(p)(p) returns a physical plan of the join of all relations that gives the order pp and costs opt(all relations,p)\mathrm{opt}(\text{all relations}, p), the least cost over all bushy join trees, algorithms, scans and placements of Sort.

Proof. Line L1 asks for the goal of the query with the limit ∞\infty. A plan always exists, so opt<∞\mathrm{opt} < \infty and by Lemma 4 the goal has a winner of cost opt\mathrm{opt}. Each winner is a move whose input goals had winners when it was accepted, and winners never change, so line L3 can read the plan from the winners. Each move gives the order that it promises, so the plan gives pp. ■\blacksquare

Work. By Lemma 3 each of the 3n−2n+1+13^n - 2^{n+1} + 1 join expressions gets each of the two rules once. Associativity on (L,R)(L, R) reads the 2∣L∣−22^{|L|} - 2 expressions of LL, so exploration costs O(∑S3∣S∣)=O(4n)O(\sum_{S} 3^{|S|}) = O(4^n) set operations. Without pruning every limit is ∞\infty, so each goal is optimized once, with O(2∣S∣)O(2^{|S|}) moves and O(1)O(1) tasks for each move and input, and the search costs O(3n)O(3^n) tasks. With pruning a goal can be optimized again with a higher limit, so the number of tasks depends on the costs.

Complexity

In the join model the memo has 2n−12^n - 1 groups and 3n−2n+1+13^n - 2^{n+1} + 1 join expressions, and each expression gets each of the two rules exactly once, which the tests count. Associativity reads the expressions of the left input, so exploration costs O(4n)O(4^n) set operations. Without pruning each goal is optimized once, with O(3n)O(3^n) tasks in all. With pruning a goal can be optimized again with a higher limit, so the work depends on the costs. The memo takes O(3n)O(3^n) space. The stack of tasks replaces the recursion of Volcano, so its depth does not limit the size of the query.

Properties

  • Exact. With rules that reach every equivalent expression, the winner of the query goal is a cheapest plan.
  • Explores on demand. A group is explored when a goal or a rule pattern needs it, not all at the start.
  • Ordered by promise. The order of the moves is free, so good moves can run first and give low limits early.
  • Memoized goals. Winners and failures are stored per group and property; a failure is a lower bound for its limit.
  • Extensible. Operators, rules, enforcers and promises are objects that the builder of the optimizer adds.
  • Explicit tasks. The search can stop after a time budget, because its state is the stack and the memo.

Variants and improvements

  • Lower bounds. Later work computes a lower bound on the cost of a group from its cardinality, so a move can stop before its inputs are optimized.
  • Join enumeration inside the memo. For large join queries a rule set that generates every split by commutativity and associativity makes many duplicates; an optimizer can instead fill a group with the splits from a DPccp or DPhyp style enumerator.
  • Rewrites before the search. Many systems apply heuristic rewrites, such as subquery unnesting, before the cost-based search.
  • Parallel search. Independent goals can be optimized in parallel, since the tasks share only the memo.
  • Search stages and timeouts. A system can run the search in stages with larger rule sets, and stop when a stage gives a good enough plan.

When to use it

Use Cascades when an optimizer must handle many operators, rules and physical properties, and the search should be easy to extend and to control. For join order alone, a bottom-up enumerator such as DPccp is simpler and faster. For a very large query, use a heuristic such as greedy operator ordering to fix the join order first, or limit the rule set.

Pitfalls

  • Optimizing a group before it is explored. If a goal starts before its group holds all expressions, moves of the expressions that come later are never tried for that goal.
  • Stale failures. A failure holds only for its limit. A request with a higher limit must search again.
  • Rule duplicates. Commutativity applied twice gives the old expression back; the memo must detect duplicates and the rules need marks, or exploration does not end.
  • Enforcer cycles. An enforcer must ask for a weaker property, or a goal depends on itself.
  • Pruning is not free. Low limits cause failures and new searches; with a poor order of moves, pruning can cost more tasks than it saves.

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.

cascades_framework.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cascades-framework/. The authors are listed in prov/SJBPXM.jsonl.
"""The task-based search of the Cascades framework on a small join model.

Cascades (Graefe, 1995) keeps equivalent logical expressions in groups of a
memo, like Volcano, but it does not explore all groups first. The search is a
stack of tasks. Optimizing a group for a required property explores the group
on demand, then tries the algorithms of each expression in the order of their
promise, and optimizes the input groups with an upper bound on their cost.
Results are stored as winners (or failures with the bound that caused them).

The model is the one of the Volcano page: relations R_0, ..., R_(n-1) share
one join attribute k, a group is a frozenset of relations, the rules are join
commutativity and associativity, and the physical property is the sort order
on k ("sorted" or "any").

Algorithms and their local costs (|A| is the estimated size of group A):
    TableScan(R)       |R|                gives no order
    IndexScan(R)       2 |R|              needs an index on R.k, gives sorted
    HashJoin(A, B)     |A| + 2 |B|        gives no order
    MergeJoin(A, B)    |A| + |B|          needs both inputs sorted, gives sorted
    NestedLoop(A, B)   |A| |B|            keeps the order of A
    Sort(A)            2 |A|              the enforcer of "sorted"

The size of a group is the product of its |R_i| divided by the product of its
distinct counts d_i without the smallest one.
"""

from fractions import Fraction
from typing import Dict, FrozenSet, List, Optional, Sequence, Tuple

ANY = "any"
SORTED = "sorted"
INF = float("inf")
Group = FrozenSet[int]
RULES = ("commute", "associate")


class Model:
    def __init__(self, card: Sequence, distinct: Sequence, indexed: Sequence[bool]) -> None:
        if not (len(card) == len(distinct) == len(indexed)) or not card:
            raise ValueError("card, distinct and indexed need the same nonzero length")
        if any(d < 1 for d in distinct) or any(c < 0 for c in card):
            raise ValueError("sizes must be nonnegative and distinct counts positive")
        self.n = len(card)
        self.card = [Fraction(c) for c in card]
        self.distinct = [Fraction(d) for d in distinct]
        self.indexed = list(indexed)

    def size(self, S: Group) -> Fraction:
        p = Fraction(1)
        for i in S:
            p *= self.card[i]
        for d in sorted(self.distinct[i] for i in S)[1:]:
            p /= d
        return p


class Context:
    """The goal of one optimization: a group, a required property and an upper bound."""

    def __init__(self, S: Group, prop: str, limit) -> None:
        self.S, self.prop, self.limit, self.limit0 = S, prop, limit, limit
        self.best: Optional[Tuple[Fraction, str, list]] = None


class Cascades:
    def __init__(self, m: Model, prune: bool = True) -> None:
        self.m = m
        self.prune = prune
        self.exprs: Dict[Group, list] = {}
        self.seen: Dict[Group, set] = {}
        self.applied: set = set()
        self.explored: set = set()
        self.exploring: set = set()
        self.active: set = set()
        self.winner: Dict[Tuple[Group, str], Tuple[Fraction, str, list]] = {}
        self.failed: Dict[Tuple[Group, str], object] = {}
        self.stack: list = []
        self.tasks = 0

    # The memo.

    def add(self, S: Group, e) -> bool:
        if S not in self.exprs:
            self.exprs[S], self.seen[S] = [], set()
        if e in self.seen[S]:
            return False
        self.seen[S].add(e)
        self.exprs[S].append(e)
        return True

    def insert_query(self) -> Group:
        """The initial query: R_0 joined with R_1, then R_2, and so on."""
        for i in range(self.m.n):
            self.add(frozenset([i]), ("GET", i))
        S = frozenset([0])
        for i in range(1, self.m.n):
            T = S | {i}
            self.add(T, (S, frozenset([i])))
            S = T
        return S

    # The search.

    def optimize(self, prop: str = ANY) -> Tuple[Fraction, object]:
        if prop not in (ANY, SORTED):
            raise ValueError("the property is 'any' or 'sorted'")
        root = self.insert_query()
        self.stack.append(("O_GROUP", root, prop, INF))  # @line L1
        while self.stack:  # @line L2
            task = self.stack.pop()
            self.tasks += 1
            getattr(self, task[0])(*task[1:])
        return self.winner[(root, prop)][0], self.plan(root, prop)  # @line L3

    def O_GROUP(self, S: Group, prop: str, limit) -> None:
        key = (S, prop)
        if key in self.winner or (key in self.failed and self.failed[key] >= limit):  # @line L4
            return
        if S not in self.explored:  # @line L5
            self.stack.append(("O_GROUP", S, prop, limit))
            self.stack.append(("E_GROUP", S))
            return
        assert key not in self.active, "a goal must not depend on itself"
        self.active.add(key)
        ctx = Context(S, prop, limit if self.prune else INF)  # @line L6
        self.stack.append(("FINISH", ctx))
        for e in reversed(self.exprs[S]):
            self.stack.append(("O_EXPR", ctx, e))
        if prop == SORTED:
            local = 2 * self.m.size(S)
            self.stack.append(("O_INPUTS", ctx, (local, "Sort", [(S, ANY)]), 0, local))

    def E_GROUP(self, S: Group) -> None:
        if S in self.explored or S in self.exploring:  # @line L7
            return
        self.exploring.add(S)
        self.stack.append(("MARK_EXPLORED", S))
        for e in reversed(self.exprs[S]):
            self.stack.append(("E_EXPR", S, e))

    def E_EXPR(self, S: Group, e) -> None:
        if e[0] == "GET":
            return
        L, R = e
        for rule in reversed(RULES):  # @line L8
            if (S, e, rule) in self.applied:
                continue
            self.applied.add((S, e, rule))
            self.stack.append(("APPLY_RULE", S, e, rule))
            if rule == "associate" and len(L) > 1:
                self.stack.append(("E_GROUP", L))

    def APPLY_RULE(self, S: Group, e, rule: str) -> None:
        L, R = e
        new = []
        if rule == "commute":
            new.append((R, L))
        elif len(L) > 1:
            assert L in self.explored, "the pattern needs an explored input group"
            for A, B in list(self.exprs[L]):
                self.add(B | R, (B, R))
                new.append((A, B | R))
        for f in new:  # @line L9
            if self.add(S, f):
                self.stack.append(("E_EXPR", S, f))

    def MARK_EXPLORED(self, S: Group) -> None:
        self.exploring.discard(S)
        self.explored.add(S)  # @line L17

    def moves(self, S: Group, e, prop: str) -> List[Tuple[Fraction, str, list]]:
        m = self.m
        out = []
        if e[0] == "GET":
            i = e[1]
            if m.indexed[i]:
                out.append((2 * m.size(S), "IndexScan", []))
            if prop == ANY:
                out.append((m.size(S), "TableScan", []))
            return out
        L, R = e
        a, b = m.size(L), m.size(R)
        out.append((a + b, "MergeJoin", [(L, SORTED), (R, SORTED)]))
        if prop == ANY:
            out.append((a + 2 * b, "HashJoin", [(L, ANY), (R, ANY)]))
        out.append((a * b, "NestedLoop", [(L, prop), (R, ANY)]))
        return out

    def O_EXPR(self, ctx: Context, e) -> None:
        ms = sorted(self.moves(ctx.S, e, ctx.prop), key=lambda mv: mv[0])
        for mv in reversed(ms):  # @line L10
            self.stack.append(("O_INPUTS", ctx, mv, 0, mv[0]))

    def O_INPUTS(self, ctx: Context, mv, i: int, total) -> None:
        """Cost the inputs of one move from input i on; total is the cost so far."""
        _, label, inputs = mv
        while i < len(inputs):  # @line L11
            G, q = inputs[i]
            rest = ctx.limit - total
            if total >= ctx.limit or self.failed.get((G, q), -1) >= rest:  # @line L12
                return
            if (G, q) in self.winner:  # @line L13
                total += self.winner[(G, q)][0]
                i += 1
                continue
            self.stack.append(("O_INPUTS", ctx, mv, i, total))  # @line L14
            self.stack.append(("O_GROUP", G, q, rest if self.prune else INF))
            return
        if total < ctx.limit and (ctx.best is None or total < ctx.best[0]):  # @line L15
            ctx.best = (total, label, inputs)
            if self.prune:
                ctx.limit = total

    def FINISH(self, ctx: Context) -> None:
        key = (ctx.S, ctx.prop)
        self.active.discard(key)
        if ctx.best is not None:  # @line L16
            self.winner[key] = ctx.best
            self.failed.pop(key, None)
        else:
            self.failed[key] = ctx.limit0

    def plan(self, S: Group, prop: str):
        """The physical plan of the winner of (S, prop), read from the winners of its inputs."""
        _, label, inputs = self.winner[(S, prop)]
        if label in ("TableScan", "IndexScan"):
            (i,) = S
            return (label, i)
        return (label,) + tuple(self.plan(G, q) for G, q in inputs)


def cascades(m: Model, prop: str = ANY, prune: bool = True) -> Tuple[Fraction, object]:
    """The cheapest physical plan for the join of all relations of m that gives prop."""
    return Cascades(m, prune).optimize(prop)


def group_of(p) -> Group:
    if p[0] in ("TableScan", "IndexScan"):
        return frozenset([p[1]])
    out: set = set()
    for c in p[1:]:
        out |= group_of(c)
    return frozenset(out)


def delivered(p) -> str:
    """The sort order that a physical plan gives."""
    if p[0] in ("IndexScan", "Sort", "MergeJoin"):
        return SORTED
    if p[0] == "NestedLoop":
        return delivered(p[1])
    return ANY
dbrel.py 522 lines
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Naive relations, operators by definition, SQL three-valued logic and a page-counting disk.

This is the reference that the tests of the databases pages compare against.
Every operator here follows its definition directly, with nested loops and no
index, hash table or sort of the input. Do not use it as a fast engine.

Relations
    Relation(schema, rows, mode) holds a tuple of distinct attribute names and
    a collections.Counter from tuples to positive counts. mode is "bag" (the
    default, SQL semantics) or "set" (relational theory); in set mode every
    count is 1. rows may be an iterable of tuples (duplicates add up) or a
    mapping from tuples to counts. Two relations are equal when they have the
    same attributes (in any column order) and the same count for each tuple.
    The mode is not compared.

Operators (each returns a new Relation in the mode of its input)
    select(rel, pred)            keeps a row only when pred(row) is True
    where(rel, pred)             the same as select (the SQL WHERE filter)
    project(rel, attrs)          bag: counts add up; set: duplicates removed
    rename(rel, mapping)         mapping is {old: new}
    union(r, s)                  bag: UNION ALL (counts add); set: union
    difference(r, s)             bag: monus max(0, m - n); set: r - s
    intersection(r, s)           bag: min(m, n); set: intersection
    product(r, s)                attributes must be disjoint; counts multiply
    natural_join(r, s)           nested loops on the common attributes
    theta_join(r, s, pred)       select(product(r, s), pred)
    semijoin(r, s), antijoin(r, s)
    distinct(rel)                every count becomes 1
    aggregate(rel, group_attrs, aggs)
                                 aggs is a list of (func, attr, out) with func in
                                 count_star, count, count_distinct, sum, avg, min, max

A predicate receives the row as a dict from attribute name to value. It may
return True, False or None (UNKNOWN). Only True keeps the row.

Nulls
    NULL is None. Joins follow SQL: a common attribute that is None in either
    row never matches. aggregate follows SQL: GROUP BY puts all nulls of a
    column in one group, every aggregate except count_star skips nulls, and
    sum, avg, min and max of no non-null value give None while count gives 0.
    With no grouping attributes, aggregate returns one row even for an empty
    input, as SQL does.

Expressions
    evaluate(expr, db, mode) evaluates a tree of nested tuples:
        ("scan", name)
        ("select", pred, e)          ("project", attrs, e)
        ("rename", mapping, e)       ("distinct", e)
        ("union", e1, e2)            ("difference", e1, e2)
        ("intersection", e1, e2)     ("product", e1, e2)
        ("join", e1, e2)             ("theta_join", pred, e1, e2)
        ("semijoin", e1, e2)         ("antijoin", e1, e2)
        ("aggregate", group_attrs, aggs, e)
    db maps a name to a Relation. Each scanned relation is first put in mode.

Three-valued logic
    tv_and, tv_or and tv_not are the strong Kleene connectives on True, False
    and None. cmp3(op, x, y) compares with op in =, <>, !=, <, <=, >, >= and
    returns None when x or y is None.

Disk
    Disk counts page reads and writes. load(rows, per_page) puts an existing
    input on the disk without counting it. paginate(rows, per_page) splits a
    list of rows into pages.

Random data
    random_relation(rng, schema, n, domain, mode, null_rate) draws n rows.
"""

from collections import Counter
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from fractions import Fraction
from numbers import Number
import random

BAG = "bag"
SET = "set"
MODES = (BAG, SET)


# ---------------------------------------------------------------- ordering

def value_key(v: object) -> tuple:
    """A total order on the values of one column: None first, then numbers, then strings."""
    if v is None:
        return (0, 0)
    if isinstance(v, Number):
        return (1, v)
    if isinstance(v, str):
        return (2, v)
    if isinstance(v, tuple):
        return (3, tuple(value_key(x) for x in v))
    return (4, repr(v))


def row_key(t: Sequence) -> tuple:
    """A total order on tuples that tolerates None. Use it to sort rows in tests."""
    return tuple(value_key(v) for v in t)


# ---------------------------------------------------------------- relations

class Relation:
    """A relation: a schema (tuple of names), a Counter of tuples and a mode."""

    __slots__ = ("schema", "rows", "mode")

    def __init__(self, schema: Sequence[str], rows: Iterable | Mapping = (), mode: str = BAG) -> None:
        if mode not in MODES:
            raise ValueError("mode must be 'bag' or 'set'")
        schema = tuple(schema)
        if len(set(schema)) != len(schema):
            raise ValueError("duplicate attribute in schema %r" % (schema,))
        counts: Counter = Counter()
        items = rows.items() if isinstance(rows, Mapping) else ((t, 1) for t in rows)
        for t, c in items:
            t = tuple(t)
            if len(t) != len(schema):
                raise ValueError("tuple %r does not fit schema %r" % (t, schema))
            if c < 0:
                raise ValueError("negative count for %r" % (t,))
            if c:
                counts[t] += c
        if mode == SET:
            counts = Counter({t: 1 for t in counts})
        self.schema = schema
        self.rows = counts
        self.mode = mode

    def index(self, attr: str) -> int:
        return self.schema.index(attr)

    def reorder(self, schema: Sequence[str]) -> "Relation":
        """The same relation with its columns in the order of schema."""
        schema = tuple(schema)
        if sorted(schema) != sorted(self.schema):
            raise ValueError("schemas %r and %r differ" % (self.schema, schema))
        pos = [self.schema.index(a) for a in schema]
        return Relation(schema, {tuple(t[i] for i in pos): c for t, c in self.rows.items()}, self.mode)

    def with_mode(self, mode: str) -> "Relation":
        return Relation(self.schema, self.rows, mode)

    def as_dict(self, t: Sequence) -> dict:
        return dict(zip(self.schema, t))

    def sorted_rows(self) -> list:
        """Every tuple, repeated by its count, in row_key order."""
        out = []
        for t in sorted(self.rows, key=row_key):
            out.extend([t] * self.rows[t])
        return out

    def __iter__(self):
        return iter(self.sorted_rows())

    def __len__(self) -> int:
        return sum(self.rows.values())

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Relation):
            return NotImplemented
        if sorted(self.schema) != sorted(other.schema):
            return False
        return self.rows == other.reorder(self.schema).rows

    def __repr__(self) -> str:
        body = ", ".join("%r: %d" % (t, self.rows[t]) for t in sorted(self.rows, key=row_key))
        return "Relation(%r, {%s}, %r)" % (self.schema, body, self.mode)


def _mode2(r: Relation, s: Relation) -> str:
    if r.mode != s.mode:
        raise ValueError("operands have modes %r and %r" % (r.mode, s.mode))
    return r.mode


def _same_schema(r: Relation, s: Relation) -> Relation:
    """s with its columns in the order of r; the attribute sets must be equal."""
    if sorted(r.schema) != sorted(s.schema):
        raise ValueError("union-incompatible schemas %r and %r" % (r.schema, s.schema))
    return s.reorder(r.schema)


# ---------------------------------------------------------------- three-valued logic

def tv_and(a: bool | None, b: bool | None) -> bool | None:
    if a is False or b is False:
        return False
    if a is None or b is None:
        return None
    return True


def tv_or(a: bool | None, b: bool | None) -> bool | None:
    if a is True or b is True:
        return True
    if a is None or b is None:
        return None
    return False


def tv_not(a: bool | None) -> bool | None:
    return None if a is None else not a


_CMP = {
    "=": lambda x, y: x == y,
    "<>": lambda x, y: x != y,
    "!=": lambda x, y: x != y,
    "<": lambda x, y: x < y,
    "<=": lambda x, y: x <= y,
    ">": lambda x, y: x > y,
    ">=": lambda x, y: x >= y,
}


def cmp3(op: str, x: object, y: object) -> bool | None:
    """SQL comparison: None (UNKNOWN) if either side is NULL."""
    if op not in _CMP:
        raise ValueError("unknown comparison %r" % (op,))
    if x is None or y is None:
        return None
    return bool(_CMP[op](x, y))


def is_true(v: bool | None) -> bool:
    """The WHERE test: only True passes; False and None (UNKNOWN) do not."""
    return v is True


# ---------------------------------------------------------------- operators

def select(rel: Relation, pred: Callable[[dict], bool | None]) -> Relation:
    out = {t: c for t, c in rel.rows.items() if pred(rel.as_dict(t)) is True}
    return Relation(rel.schema, out, rel.mode)


where = select


def project(rel: Relation, attrs: Sequence[str]) -> Relation:
    attrs = tuple(attrs)
    pos = [rel.index(a) for a in attrs]
    out: Counter = Counter()
    for t, c in rel.rows.items():
        out[tuple(t[i] for i in pos)] += c
    return Relation(attrs, out, rel.mode)


def rename(rel: Relation, mapping: Mapping[str, str]) -> Relation:
    for a in mapping:
        if a not in rel.schema:
            raise ValueError("no attribute %r to rename" % (a,))
    return Relation(tuple(mapping.get(a, a) for a in rel.schema), rel.rows, rel.mode)


def union(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = Counter(r.rows)
    out.update(s.rows)
    return Relation(r.schema, out, mode)


def difference(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = {t: max(0, c - s.rows.get(t, 0)) for t, c in r.rows.items()}
    return Relation(r.schema, out, mode)


def intersection(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    s = _same_schema(r, s)
    out = {t: min(c, s.rows.get(t, 0)) for t, c in r.rows.items()}
    return Relation(r.schema, out, mode)


def product(r: Relation, s: Relation) -> Relation:
    mode = _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    if common:
        raise ValueError("product needs disjoint schemas; common: %r" % (common,))
    out: Counter = Counter()
    for t, c in r.rows.items():
        for u, d in s.rows.items():
            out[t + u] += c * d
    return Relation(r.schema + s.schema, out, mode)


def _matches(r: Relation, s: Relation, t: tuple, u: tuple, common: Sequence[str]) -> bool:
    for a in common:
        x, y = t[r.index(a)], u[s.index(a)]
        if x is None or y is None or x != y:
            return False
    return True


def natural_join(r: Relation, s: Relation) -> Relation:
    """Nested loops over both inputs. With no common attribute it is the product."""
    mode = _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    rest = [a for a in s.schema if a not in common]
    rest_pos = [s.index(a) for a in rest]
    out: Counter = Counter()
    for t, c in r.rows.items():
        for u, d in s.rows.items():
            if _matches(r, s, t, u, common):
                out[t + tuple(u[i] for i in rest_pos)] += c * d
    return Relation(r.schema + tuple(rest), out, mode)


def theta_join(r: Relation, s: Relation, pred: Callable[[dict], bool | None]) -> Relation:
    return select(product(r, s), pred)


def semijoin(r: Relation, s: Relation) -> Relation:
    """Rows of r (with their counts) that join with at least one row of s."""
    _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    out = {t: c for t, c in r.rows.items() if any(_matches(r, s, t, u, common) for u in s.rows)}
    return Relation(r.schema, out, r.mode)


def antijoin(r: Relation, s: Relation) -> Relation:
    """Rows of r (with their counts) that join with no row of s."""
    _mode2(r, s)
    common = [a for a in r.schema if a in s.schema]
    out = {t: c for t, c in r.rows.items() if not any(_matches(r, s, t, u, common) for u in s.rows)}
    return Relation(r.schema, out, r.mode)


def distinct(rel: Relation) -> Relation:
    return Relation(rel.schema, {t: 1 for t in rel.rows}, rel.mode)


AGG_FUNCS = ("count_star", "count", "count_distinct", "sum", "avg", "min", "max")


def _avg(vals: list) -> object:
    total = sum(vals)
    if all(isinstance(v, (int, Fraction)) for v in vals):
        return Fraction(total, 1) / len(vals)
    return total / len(vals)


def agg_value(func: str, vals: list) -> object:
    """One SQL aggregate over a list of column values (with repeats). count_star counts all."""
    if func == "count_star":
        return len(vals)
    nn = [v for v in vals if v is not None]
    if func == "count":
        return len(nn)
    if func == "count_distinct":
        seen: list = []
        for v in nn:
            if v not in seen:
                seen.append(v)
        return len(seen)
    if not nn:
        return None
    if func == "sum":
        return sum(nn)
    if func == "avg":
        return _avg(nn)
    if func == "min":
        return min(nn)
    if func == "max":
        return max(nn)
    raise ValueError("unknown aggregate %r" % (func,))


def aggregate(rel: Relation, group_attrs: Sequence[str], aggs: Sequence[tuple]) -> Relation:
    """gamma_{G; f(A) -> B}(rel) by definition.

    aggs is a list of (func, attr, out); attr is ignored for count_star and may
    be None. For each distinct group key, in row_key order, the whole input is
    scanned. Each result row has count 1 in either mode.
    """
    group_attrs = tuple(group_attrs)
    gpos = [rel.index(a) for a in group_attrs]
    for func, attr, _ in aggs:
        if func not in AGG_FUNCS:
            raise ValueError("unknown aggregate %r" % (func,))
        if func != "count_star":
            rel.index(attr)
    keys: list = []
    for t in rel.rows:
        k = tuple(t[i] for i in gpos)
        if k not in keys:
            keys.append(k)
    if not group_attrs and not keys:
        keys = [()]
    out: Counter = Counter()
    for k in sorted(keys, key=row_key):
        row = list(k)
        for func, attr, _ in aggs:
            vals: list = []
            for t, c in rel.rows.items():
                if tuple(t[i] for i in gpos) == k:
                    vals.extend([None if func == "count_star" else t[rel.index(attr)]] * c)
            row.append(agg_value(func, vals))
        out[tuple(row)] = 1
    schema = group_attrs + tuple(o for _, _, o in aggs)
    return Relation(schema, out, rel.mode)


# ---------------------------------------------------------------- evaluation

def evaluate(expr: tuple, db: Mapping[str, Relation], mode: str = BAG) -> Relation:
    """Evaluate an expression tree of nested tuples over db, in mode."""
    if mode not in MODES:
        raise ValueError("mode must be 'bag' or 'set'")
    op = expr[0]
    ev = lambda e: evaluate(e, db, mode)
    if op == "scan":
        return db[expr[1]].with_mode(mode)
    if op == "select":
        return select(ev(expr[2]), expr[1])
    if op == "project":
        return project(ev(expr[2]), expr[1])
    if op == "rename":
        return rename(ev(expr[2]), expr[1])
    if op == "distinct":
        return distinct(ev(expr[1]))
    if op == "aggregate":
        return aggregate(ev(expr[3]), expr[1], expr[2])
    if op == "theta_join":
        return theta_join(ev(expr[2]), ev(expr[3]), expr[1])
    binary = {
        "union": union, "difference": difference, "intersection": intersection,
        "product": product, "join": natural_join, "semijoin": semijoin, "antijoin": antijoin,
    }
    if op in binary:
        return binary[op](ev(expr[1]), ev(expr[2]))
    raise ValueError("unknown operator %r" % (op,))


# ---------------------------------------------------------------- disk

def paginate(rows: Sequence, per_page: int) -> list:
    """Split rows into pages of per_page rows; the last page may be shorter."""
    if per_page < 1:
        raise ValueError("per_page must be at least 1")
    rows = list(rows)
    return [rows[i:i + per_page] for i in range(0, len(rows), per_page)]


class Disk:
    """Pages on a simulated disk. Each read_page and write_page call costs one I/O."""

    def __init__(self) -> None:
        self.pages: dict = {}
        self.reads = 0
        self.writes = 0
        self._next = 0

    def alloc(self) -> int:
        pid = self._next
        self._next += 1
        self.pages[pid] = ()
        return pid

    def write_page(self, pid: int, rows: Iterable) -> None:
        if pid not in self.pages:
            raise KeyError("page %r was not allocated" % (pid,))
        self.pages[pid] = tuple(rows)
        self.writes += 1

    def read_page(self, pid: int) -> list:
        self.reads += 1
        return list(self.pages[pid])

    def free(self, pid: int) -> None:
        del self.pages[pid]

    def load(self, rows: Sequence, per_page: int) -> list:
        """Store an input file without counting I/O; return its page ids in order."""
        ids = []
        for page in paginate(rows, per_page):
            pid = self.alloc()
            self.pages[pid] = tuple(page)
            ids.append(pid)
        return ids

    def io(self) -> int:
        return self.reads + self.writes

    def reset_counters(self) -> None:
        self.reads = 0
        self.writes = 0


# ---------------------------------------------------------------- random data

def random_relation(rng: random.Random, schema: Sequence[str], n: int,
                    domain: int | Sequence | Mapping = 4, mode: str = BAG,
                    null_rate: float = 0.0) -> Relation:
    """n rows drawn with rng. domain is a size k (values 0 to k - 1), a list of
    values, or a dict from attribute to either. Each value is None with
    probability null_rate. In set mode duplicates collapse, so there may be
    fewer than n rows."""
    schema = tuple(schema)

    def values(a: str) -> list:
        d = domain[a] if isinstance(domain, Mapping) else domain
        return list(range(d)) if isinstance(d, int) else list(d)

    doms = [values(a) for a in schema]
    rows = []
    for _ in range(n):
        t = []
        for d in doms:
            if null_rate and rng.random() < null_rate:
                t.append(None)
            else:
                t.append(rng.choice(d))
        rows.append(tuple(t))
    return Relation(schema, rows, mode)
test_cascades_framework.py 242 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cascades-framework/. The authors are listed in prov/SJBPXM.jsonl.

import itertools
import random
import unittest

import dbrel
from cascades_framework import ANY, INF, SORTED, Cascades, Model, cascades, delivered, group_of


def cost(m, p):
    """The cost model of the module docstring, written again for the tests."""
    op, S = p[0], group_of(p)
    if op == "TableScan":
        return m.size(S)
    if op == "IndexScan":
        assert m.indexed[p[1]]
        return 2 * m.size(S)
    if op == "Sort":
        return 2 * m.size(S) + cost(m, p[1])
    if op == "MergeJoin":
        assert delivered(p[1]) == SORTED and delivered(p[2]) == SORTED
    a, b = m.size(group_of(p[1])), m.size(group_of(p[2]))
    local = {"HashJoin": a + 2 * b, "MergeJoin": a + b, "NestedLoop": a * b}[op]
    return local + cost(m, p[1]) + cost(m, p[2])


def all_plans(m, S, memo):
    """Every physical plan for S, with at most one Sort directly above each operator."""
    if S in memo:
        return memo[S]
    base = []
    if len(S) == 1:
        (i,) = S
        base.append(("TableScan", i))
        if m.indexed[i]:
            base.append(("IndexScan", i))
    else:
        items = sorted(S)
        for k in range(1, (1 << len(items)) - 1):
            A = frozenset(x for j, x in enumerate(items) if k >> j & 1)
            for pa in all_plans(m, A, memo):
                for pb in all_plans(m, S - A, memo):
                    base.append(("HashJoin", pa, pb))
                    base.append(("NestedLoop", pa, pb))
                    if delivered(pa) == SORTED and delivered(pb) == SORTED:
                        base.append(("MergeJoin", pa, pb))
    memo[S] = base + [("Sort", p) for p in base]
    return memo[S]


def dp_oracle(m):
    """Bottom-up dynamic program over subsets and the two properties."""
    best = {}
    for r in range(1, m.n + 1):
        for S in map(frozenset, itertools.combinations(range(m.n), r)):
            a = s = INF
            if r == 1:
                (i,) = S
                a = m.card[i]
                if m.indexed[i]:
                    s = 2 * m.card[i]
                    a = min(a, s)
            else:
                items = sorted(S)
                for k in range(1, (1 << r) - 1):
                    A = frozenset(x for j, x in enumerate(items) if k >> j & 1)
                    sa, sb = m.size(A), m.size(S - A)
                    (aa, as_), (ba, bs) = best[A], best[S - A]
                    a = min(a, sa + 2 * sb + aa + ba, sa + sb + as_ + bs, sa * sb + aa + ba)
                    s = min(s, sa + sb + as_ + bs, sa * sb + as_ + ba)
            s = min(s, 2 * m.size(S) + a)
            best[S] = (a, s)
    return best


def random_model(rng, n):
    return Model([rng.choice([1, 10, 50, 100, 1000]) for _ in range(n)],
                 [rng.choice([1, 2, 10, 50, 100]) for _ in range(n)],
                 [rng.random() < 0.4 for _ in range(n)])


def key(row):
    return dbrel.value_key(row["k"])


def execute(p, db, rng):
    """Run a physical plan on lists of rows; the operators without an order shuffle their output."""
    op = p[0]
    if op in ("TableScan", "IndexScan"):
        rows = [dict(zip(db[p[1]].schema, t)) for t in db[p[1]].sorted_rows()]
        rng.shuffle(rows)
        return sorted(rows, key=key) if op == "IndexScan" else rows
    if op == "Sort":
        return sorted(execute(p[1], db, rng), key=key)
    left, right = execute(p[1], db, rng), execute(p[2], db, rng)
    out = []
    if op == "HashJoin":
        table = {}
        for r in right:
            if r["k"] is not None:
                table.setdefault(r["k"], []).append(r)
        out = [{**l, **r} for l in left for r in table.get(l["k"], [])]
        rng.shuffle(out)
    elif op == "NestedLoop":
        out = [{**l, **r} for l in left for r in right if l["k"] is not None and l["k"] == r["k"]]
    else:
        assert [key(r) for r in left] == sorted(map(key, left))
        assert [key(r) for r in right] == sorted(map(key, right))
        i = j = 0
        while i < len(left) and j < len(right):
            if left[i]["k"] is None:
                i += 1
            elif right[j]["k"] is None:
                j += 1
            elif left[i]["k"] < right[j]["k"]:
                i += 1
            elif left[i]["k"] > right[j]["k"]:
                j += 1
            else:
                k, j0 = left[i]["k"], j
                while i < len(left) and left[i]["k"] == k:
                    j = j0
                    while j < len(right) and right[j]["k"] == k:
                        out.append({**left[i], **right[j]})
                        j += 1
                    i += 1
    return out


class CountingCascades(Cascades):
    def __init__(self, m, prune=True):
        super().__init__(m, prune)
        self.rule_tasks = 0
        self.goals = []

    def APPLY_RULE(self, S, e, rule):
        self.rule_tasks += 1
        super().APPLY_RULE(S, e, rule)

    def FINISH(self, ctx):
        self.goals.append((ctx.S, ctx.prop))
        super().FINISH(ctx)


class TestCascades(unittest.TestCase):
    def test_oracle_matches_exhaustive_search(self):
        rng = random.Random(1)
        for n in (1, 2, 2, 3):
            m = random_model(rng, n)
            plans = all_plans(m, frozenset(range(n)), {})
            want = dp_oracle(m)[frozenset(range(n))]
            self.assertEqual(min(cost(m, p) for p in plans), want[0])
            self.assertEqual(min(cost(m, p) for p in plans if delivered(p) == SORTED), want[1])

    def test_optimal_for_both_properties(self):
        rng = random.Random(2)
        for trial in range(40):
            m = random_model(rng, rng.randint(1, 4) if trial % 5 else 5)
            want = dp_oracle(m)
            for j, prop in enumerate((ANY, SORTED)):
                for prune in (True, False):
                    c = Cascades(m, prune)
                    got, p = c.optimize(prop)
                    self.assertEqual(got, want[frozenset(range(m.n))][j])
                    self.assertEqual(cost(m, p), got)
                    if prop == SORTED:
                        self.assertEqual(delivered(p), SORTED)
                    for (S, q), w in c.winner.items():
                        self.assertEqual(w[0], want[S][0 if q == ANY else 1])
                        self.assertEqual(cost(m, c.plan(S, q)), w[0])
                    for (S, q), bound in c.failed.items():
                        self.assertTrue(prune)
                        self.assertLessEqual(bound, want[S][0 if q == ANY else 1])
                    self.assertEqual(c.active, set())
                    self.assertEqual(c.exploring, set())

    def test_exploration_is_complete_and_each_rule_runs_once(self):
        for n in range(1, 7):
            c = CountingCascades(random_model(random.Random(n), n))
            c.optimize(ANY)
            self.assertEqual(len(c.explored), 2 ** n - 1)
            for S in c.explored:
                if len(S) > 1:
                    splits = {(A, S - A) for r in range(1, len(S))
                              for A in map(frozenset, itertools.combinations(sorted(S), r))}
                    self.assertEqual(set(c.exprs[S]), splits)
                    self.assertEqual(len(c.exprs[S]), len(splits))
            self.assertEqual(c.rule_tasks, 2 * (3 ** n - 2 ** (n + 1) + 1))

    def test_without_pruning_each_goal_is_optimized_once(self):
        rng = random.Random(4)
        for n in range(1, 6):
            c = CountingCascades(random_model(rng, n), prune=False)
            c.optimize(SORTED)
            self.assertEqual(len(c.goals), len(set(c.goals)))
            self.assertEqual(set(c.goals), set(c.winner))

    def test_plans_run_and_give_the_join(self):
        rng = random.Random(3)
        for _ in range(40):
            n = rng.randint(1, 4)
            m = random_model(rng, n)
            db = {i: dbrel.random_relation(rng, ["k", "v%d" % i], rng.randint(0, 4),
                                           domain={"k": [0, 1, 2], "v%d" % i: [0, 1]}, null_rate=0.15)
                  for i in range(n)}
            want = db[0]
            for i in range(1, n):
                want = dbrel.natural_join(want, db[i])
            for prop in (ANY, SORTED):
                _, p = cascades(m, prop)
                rows = execute(p, db, rng)
                self.assertEqual(dbrel.Relation(want.schema, [tuple(r[a] for a in want.schema) for r in rows]), want)
                if prop == SORTED:
                    self.assertEqual([key(r) for r in rows], sorted(key(r) for r in rows))

    def test_worked_example(self):
        m = Model([200, 100, 50], [100, 50, 10], [True, False, False])
        c = Cascades(m)
        self.assertEqual(c.optimize(ANY), (950, ("HashJoin", ("TableScan", 0),
                                                 ("HashJoin", ("TableScan", 1), ("TableScan", 2)))))
        self.assertEqual(c.failed, {(frozenset([0, 2]), SORTED): 750})
        self.assertEqual(c.winner[(frozenset([0, 2]), ANY)][0], 550)
        self.assertEqual(cascades(m, SORTED), (1250, ("MergeJoin", ("IndexScan", 0),
                                                      ("Sort", ("HashJoin", ("TableScan", 1), ("TableScan", 2))))))

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            Model([], [], [])
        with self.assertRaises(ValueError):
            Model([1, 2], [1], [False, False])
        with self.assertRaises(ValueError):
            Model([1], [0], [False])
        with self.assertRaises(ValueError):
            cascades(Model([1], [1], [False]), "hashed")
        self.assertEqual(cascades(Model([7], [1], [False]), SORTED), (21, ("Sort", ("TableScan", 0))))
        self.assertEqual(cascades(Model([0, 5], [1, 1], [False, False]))[0], 5)


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

History

Goetz Graefe built the EXODUS optimizer generator with David DeWitt in 1987 and the Volcano optimizer generator with William McKenna in 1993. In 1995 he described the Cascades framework, which kept the memo and the goal-driven search of Volcano but replaced its fixed two-phase search with tasks, explored on demand, and made rules and promises into objects. The Columbia optimizer at Portland State University later reimplemented the framework for research.

References

  1. The Cascades framework for query optimization, the memo of groups, the rules with patterns and promises, the search by tasks, and the comparison with the Volcano search
  2. The Volcano optimizer generator: extensibility and efficient search, the earlier search with a look-up table, physical properties, enforcers and a cost limit, which Cascades refines

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.exploration
  • a full proof of time.search without pruning
  • a full proof of space.memo
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