Algorithmadvanced
Volcano optimizer generator
Also called Volcano optimizer, Volcano search strategy.
Generate an optimizer from algebraic rules and physical properties that searches plans top down by dynamic programming with memoization.
- 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
- Model
- Word RAM
- Properties
- deterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Goetz Graefe, William J. McKenna, 1993
The Volcano optimizer generator takes a description of a data model and produces a query optimizer for it. The description gives the logical operators, the algorithms that implement them, the transformation rules between logical expressions, the physical properties such as sort order, the enforcers that create a property, such as a Sort, and the cost functions. The generated optimizer keeps equivalent expressions in groups of a memo and searches top down. For a group and a required physical property it tries every algorithm that gives the property and every enforcer, asks for the best plans of the inputs with the properties they need, stores the best plan in a table, and prunes moves that cost more than a limit. Goetz Graefe and William McKenna presented it in 1993. Its search is a form of dynamic programming with memoization, driven by the goal instead of built bottom up.
In plain words
An optimizer must find, among many equivalent ways to run a query, a cheap one. Volcano does not write this search by hand for each system. The builder of a database describes the operators, the rules that turn one form of a query into another, and the costs. Volcano makes the search code from this description.
The search first applies the rules until no new form appears, and it puts forms that give the same result in one group. Then it asks one question: what is the cheapest way to compute this group so that the result has the needed sort order? It answers by trying each method, asking the same question for the inputs, and adding up the costs. It writes each answer down, so it never computes the same answer twice. It also stops a try as soon as it costs more than the best answer so far.
The problem
The input is a logical query and a required physical property, for example "no order needed" or "sorted on the join key". A logical expression is an operator with groups as inputs; a group is a set of logical expressions that give the same result. A physical plan is a tree of algorithms. Each algorithm implements one logical expression of a group, needs some properties of its inputs, gives some property of its output, and has a local cost. An enforcer, such as Sort, changes only the property. The task is to find a physical plan of least total cost for the query that gives the required property.
The code of this page uses a small model of joins. Relations share one join attribute , a group is a set of relations, and the rules are join commutativity and associativity. The property is the sort order on . The algorithms are TableScan, IndexScan (sorted, if has an index on ), 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
VOLCANO(query, required property p)- 1
put the query in the memo, and EXPLORE each group until no rule adds an expression - 2
return FIND-BEST-PLAN(the group of the query, p, ∞)
EXPLORE(group S)- 1
repeat until a pass adds no expression to S - 2
for each expression (L, R) of S do - 3
add (R, L) to S, by commutativity - 4
EXPLORE(L); for each expression (A, B) of L, add (B, R) to the group B ∪ R and (A, B ∪ R) to S, by associativity - 5
mark S as explored
FIND-BEST-PLAN(group S, property p, limit)- 1
if (S, p) is in the table, return its plan if it costs less than limit, or failure if it failed with a limit of at least limit - 2
best ← none - 3
for each move for (S, p): an algorithm that gives p on an expression of S, or the enforcer of p on (S, any) do - 4
total ← the local cost of the move - 5
for each input (G, q) of the move, while total < limit do - 6
r ← FIND-BEST-PLAN(G, q, limit - total) - 7
if r is failure, reject the move; else total ← total + the cost of r - 8
if every input has a plan and total < limit, then best ← this move with its input plans, and limit ← total - 9
store best for (S, p) in the table, or store a failure with the first limit if best is none - 10
return best
Line L8 is the memoization. Lines L12 and L15 are the branch and bound: a move stops as soon as its partial cost reaches the limit, and each input gets only the part of the limit that is left. The enforcer move asks for the same group with a weaker property, so a plan that needs sorted output can use an unsorted plan and a Sort on top. In the code a failure also stores its limit, so a later call with a lower or equal limit fails at once, and a call with a higher limit searches again.
The 1993 paper lists the transformations among the moves of FindBestPlan. Graefe described the Volcano search in 1995 as two phases, all transformations first and then the search for plans, and this page uses that form, with lines L1 to L7 as the first phase.
Example
Take , and , with 100, 50 and 10 distinct values of , and an index on only. The size estimates are and . Exploration makes all 7 groups and the 12 ordered splits. The best plans per group and property are these.
| group | any order | cost | sorted | cost |
|---|---|---|---|---|
| TableScan | 200 | IndexScan | 400 | |
| TableScan | 100 | Sort(TableScan) | 300 | |
| TableScan | 50 | Sort(TableScan) | 150 | |
| HashJoin | 350 | Sort(HashJoin) | 550 | |
| HashJoin(, ) | 950 | MergeJoin(IndexScan , Sort(HashJoin(, ))) | 1250 |
For no order, the best plan costs 950. For sorted output, the obvious plan is a Sort on top of that plan, at . Volcano finds a cheaper plan at 1250: it reads in order through the index, sorts the small join , and merges. The pruning shows in the same search. After the merge join at 1250 is found, the Sort move asks for the unsorted plan of the whole query with the limit . The best unsorted plan costs 950, so the call fails and the table stores that failure with the limit 850. With pruning, this search makes 79 calls of FIND-BEST-PLAN; without it, 128.
Correctness
The rules are sound because the join is commutative and associative on bags. They are complete in this model: in each group, a short chain of the two rules reaches every ordered split, so the memo holds all bushy join trees. The search is correct by induction over the groups, smaller groups first, and for one group with the property "any" before "sorted". If the best plan for costs less than the limit, every input of that plan costs less than the part of the limit that it gets, so the induction returns it exactly; otherwise the call fails, and the stored failure limit is a lower bound on the optimum. The proof file has the details.
Proof: The Volcano search on the join model explores every join tree and returns a cheapest physical plan for the required sort orderfull
Setting. The relations share one join attribute , so a join of any two disjoint sets of relations is an equijoin on , and every bushy join tree over all relations is a valid logical plan. A group is a set of relations, and a join expression of a group is an ordered pair of disjoint nonempty groups with , an ordered split. The transformation rules are commutativity, , and associativity, which for an expression of and an expression of adds to the group and to . The required property is . The moves for are the ones listed in the code: the scans for a single relation, the three join algorithms for each expression of with their required input properties, and the Sort enforcer over when is sorted. Every local cost is a nonnegative number that depends only on the groups. A physical plan for is a move for together with a physical plan for each of its inputs , and its cost is the local cost plus the costs of the input plans. is the least cost of such a plan.
Lemma 1 (the rules are sound). Every expression that the rules add to a group is an ordered split of , and it computes the same bag of rows as every other expression of .
Proof. Commutativity keeps the two sides. Associativity on with makes , a split of , and , a split of . The natural join on is commutative and associative on bags, also with nulls, since a row of the result is a choice of one row from each relation with equal non-null values of , whatever the order of the joins.
Lemma 2 (the rules are complete). When EXPLORE returns, holds every ordered split of , and every nonempty proper subset of is a group of the memo.
Proof. By induction on ; for there is nothing to show. A group always holds at least one expression, because it is created with one. Lines L3 to L7 repeat until a pass adds nothing, so at the end the set of expressions of is closed under the two rules, where associativity on uses the expressions of , which hold all ordered splits of by the induction hypothesis, because line L6 explores first. By Lemma 1 later additions to an explored group are splits that it holds already, so explored groups stay complete.
Let . If , commutativity gives both splits. Otherwise one side has two or more relations, and by commutativity we may take . Pick . Associativity with the split of gives , and commutativity gives . Associativity on this expression with every split of gives for every nonempty proper subset of , and is there too. So holds for every nonempty with , and by commutativity for every with . These are all ordered splits. Each side of an expression is a group, so every nonempty proper subset of is a group.
EXPLORE-ALL explores the query group and then every group that is not explored yet, so by Lemma 2 the memo holds every nonempty subset of the relations, each with all its ordered splits. So the logical space is the set of all bushy join trees.
Lemma 3 (the search). Let FIND-BEST-PLAN be called. If , it returns a plan for of cost , and otherwise it returns failure. Afterwards the table holds either ("plan", ) or ("fail", ) with .
Proof. The calls form a recursion on the pairs : a join move calls strictly smaller groups, and the Sort move for calls , whose moves do not call again. So we can use induction in the order where smaller groups come first and comes before , and inside one pair on the order of the calls.
Lookup, line L8. If the table holds ("plan", ) for , then by the induction hypothesis for the earlier call, and returning the plan when and failure otherwise is correct. If it holds ("fail", ), then , so failure is correct when ; otherwise the search runs again.
Search, lines L9 to L15. For a move with inputs , let , so . Let be the value of the limit when the loop reaches . We claim that is accepted at line L15 exactly when , and then with the total . Suppose . Before input , the total is , so the loop does not stop, and , so by induction the call of line L13 returns a plan of cost . Hence the total ends at and the move is accepted. Conversely, every input plan that a call returns has the optimal cost of its input, so an accepted total equals , and it is accepted only if it is below . After an acceptance the limit becomes . So after the loop, if some is below the first limit , the loop has accepted a move with the smallest , and costs . If every , no move is accepted and the result is failure, with , which line L16 stores. Without pruning, the limit passed to the inputs is and the same argument holds with the cost of the best move so far.
Theorem. VOLCANO returns a physical plan for the join of all relations that gives the order , of cost . This is the least cost over all bushy join trees, all choices of join algorithms and scans, and all placements of Sort, except a Sort at the top of a plan that needs no order, which is never cheaper than the plan below it.
Proof. Line L2 calls FIND-BEST-PLAN with the limit , so by Lemma 3 it returns a plan of cost ; such a plan exists, since a table scan of each relation, hash joins and a Sort make one. By Lemma 2 the expressions of each group are all its ordered splits, so the moves range over all join trees. Each move gives the property that it promises: a merge join of sorted inputs is sorted on , a nested loop join keeps the order of its outer input, and a Sort sorts. A plan with a Sort on top of a plan that gives no required order costs at least as much as the plan below, because the Sort has a nonnegative cost.
Work. By Lemmas 1 and 2 the memo holds join expressions. The proof of Lemma 2 uses a chain of at most five rule steps from the first expression, and each pass of lines L3 to L7 does at least one more step of the chain, so a group reaches all its splits within five passes, and a sixth pass finds nothing new. One pass over a group with relations costs set operations, one for each expression and each expression of its left side, so the exploration costs set operations. Without pruning, each pair is searched once, with moves, which is in all. With pruning, a pair that failed can be searched again with a larger limit, so the number of searches depends on the costs.
Complexity
In the join model with relations, the memo has groups and join expressions. Exploration of a group with relations takes a constant number of passes, each over its expressions and the expressions of their left inputs, so the exploration costs set operations. Without pruning, each pair of a group and a property is searched once, with moves, so the search costs moves. With pruning, a pair that failed can be searched again with a higher limit, so the number of searches depends on the costs; in return many moves stop early. The memo and the table take space. In general models the size of the memo depends on the rules, and it can be exponential in the size of the query.
Properties
- Exact. If the rules reach every equivalent expression, the result is a cheapest plan for the required property.
- Top down and goal driven. Only pairs of a group and a property that some move needs are optimized, unlike a bottom-up dynamic program that computes all of them.
- Physical properties and enforcers. Sort order, and in a parallel system the partitioning of data, are properties that an algorithm can give or that an enforcer can create.
- Extensible. New operators, algorithms and rules change the description, not the search.
- Memoized. Each result and each failure is stored for the pair of a group and a property.
Variants and improvements
- Cascades. Graefe's successor explores groups on demand with a stack of tasks, orders rules by promise, and merges transformation and implementation into one search.
- Better bounds. Later work uses lower bounds on the cost of a group, so a move can stop before its inputs are optimized.
- Bottom-up search. A Selinger-style dynamic program or DPccp builds the same table of best plans bottom up for join order, keeping interesting orders instead of required properties.
- Heuristic limits. A generated optimizer can stop exploration early, or skip rules, to bound the time for large queries.
When to use it
Use the Volcano search when an optimizer must support many operators and rules, and the rules should be separate from the search code. For join ordering alone, a bottom-up enumerator such as DPccp is simpler and faster, because it does not generate the expressions by rules. Many newer optimizers follow the Cascades framework instead, because it does not need to explore everything before the search.
Pitfalls
- Cost of full exploration. Applying every rule to every group before the search can generate a very large memo, also for expressions that no good plan uses.
- Rule duplicates. Commutativity applied twice gives the old expression back; the memo must detect duplicate expressions, or the rules never stop.
- Stored failures. A failure is only a lower bound for the limit that caused it. Returning it for a call with a higher limit loses plans.
- Enforcer loops. An enforcer must ask for a weaker property; if Sort asks for sorted input, the search calls itself without end.
- The name. The Volcano iterator model of query execution comes from the same research project; it is a different topic, the iterator model.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# 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)
volcano_optimizer_generator.py 247 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/volcano-optimizer-generator/. The authors are listed in prov/KJT4MR.jsonl.
"""The search of the Volcano optimizer generator on a small join model.
Volcano (Graefe and McKenna, 1993) generates an optimizer from rules. The
search has two phases. First it applies the transformation rules until no new
logical expression appears, and keeps the expressions in equivalence classes
(groups) of a memo. Then FIND-BEST-PLAN works top down: for a group and a
required physical property, it tries every algorithm that can give the
property and every enforcer of the property, asks for the best plans of the
inputs with their required properties, keeps the cheapest plan in a table,
and prunes with a cost limit (branch and bound).
The model of this file: relations R_0, ..., R_(n-1) that all share one join
attribute k, so every split of a set of relations is a valid join. A group is
a frozenset of relations. The logical operators are GET(R_i) and JOIN. The
transformation rules are join commutativity and associativity. The physical
property is the sort order on k: "sorted" or "any".
Algorithms and their local costs (sizes are estimates, |A| for a 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| builds on 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 S is the product of |R_i| over S divided by the product
of the numbers of distinct keys d_i over S without the smallest d_i, which is
the usual estimate for an equijoin on one attribute.
"""
from fractions import Fraction
from typing import Dict, FrozenSet, Iterator, List, Optional, Sequence, Tuple
ANY = "any"
SORTED = "sorted"
INF = float("inf")
Group = FrozenSet[int]
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]
ds = sorted(self.distinct[i] for i in S)
for d in ds[1:]:
p /= d
return p
def local_cost(m: Model, op: str, S: Group, inputs: Sequence[Group]) -> Fraction:
if op == "TableScan":
return m.size(S)
if op == "IndexScan":
return 2 * m.size(S)
if op == "Sort":
return 2 * m.size(S)
a, b = (m.size(g) for g in inputs)
if op == "HashJoin":
return a + 2 * b
if op == "MergeJoin":
return a + b
if op == "NestedLoop":
return a * b
raise ValueError("unknown operator %r" % (op,))
def moves(m: Model, exprs: Sequence, S: Group, prop: str) -> Iterator[Tuple[Fraction, object, list]]:
"""The algorithms and enforcers that give prop for group S, in order of promise.
Each move is (local cost, label, [(input group, required property)]).
"""
if len(S) == 1:
(i,) = S
if m.indexed[i]:
yield local_cost(m, "IndexScan", S, []), ("IndexScan", i), []
if prop == ANY:
yield local_cost(m, "TableScan", S, []), ("TableScan", i), []
else:
for A, B in exprs:
yield local_cost(m, "MergeJoin", S, [A, B]), "MergeJoin", [(A, SORTED), (B, SORTED)]
if prop == ANY:
yield local_cost(m, "HashJoin", S, [A, B]), "HashJoin", [(A, ANY), (B, ANY)]
yield local_cost(m, "NestedLoop", S, [A, B]), "NestedLoop", [(A, prop), (B, ANY)]
if prop == SORTED:
yield local_cost(m, "Sort", S, [S]), "Sort", [(S, ANY)]
class Memo:
"""Groups of logical expressions. A join expression is a pair (left group, right group)."""
def __init__(self, n: int) -> None:
self.n = n
self.exprs: Dict[Group, List[Tuple[Group, Group]]] = {}
self.seen: Dict[Group, set] = {}
self.explored: set = set()
def group(self, S: Group) -> Group:
if S not in self.exprs:
self.exprs[S], self.seen[S] = [], set()
return S
def add(self, S: Group, e: Tuple[Group, Group]) -> bool:
self.group(S)
if e in self.seen[S]:
return False
self.seen[S].add(e)
self.exprs[S].append(e)
return True
def insert_left_deep(self) -> Group:
"""The initial query: R_0 joined with R_1, then R_2, and so on."""
S = self.group(frozenset([0]))
for i in range(1, self.n):
R = self.group(frozenset([i]))
T = S | R
self.add(T, (S, R))
S = T
return S
def explore(self, S: Group) -> None:
"""Apply commutativity and associativity to the group S until nothing new appears."""
if S in self.explored or len(S) == 1:
self.explored.add(S)
return
changed = True
while changed: # @line L3
changed = False
for L, R in list(self.exprs[S]): # @line L4
changed |= self.add(S, (R, L)) # @line L5
if len(L) > 1:
self.explore(L) # @line L6
for A, B in list(self.exprs[L]):
BR = B | R
self.add(BR, (B, R))
changed |= self.add(S, (A, BR))
self.explored.add(S) # @line L7
def explore_all(self, root: Group) -> None:
self.explore(root)
while True:
todo = [S for S in self.exprs if S not in self.explored]
if not todo:
return
for S in todo:
self.explore(S)
class Volcano:
def __init__(self, m: Model, prune: bool = True) -> None:
self.m = m
self.prune = prune
self.memo = Memo(m.n)
self.table: Dict[Tuple[Group, str], tuple] = {}
self.calls = 0
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.memo.insert_left_deep()
self.memo.explore_all(root) # @line L1
found = self.find_best_plan(root, prop, INF) # @line L2
assert found is not None
return found
def find_best_plan(self, S: Group, prop: str, limit) -> Optional[Tuple[Fraction, object]]:
"""The cheapest plan for S with property prop that costs less than limit, or None."""
self.calls += 1
key = (S, prop)
if key in self.table: # @line L8
kind, a, plan = self.table[key]
if kind == "plan":
return (a, plan) if a < limit else None
if limit <= a:
return None
limit0 = limit
best = None # @line L9
for local, label, inputs in moves(self.m, self.memo.exprs[S], S, prop): # @line L10
total = local # @line L11
plans = []
for g, p in inputs: # @line L12
if total >= limit:
break
r = self.find_best_plan(g, p, limit - total if self.prune else INF) # @line L13
if r is None: # @line L14
total = INF
break
total += r[0]
plans.append(r[1])
if len(plans) == len(inputs) and total < limit and (best is None or total < best[0]): # @line L15
best = (total, label if not inputs else (label,) + tuple(plans))
if self.prune:
limit = total
if best is None: # @line L16
self.table[key] = ("fail", limit0, None)
else:
self.table[key] = ("plan", best[0], best[1])
return best # @line L17
def volcano(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 Volcano(m, prune).optimize(prop)
def group_of(p) -> Group:
if isinstance(p[0], str) and 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."""
op = p[0]
if op in ("IndexScan", "Sort", "MergeJoin"):
return SORTED
if op == "NestedLoop":
return delivered(p[1])
return ANY
def plan_cost(m: Model, p) -> Fraction:
"""The cost of a physical plan; raises ValueError if an input lacks a required order."""
op = p[0]
if op in ("TableScan", "IndexScan"):
if op == "IndexScan" and not m.indexed[p[1]]:
raise ValueError("no index on R_%d" % p[1])
return local_cost(m, op, group_of(p), [])
kids = p[1:]
if op == "MergeJoin" and any(delivered(c) != SORTED for c in kids):
raise ValueError("a merge join needs sorted inputs")
return local_cost(m, op, group_of(p), [group_of(c) for c in kids]) + sum(plan_cost(m, c) for c in kids)
test_volcano_optimizer_generator.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/volcano-optimizer-generator/. The authors are listed in prov/KJT4MR.jsonl.
import itertools
import random
import unittest
from fractions import Fraction
import dbrel
from volcano_optimizer_generator import (ANY, INF, SORTED, Memo, Model, Volcano, delivered, group_of,
plan_cost, volcano)
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])
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)
B = S - A
sa, sb = m.size(A), m.size(B)
(aa, as_), (ba, bs) = best[A], best[B]
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 == "TableScan":
rows = [dict(zip(db[p[1]].schema, t)) for t in db[p[1]].sorted_rows()]
rng.shuffle(rows)
return rows
if op == "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 == "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)
for l in left:
for r in table.get(l["k"], []):
out.append({**l, **r})
rng.shuffle(out)
elif op == "NestedLoop":
for l in left:
for r in right:
if l["k"] is not None and l["k"] == r["k"]:
out.append({**l, **r})
elif op == "MergeJoin":
assert [key(r) for r in left] == sorted(key(r) for r in left)
assert [key(r) for r in right] == sorted(key(r) for r in 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 TestVolcano(unittest.TestCase):
def test_oracle_matches_exhaustive_search(self):
rng = random.Random(1)
for n in (1, 2, 2, 2, 3):
m = random_model(rng, n)
plans = all_plans(m, frozenset(range(m.n)), {})
want = dp_oracle(m)[frozenset(range(m.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(50):
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):
v = Volcano(m, prune)
c, p = v.optimize(prop)
self.assertEqual(c, want[frozenset(range(m.n))][j])
self.assertEqual(cost(m, p), c)
self.assertEqual(plan_cost(m, p), c)
if prop == SORTED:
self.assertEqual(delivered(p), SORTED)
for (S, q), (kind, a, plan) in v.table.items():
if kind == "plan":
self.assertEqual(a, want[S][0 if q == ANY else 1])
self.assertEqual(cost(m, plan), a)
else:
self.assertLessEqual(a, want[S][0 if q == ANY else 1])
def test_rules_reach_every_split(self):
for n in range(1, 7):
memo = Memo(n)
memo.explore_all(memo.insert_left_deep())
groups = {S for S in memo.exprs}
self.assertEqual(len(groups), 2 ** n - 1)
for S in groups:
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(memo.exprs[S]), splits)
self.assertEqual(len(memo.exprs[S]), len(splits))
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])
schema = want.schema
for prop in (ANY, SORTED):
_, p = volcano(m, prop)
rows = execute(p, db, rng)
self.assertEqual(dbrel.Relation(schema, [tuple(r[a] for a in 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])
self.assertEqual(m.size(frozenset([1, 2])), 100)
self.assertEqual(m.size(frozenset([0, 1, 2])), 200)
self.assertEqual(volcano(m, ANY), (950, ("HashJoin", ("TableScan", 0),
("HashJoin", ("TableScan", 1), ("TableScan", 2)))))
self.assertEqual(volcano(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):
volcano(Model([1], [1], [False]), "hashed")
self.assertEqual(volcano(Model([7], [1], [False]), SORTED), (21, ("Sort", ("TableScan", 0))))
with self.assertRaises(ValueError):
plan_cost(Model([1, 1], [1, 1], [False, False]), ("MergeJoin", ("TableScan", 0), ("TableScan", 1)))
if __name__ == "__main__":
unittest.main()
History
Goetz Graefe and David DeWitt presented the EXODUS optimizer generator in 1987, which already generated an optimizer from rules. Graefe and William McKenna presented the Volcano optimizer generator at ICDE 1993. Its aims were extensibility and an efficient search, and it brought physical properties and enforcers, a top-down search with memoization and a cost limit, and a split between the logical and the physical part of the model. In 1995 Graefe described its successor, the Cascades framework, which kept the memo and the goal-driven search but explored on demand.
References
- The Volcano optimizer generator: extensibility and efficient search, the model specification with operators, algorithms, enforcers, rules and properties, and the search procedure FindBestPlan with its look-up table and cost limit
- The Cascades framework for query optimization, the description of the Volcano search strategy and its two phases, compared with the search of Cascades
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KJT4MR Edit this page History Report an error Markdown