Algorithmadvanced
IKKBZ algorithm
Also called Ibaraki-Kameda-Krishnamurthy-Boral-Zaniolo algorithm, KBZ algorithm, IKKBZ, rank-based join ordering for tree queries.
Find the optimal left-deep join order without cross products for an acyclic query graph and an ASI cost, in polynomial time.
- Solves
- Join ordering problem
- Time
- O(n^2 log n) worst
- Space
- O(n) extra
- Where
- n = the number of relations
- Model
- Word RAM
- Properties
- deterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Toshihide Ibaraki, Tiko Kameda, Ravi Krishnamurthy, Haran Boral, Carlo Zaniolo, 1984
The IKKBZ algorithm finds the cheapest left-deep join order without cross products when the query graph is a tree and the cost function has the adjacent sequence interchange (ASI) property, such as the sum of the intermediate result sizes. It runs in polynomial time, although join ordering is NP-hard in general. It fixes the first relation, which turns the query tree into a precedence order: each relation must come after its parent. Then it gives every relation and every group of relations a rank, and sorts by rank. Where the precedence order forbids the sorted position, it glues a parent to its child into one block. It tries every relation as the first one and keeps the best order. The name comes from Ibaraki and Kameda (1984) and Krishnamurthy, Boral and Zaniolo (1986).
In plain words
A plan that joins tables one at a time should first add the tables that shrink the result, and late the tables that make it grow. A good number for this is the rank of a table: how much it makes the result grow, against how much work it adds. Sorting the tables by rank gives the best order when the tables can come in any order.
But a table can only join a table that is already in the result. When a good table must wait for a poor table, the algorithm glues the two into one block and gives the block its own rank. The block is then sorted like a single table. This needs no search, so it is fast. The algorithm does this once for each possible first table and keeps the cheapest order.
The problem
The input is a set of relations with sizes and a query graph that is a tree, with a selectivity on each edge. Under the independence assumption, the join of a set has tuples. The output is a left-deep order in which each relation after the first has an edge to an earlier one (no cross product), with the least cost .
Fix the first relation and hang the tree from it. For with parent , let : the factor by which multiplies the result when it is joined. For a sequence of non-root relations, is the product of the factors, and the cost is defined by
Then . A cost with this form has the ASI property: exchanging two adjacent blocks and changes the cost by , where is the part before them. So the block with the smaller rank should come first.
The algorithm
A module is a sequence of relations that stays together, with its and .
IKKBZ(relations, tree of predicates)- 1
best ← none - 2
for each relation r do - 3
hang the tree from r; p(v) is the parent of v - 4
for each v ≠ r do T(v) ← f(v, p(v)) · |R_v| - 5
mods ← LINEARIZE(r) - 6
cost ← |R_r| · C(concatenation of mods) - 7
if best = none or cost < cost(best) then best ← (cost, r followed by mods) - 8
return best
LINEARIZE(v)- 1
merged ← the modules of LINEARIZE(c) for all children c of v, merged by rank - 2
if v = r then return merged - 3
head ← the module (v), with T = C = T(v) - 4
while merged is not empty and rank(head) > rank(first module of merged) do - 5
head ← head followed by the first module of merged, which is removed - 6
return head followed by merged
Line L9 merges lists that are already sorted by rank, so each child list keeps its own order and the precedence order inside each subtree holds. Lines L11 to L13 handle the case where a child block has a smaller rank than its parent: it should come before the parent, but it cannot, so the best place for it is directly after the parent, and the two become one module. The new module has a rank between the two old ranks, so it may also absorb the next module. Line L14 returns a list whose ranks do not decrease, which is what the parent needs for its own merge. On equal ranks the order of the merge does not change the cost.
Example
Five relations: with 100 tuples, with 1000, with 200, with 50 and with 10. The query tree has the edges - (selectivity 1/100), - (1/50), - (1/10) and - (1/2).
With first, , , and , so the ranks of the single relations are 9/10, 3/4, 4/5 and 4/5. has a smaller rank than its children, so LINEARIZE() returns , , unchanged, and the root merges this list with : the order is . Its cost is .
With first, the tree hangs as -, and has the children and . Now and , so is larger than , but must come after . Line L13 glues them into the module with and , so its rank is . That is below , so the loop stops.
| first relation | modules after LINEARIZE | order | |
|---|---|---|---|
| , , , | 112 400 | ||
| , , , | 125 000 | ||
| , , , | 112 400 | ||
| , , | 113 000 | ||
| , , | 113 000 |
Line L7 keeps the first order of cost 112 400. Of the 120 orders of five relations, 28 have no cross product; their costs range from 112 400 to 125 000, and four of them reach the minimum. Starting with the largest relation gives the worst choice of first relation here.
Correctness
Fix the first relation. The orders without cross products are exactly the sequences in which each relation comes after its parent, and the cost of such an order is , because the edges inside a prefix are exactly the parent edges of its relations. The proof turns any such sequence into the output of the algorithm without raising the cost, from the leaves up. At each node, two child modules that are in the wrong order are brought together by moving one of them past the unrelated relations between them, and then exchanged; by the ASI identity no step raises the cost. A child module that follows its parent block with a smaller rank is brought next to it the same way, which is the gluing of line L13. At the root, the result is the order of line L10, so it is optimal for that first relation, and line L2 tries all first relations. The proof file has the details.
Proof: IKKBZ finds the cheapest left-deep order without cross products for a tree queryfull
Setting. The relations are with sizes , and the query graph is a tree whose edge has a selectivity . The size of the join of a set is . A left-deep order has no cross product when each , , has an edge to some earlier relation. Its cost is .
Fix a root and hang the tree from it; is the parent of . Put for . For a sequence of non-root relations put and define by , and . This is well defined, because both sides of the rule for and equal . Unfolding gives . For a nonempty put . All and of nonempty sequences are positive. A sequence of the non-root relations is valid if every comes after (the root counts as placed first).
Lemma 1 (orders and costs). The orders without cross products that start with are exactly for the valid sequences , and .
Proof. If is valid, each joins its parent, which is earlier. Conversely, take an order without cross products and suppose some comes before ; take the first such in . It has an earlier neighbor, which is not , so it is a child of . Then is earlier than and comes before its parent , which contradicts the choice of . For the cost, a prefix of a valid order is closed under parents, so the tree edges inside it are exactly the edges , and . Summing over gives .
Lemma 2 (adjacent sequence interchange). For sequences with and nonempty,
Proof. , and , so the difference is . Then .
So, in any sequence, exchanging two adjacent blocks into does not raise the cost when , and lowers it when the inequality is strict.
Lemma 3 (rank of a concatenation). is a weighted mean of and with positive weights and .
Proof. , and .
Lemma 3 is not needed for the proof below, but it explains why the merged head of line L13 has a rank between the ranks of its parts.
The invariant. For let be the list that LINEARIZE returns. Call a valid sequence -normal if the relations of the subtree of appear in as the blocks , each contiguous, in this order (other relations may lie between the blocks). We show, for the nodes in post-order:
- (a) the concatenation is a valid order of the subtree of that starts with , and ;
- (b) every valid can be changed into a valid with that is -normal and also -normal for every node , outside the subtree of , for which was -normal.
All changes below move a contiguous block of relations of the subtree of past a block that is the whole gap between two such blocks. So stays contiguous and in order, and a contiguous block of another subtree, which cannot contain a relation of the subtree of , lies entirely inside or entirely outside the moved span. This gives the second half of (b).
Proof of (a) and (b). Let be the children of . By induction (a) and (b) hold for each ; applying (b) to in turn, we may assume is -normal for all .
Merge (line L9). Line L9 sorts all modules of the lists by the key (rank, , position in ). This order keeps each in its own order, because ranks inside are nondecreasing by (a), so the merged order is a valid order of the subtree of minus , given first. In , list the child modules in their order of appearance. If this list is not the merged order, it has two neighbors before with . They come from different lists and , since the list keeps the order inside each and that order agrees with the keys. Let be the gap between and in . It holds no relation of the subtree of : comes before every child module, and the child modules between and are none. No relation of is an ancestor or a descendant of a relation of or , and and are not related either, so every reordering of that keeps in order is valid. Note . If is empty, swap and ; by Lemma 2 the cost does not rise. Otherwise, if , change into ; else and change into . By Lemma 2 neither step raises the cost, and now and are adjacent, so swap them. The number of inverted pairs in the list drops by one. Repeat until the child modules appear in the merged order .
Contraction (lines L11 to L13). Keep the invariant that the current head (at first the single relation ) is contiguous in and the remaining merged modules follow it in order. Let be the first remaining module, with , as line L12 requires. Let be the gap between and ; it holds no relation of the subtree of . The parent of the first relation of is or lies in an earlier module of the same ; that module comes earlier in the merged order, so it is already in . Hence every ancestor of a relation of is in , in or before , and no relation of is related to or . If is not empty: when change into ; otherwise and change into . By Lemma 2 the cost does not rise. Now is contiguous, which is the new head of line L13.
When the loop stops, the list of line L14 is followed by the remaining merged modules. Its ranks are nondecreasing: the remaining merged modules are sorted, and for the first of them if any is left. starts with , and the concatenation is valid because the merged order is valid after . This proves (a), and is now -normal, which proves (b).
Theorem. For each root , the order of lines L3 to L6 is a cheapest order without cross products among those that start with , and its cost is computed correctly. Line L7 keeps the cheapest over all roots, so line L8 returns a cheapest left-deep order without cross products.
Proof. Take any order without cross products. By Lemma 1, is valid. Apply (b) to every child of and then the merge step above with . Every non-root relation lies in the subtree of a child of , so all gaps are empty and becomes exactly the merged list that line L10 returns, with cost at most . By Lemma 1 the cost of the result is , which is what line L6 computes, since the code folds the modules with the rule . Every order starts with some root, and line L2 tries all of them.
Where the hypotheses are used. Positive sizes and selectivities make every positive, so the ranks exist and Lemma 2 gives the sign of each exchange. The tree shape gives the parent of each relation, which Lemma 1 needs; on a graph with a cycle, the prefix of a valid order can contain an edge that is not a parent edge, and the cost is no longer .
Complexity
The algorithm runs once for each of the first relations. Ibaraki and Kameda do one run in time, so the total is ; Krishnamurthy, Boral and Zaniolo reduce the total to . The version on this page sorts all modules of a subtree at every node, which costs for one run on a path-shaped tree and in total; it is simpler to check. The extra space is for the tree and the module lists. This is polynomial, against orders without cross products for a chain query and for a star (see query plan).
Properties
- Exact for its space. The result is a cheapest left-deep order without cross products for a tree query under an ASI cost. It says nothing about bushy trees or about orders with cross products, which can be cheaper.
- Needs the ASI form. The cost of a sequence must be for some positive . and the nested loop cost of Ibaraki and Kameda have this form.
- Deterministic and simple. There is no table over subsets; the work is sorting and gluing.
Variants and improvements
- KBZ. Krishnamurthy, Boral and Zaniolo (1986) state the algorithm for every ASI cost and bring the total time for all first relations to .
- A fixed first relation. When the first relation is given, for example because it is the only one with a useful index, one run of lines L3 to L6 is enough.
- Cyclic query graphs. A common heuristic keeps only a spanning tree of the query graph, for example one that keeps the most selective predicates, runs IKKBZ on the tree and applies the other predicates where their relations are present. The result is then not guaranteed to be optimal; Steinbrunn, Moerkotte and Kemper (1997) compare this use of KBZ with randomized methods on large queries.
When to use it
Use it for tree queries (chains, stars, snowflakes) with many relations, where the dynamic programs over subsets are too slow, and when left-deep plans without cross products are acceptable. For up to about a dozen relations, the exact Selinger enumeration or DPccp can also choose bushy trees and physical operators. For large cyclic graphs, greedy operator ordering or IKKBZ on a spanning tree are both heuristics.
Pitfalls
- Trying one first relation only. The root changes the precedence order and the result. In the example, starting with costs 125 000 against 112 400.
- Zero sizes. A relation with no tuples gives and a module with , and the rank is not defined. An empty relation makes the whole join empty, so the order hardly matters; handle it before the algorithm.
- Floating point ranks. Ranks that are equal in exact arithmetic can compare unequal in floating point, which changes the merge order. That does not change the cost, but it can make plans differ between runs on different machines. Exact fractions or a stable tie rule avoid this.
- Costs without the ASI form. A cost that depends on the physical join method per step, such as the choice between a hash join and an index nested loop join, is usually not of this form, and then the result is a heuristic.
- Independence. The sizes come from the product of the selectivities. The order is optimal for those estimates; see cardinality estimation.
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)
ikkbz_algorithm.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ikkbz-algorithm/. The authors are listed in prov/ZKFGDY.jsonl.
"""The IKKBZ algorithm: the cheapest left-deep join order without cross
products for an acyclic (tree) query graph, under a cost function with the
adjacent sequence interchange (ASI) property.
A query has n relations 0 .. n - 1 with cardinalities card[i] and a tree of
join predicates: sel maps a pair (i, j) with i < j to the selectivity of the
predicate between R_i and R_j. Under the independence assumption the size of
the join of a set S of relations is the product of card[i] for i in S times
the product of the selectivities of the edges inside S.
The cost function is C_out of a left-deep order: the sum of the sizes of the
results of the n - 1 joins. With the root r first, a relation v that joins
its parent p(v) multiplies the size of the result by T(v) = sel(v, p(v)) *
card[v]. The cost of a sequence s of non-root relations is
C(empty) = 0, C(v) = T(v), C(s1 s2) = C(s1) + T(s1) C(s2),
with T(s) the product of T(v) over s, and C_out(r s) = card[r] * C(s).
The rank of a nonempty sequence is (T(s) - 1) / C(s).
All arithmetic is exact (Fractions).
"""
from fractions import Fraction
from itertools import permutations
from typing import Dict, List, Sequence, Tuple
Edges = Dict[Tuple[int, int], Fraction]
class Module:
"""A sequence of relations that the algorithm keeps together, with T and C."""
__slots__ = ("seq", "T", "C")
def __init__(self, seq: Tuple[int, ...], T: Fraction, C: Fraction) -> None:
self.seq, self.T, self.C = seq, T, C
def rank(self) -> Fraction:
return (self.T - 1) / self.C
def then(self, other: "Module") -> "Module":
"""The concatenation of self and other."""
return Module(self.seq + other.seq, self.T * other.T, self.C + self.T * other.C)
def edge_sel(sel: Edges, i: int, j: int) -> Fraction:
return sel[(min(i, j), max(i, j))]
def neighbors(n: int, sel: Edges) -> List[List[int]]:
adj: List[List[int]] = [[] for _ in range(n)]
for (i, j) in sel:
adj[i].append(j)
adj[j].append(i)
return [sorted(a) for a in adj]
def is_tree(n: int, sel: Edges) -> bool:
if len(sel) != n - 1:
return False
adj = neighbors(n, sel)
seen, stack = {0}, [0]
while stack:
v = stack.pop()
for w in adj[v]:
if w not in seen:
seen.add(w)
stack.append(w)
return len(seen) == n
def join_size(card: Sequence, sel: Edges, S) -> Fraction:
"""The estimated size of the join of the set S, under independence."""
p = Fraction(1)
for i in S:
p *= card[i]
for (i, j), f in sel.items():
if i in S and j in S:
p *= f
return p
def cout(card: Sequence, sel: Edges, order: Sequence[int]) -> Fraction:
"""C_out of a left-deep order: the sum of the sizes of the n - 1 join results."""
return sum((join_size(card, sel, set(order[:k])) for k in range(2, len(order) + 1)), Fraction(0))
def is_connected_order(n: int, sel: Edges, order: Sequence[int]) -> bool:
"""True if each relation after the first joins some earlier relation (no cross product)."""
adj = neighbors(n, sel)
seen = {order[0]}
for v in order[1:]:
if not any(w in seen for w in adj[v]):
return False
seen.add(v)
return True
def rooted_tree(n: int, sel: Edges, root: int) -> Tuple[Dict[int, int], Dict[int, List[int]]]:
"""Parent and children lists of the query tree rooted at root (the precedence tree)."""
adj = neighbors(n, sel)
parent, children = {root: -1}, {v: [] for v in range(n)}
stack = [root]
while stack:
v = stack.pop()
for w in adj[v]:
if w not in parent:
parent[w] = v
children[v].append(w)
stack.append(w)
for v in children:
children[v].sort()
return parent, children
def linearize(v: int, root: int, children: Dict[int, List[int]], T: Dict[int, Fraction]) -> List[Module]:
"""The modules of the subtree of v, in the order of an optimal sequence.
For v other than the root, the first module starts with v, and the ranks of
the modules are nondecreasing. For the root, the list holds only the modules
of its children (the root itself comes first in every sequence)."""
chains = [linearize(c, root, children, T) for c in children[v]]
tagged = [(m.rank(), ci, pos, m) for ci, ch in enumerate(chains) for pos, m in enumerate(ch)]
tagged.sort(key=lambda x: (x[0], x[1], x[2]))
merged = [m for _, _, _, m in tagged] # @line L9
if v == root: # @line L10
return merged
head = Module((v,), T[v], T[v]) # @line L11
while merged and head.rank() > merged[0].rank(): # @line L12
head = head.then(merged.pop(0)) # @line L13
return [head] + merged # @line L14
def ikkbz_for_root(n: int, card: Sequence, sel: Edges, root: int) -> Tuple[Fraction, Tuple[int, ...]]:
"""The cheapest order that starts with root, and its C_out."""
parent, children = rooted_tree(n, sel, root) # @line L3
T = {v: edge_sel(sel, v, parent[v]) * card[v] for v in range(n) if v != root} # @line L4
mods = linearize(root, root, children, T) # @line L5
order = (root,) + tuple(x for m in mods for x in m.seq)
rest = Module((), Fraction(1), Fraction(0))
for m in mods:
rest = rest.then(m)
cost = Fraction(card[root]) * rest.C # @line L6
return cost, order
def ikkbz(card: Sequence, sel: Edges) -> Tuple[Fraction, Tuple[int, ...]]:
"""The cheapest left-deep order without cross products, and its C_out.
sel must form a tree on the relations 0 .. n - 1. Ties go to the smaller root."""
n = len(card)
if n == 1:
return Fraction(0), (0,)
if not is_tree(n, sel):
raise ValueError("IKKBZ needs an acyclic, connected query graph")
best = None # @line L1
for r in range(n): # @line L2
cost, order = ikkbz_for_root(n, card, sel, r)
if best is None or cost < best[0]: # @line L7
best = (cost, order)
return best # @line L8
def brute_force(card: Sequence, sel: Edges) -> Tuple[Fraction, Tuple[int, ...]]:
"""Try every left-deep order without cross products."""
n = len(card)
best = None
for order in permutations(range(n)):
if is_connected_order(n, sel, order):
c = cout(card, sel, order)
if best is None or c < best[0]:
best = (c, order)
return best
test_ikkbz_algorithm.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ikkbz-algorithm/. The authors are listed in prov/ZKFGDY.jsonl.
import random
import unittest
from fractions import Fraction
from itertools import permutations
import dbrel
from ikkbz_algorithm import (Module, brute_force, cout, ikkbz, ikkbz_for_root, is_connected_order, join_size,
rooted_tree)
def random_tree(rng, n):
perm = list(range(n))
rng.shuffle(perm)
sel = {}
for i in range(1, n):
a, b = perm[i], perm[rng.randrange(i)]
sel[(min(a, b), max(a, b))] = Fraction(1, rng.choice([1, 2, 3, 5, 10, 20, 100]))
card = [rng.randint(1, 100) for _ in range(n)]
return card, sel
def seq_cost(T, seq):
"""C and T of a sequence of non-root relations, from the recurrence."""
m = Module((), Fraction(1), Fraction(0))
for v in seq:
m = m.then(Module((v,), T[v], T[v]))
return m
EXAMPLE_CARD = [100, 1000, 200, 50, 10]
EXAMPLE_SEL = {(0, 1): Fraction(1, 100), (0, 2): Fraction(1, 50), (2, 3): Fraction(1, 10), (2, 4): Fraction(1, 2)}
class TestIKKBZ(unittest.TestCase):
def test_matches_brute_force(self):
rng = random.Random(1)
for _ in range(150):
n = rng.randint(2, 7)
card, sel = random_tree(rng, n)
cost, order = ikkbz(card, sel)
self.assertEqual(sorted(order), list(range(n)))
self.assertTrue(is_connected_order(n, sel, order))
self.assertEqual(cout(card, sel, order), cost)
self.assertEqual(brute_force(card, sel)[0], cost)
def test_each_root_is_optimal_for_that_root(self):
rng = random.Random(2)
for _ in range(60):
n = rng.randint(2, 6)
card, sel = random_tree(rng, n)
for r in range(n):
cost, order = ikkbz_for_root(n, card, sel, r)
self.assertEqual(order[0], r)
self.assertEqual(cout(card, sel, order), cost)
best = min(cout(card, sel, (r,) + p) for p in permutations([v for v in range(n) if v != r])
if is_connected_order(n, sel, (r,) + p))
self.assertEqual(cost, best)
def test_cost_recurrence_equals_cout(self):
rng = random.Random(3)
for _ in range(100):
n = rng.randint(2, 6)
card, sel = random_tree(rng, n)
r = rng.randrange(n)
parent, _ = rooted_tree(n, sel, r)
T = {v: sel[(min(v, parent[v]), max(v, parent[v]))] * card[v] for v in range(n) if v != r}
for p in permutations([v for v in range(n) if v != r]):
order = (r,) + p
if is_connected_order(n, sel, order):
self.assertEqual(card[r] * seq_cost(T, p).C, cout(card, sel, order))
self.assertEqual(card[r] * seq_cost(T, p).T, join_size(card, sel, set(order)))
def test_adjacent_sequence_interchange(self):
rng = random.Random(4)
for _ in range(500):
T = {v: Fraction(rng.randint(1, 30), rng.randint(1, 30)) for v in range(6)}
vs = list(range(6))
rng.shuffle(vs)
cuts = sorted(rng.sample(range(7), 3))
U, A, B, V = vs[:cuts[0]], vs[cuts[0]:cuts[1]], vs[cuts[1]:cuts[2]], vs[cuts[2]:]
if not A or not B:
continue
ma, mb, mu = seq_cost(T, A), seq_cost(T, B), seq_cost(T, U)
diff = seq_cost(T, U + A + B + V).C - seq_cost(T, U + B + A + V).C
self.assertEqual(diff, mu.T * ma.C * mb.C * (ma.rank() - mb.rank()))
def test_worked_example(self):
cost, order = ikkbz(EXAMPLE_CARD, EXAMPLE_SEL)
self.assertEqual(cost, 112400)
self.assertEqual(order, (0, 2, 3, 4, 1))
per_root = [ikkbz_for_root(5, EXAMPLE_CARD, EXAMPLE_SEL, r) for r in range(5)]
self.assertEqual([c for c, _ in per_root], [112400, 125000, 112400, 113000, 113000])
self.assertEqual(per_root[3][1], (3, 2, 0, 4, 1))
self.assertEqual(per_root[4][1], (4, 2, 0, 3, 1))
def test_plan_runs_and_gives_the_join(self):
rng = random.Random(5)
for _ in range(40):
n = rng.randint(2, 5)
card, sel = random_tree(rng, n)
_, order = ikkbz(card, sel)
schema = {v: [] for v in range(n)}
for (i, j) in sel:
schema[i].append("k%d_%d" % (i, j))
schema[j].append("k%d_%d" % (i, j))
db = {v: dbrel.random_relation(rng, ["id%d" % v] + schema[v], rng.randint(0, 6), domain=3,
null_rate=0.1) for v in range(n)}
result = db[order[0]]
for v in order[1:]:
self.assertTrue(set(result.schema) & set(db[v].schema))
result = dbrel.natural_join(result, db[v])
naive = db[0]
for v in range(1, n):
naive = dbrel.natural_join(naive, db[v])
self.assertEqual(result, naive)
def test_rejects_cyclic_or_disconnected_graphs(self):
with self.assertRaises(ValueError):
ikkbz([10, 10, 10], {(0, 1): Fraction(1, 2), (1, 2): Fraction(1, 2), (0, 2): Fraction(1, 2)})
with self.assertRaises(ValueError):
ikkbz([10, 10, 10, 10], {(0, 1): Fraction(1, 2), (2, 3): Fraction(1, 2)})
def test_small_inputs(self):
self.assertEqual(ikkbz([7], {}), (0, (0,)))
self.assertEqual(ikkbz([10, 20], {(0, 1): Fraction(1, 10)}), (Fraction(20), (0, 1)))
if __name__ == "__main__":
unittest.main()
History
The problem is a form of job sequencing with precedence constraints: order jobs on one machine to minimize a weighted cost, where some jobs must wait for others. Monma and Sidney (1979) solved it for series-parallel precedence orders and costs with the adjacent sequence interchange property. Ibaraki and Kameda (1984) used this approach for join orders, with the nested loop cost and tree queries, and showed in the same paper that the general problem is NP-complete. Krishnamurthy, Boral and Zaniolo (1986) extended it to every ASI cost and brought the time to . The algorithm is known as IKKBZ after the five authors.
References
- Toshihide Ibaraki and Tiko Kameda, On the optimal nesting order for computing N-relational joins, ACM Transactions on Database Systems 9(3) (1984), 482 to 502, the algorithm for tree queries with the nested loop cost, which tries each relation as the first one and orders the rest by rank, in O(n^2 log n) time
- Optimization of nonrecursive queries, the O(n^2) algorithm for tree queries with cost functions that have the adjacent sequence interchange (ASI) property
- Sequencing with series-parallel precedence constraints, the adjacent sequence interchange property and the optimal sequencing of jobs under series-parallel precedence constraints, on which the join algorithm is based
- Heuristic and randomized optimization for the join ordering problem, the KBZ algorithm as one of the compared methods on large join queries, applied to a spanning tree of the query graph
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 ZKFGDY Edit this page History Report an error Markdown