Algorithm Search⌘K

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.

Time
O(n^2 log n) worst
Space
O(n) extra
Where
n = the number of relations
Properties
deterministicexactrecursive
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 R0,…,Rn−1R_0, \ldots, R_{n-1} with sizes ∣Ri∣>0|R_i| > 0 and a query graph that is a tree, with a selectivity fij>0f_{ij} > 0 on each edge. Under the independence assumption, the join of a set SS has ∣RS∣=∏i∈S∣Ri∣∏{i,j}⊆Sfij|R_S| = \prod_{i \in S} |R_i| \prod_{\{i,j\} \subseteq S} f_{ij} tuples. The output is a left-deep order Rv1,…,RvnR_{v_1}, \ldots, R_{v_n} in which each relation after the first has an edge to an earlier one (no cross product), with the least cost Cout=∑k=2n∣R{v1,…,vk}∣C_{out} = \sum_{k=2}^{n} |R_{\{v_1, \ldots, v_k\}}|.

Fix the first relation rr and hang the tree from it. For v≠rv \ne r with parent p(v)p(v), let T(v)=fvp(v)∣Rv∣T(v) = f_{v p(v)} |R_v|: the factor by which RvR_v multiplies the result when it is joined. For a sequence ss of non-root relations, T(s)T(s) is the product of the factors, and the cost is defined by

C(v)=T(v),C(s1s2)=C(s1)+T(s1) C(s2),rank(s)=T(s)−1C(s).C(v) = T(v), \qquad C(s_1 s_2) = C(s_1) + T(s_1)\, C(s_2), \qquad \mathrm{rank}(s) = \frac{T(s) - 1}{C(s)}.

Then Cout(r s)=∣Rr∣⋅C(s)C_{out}(r\, s) = |R_r| \cdot C(s). A cost with this form has the ASI property: exchanging two adjacent blocks AA and BB changes the cost by T(U) C(A) C(B) (rank(A)−rank(B))T(U)\, C(A)\, C(B)\, (\mathrm{rank}(A) - \mathrm{rank}(B)), where UU 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 TT and CC.

  1. IKKBZ(relations, tree of predicates)
  2. 1best ← none
  3. 2for each relation r do
  4. 3hang the tree from r; p(v) is the parent of v
  5. 4for each v ≠ r do T(v) ← f(v, p(v)) · |R_v|
  6. 5mods ← LINEARIZE(r)
  7. 6cost ← |R_r| · C(concatenation of mods)
  8. 7if best = none or cost < cost(best) then best ← (cost, r followed by mods)
  9. 8return best
  1. LINEARIZE(v)
  2. 1merged ← the modules of LINEARIZE(c) for all children c of v, merged by rank
  3. 2if v = r then return merged
  4. 3head ← the module (v), with T = C = T(v)
  5. 4while merged is not empty and rank(head) > rank(first module of merged) do
  6. 5head ← head followed by the first module of merged, which is removed
  7. 6return 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: AA with 100 tuples, BB with 1000, CC with 200, DD with 50 and EE with 10. The query tree has the edges AA-BB (selectivity 1/100), AA-CC (1/50), CC-DD (1/10) and CC-EE (1/2).

With AA first, T(B)=10T(B) = 10, T(C)=4T(C) = 4, T(D)=5T(D) = 5 and T(E)=5T(E) = 5, so the ranks of the single relations are 9/10, 3/4, 4/5 and 4/5. CC has a smaller rank than its children, so LINEARIZE(CC) returns CC, DD, EE unchanged, and the root merges this list with BB: the order is ACDEBA C D E B. Its cost is 100⋅(4+4⋅5+20⋅5+100⋅10)=112 400100 \cdot (4 + 4 \cdot 5 + 20 \cdot 5 + 100 \cdot 10) = 112\,400.

With DD first, the tree hangs as DD-CC, and CC has the children AA and EE. Now T(C)=20T(C) = 20 and T(A)=2T(A) = 2, so rank(C)=19/20\mathrm{rank}(C) = 19/20 is larger than rank(A)=1/2\mathrm{rank}(A) = 1/2, but AA must come after CC. Line L13 glues them into the module CACA with T=40T = 40 and C=20+20⋅2=60C = 20 + 20 \cdot 2 = 60, so its rank is 39/60=13/2039/60 = 13/20. That is below rank(E)=4/5\mathrm{rank}(E) = 4/5, so the loop stops.

first relation modules after LINEARIZE order CoutC_{out}
AA CC, DD, EE, BB ACDEBA C D E B 112 400
BB AA, CC, DD, EE BACDEB A C D E 125 000
CC AA, DD, EE, BB CADEBC A D E B 112 400
DD CACA, EE, BB DCAEBD C A E B 113 000
EE CACA, DD, BB ECADBE C A D B 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 BB 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 ∣Rr∣⋅C(s)|R_r| \cdot C(s), 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 R0,…,Rn−1R_0, \ldots, R_{n-1} with sizes ∣Ri∣>0|R_i| > 0, and the query graph is a tree whose edge {i,j}\{i, j\} has a selectivity fij>0f_{ij} > 0. The size of the join of a set SS is ∣RS∣=∏i∈S∣Ri∣∏{i,j}⊆Sfij|R_S| = \prod_{i \in S} |R_i| \prod_{\{i,j\} \subseteq S} f_{ij}. A left-deep order Rv1,…,RvnR_{v_1}, \ldots, R_{v_n} has no cross product when each RvkR_{v_k}, k≥2k \ge 2, has an edge to some earlier relation. Its cost is Cout=∑k=2n∣R{v1,…,vk}∣C_{out} = \sum_{k=2}^{n} |R_{\{v_1, \ldots, v_k\}}|.

Fix a root rr and hang the tree from it; p(v)p(v) is the parent of vv. Put T(v)=fvp(v)∣Rv∣T(v) = f_{v p(v)} |R_v| for v≠rv \ne r. For a sequence ss of non-root relations put T(s)=∏v∈sT(v)T(s) = \prod_{v \in s} T(v) and define CC by C(ε)=0C(\varepsilon) = 0, C(v)=T(v)C(v) = T(v) and C(s1s2)=C(s1)+T(s1)C(s2)C(s_1 s_2) = C(s_1) + T(s_1) C(s_2). This is well defined, because both sides of the rule for C((s1s2)s3)C((s_1 s_2) s_3) and C(s1(s2s3))C(s_1 (s_2 s_3)) equal C(s1)+T(s1)C(s2)+T(s1)T(s2)C(s3)C(s_1) + T(s_1) C(s_2) + T(s_1) T(s_2) C(s_3). Unfolding gives C(u1⋯um)=∑k=1mT(u1⋯uk)C(u_1 \cdots u_m) = \sum_{k=1}^{m} T(u_1 \cdots u_k). For a nonempty ss put rank(s)=(T(s)−1)/C(s)\mathrm{rank}(s) = (T(s) - 1) / C(s). All TT and CC of nonempty sequences are positive. A sequence of the non-root relations is valid if every vv comes after p(v)p(v) (the root counts as placed first).

Lemma 1 (orders and costs). The orders without cross products that start with rr are exactly rsr s for the valid sequences ss, and Cout(rs)=∣Rr∣⋅C(s)C_{out}(r s) = |R_r| \cdot C(s).

Proof. If ss is valid, each vv joins its parent, which is earlier. Conversely, take an order rsr s without cross products and suppose some vv comes before p(v)p(v); take the first such vv in ss. It has an earlier neighbor, which is not p(v)p(v), so it is a child ww of vv. Then ww is earlier than vv and comes before its parent vv, which contradicts the choice of vv. For the cost, a prefix ru1⋯ukr u_1 \cdots u_k of a valid order is closed under parents, so the tree edges inside it are exactly the edges {ui,p(ui)}\{u_i, p(u_i)\}, and ∣R{r,u1,…,uk}∣=∣Rr∣T(u1⋯uk)|R_{\{r, u_1, \ldots, u_k\}}| = |R_r| T(u_1 \cdots u_k). Summing over kk gives ∣Rr∣C(s)|R_r| C(s). □\square

Lemma 2 (adjacent sequence interchange). For sequences U,A,B,VU, A, B, V with AA and BB nonempty,

C(UABV)−C(UBAV)=T(U) C(A) C(B) (rank(A)−rank(B)).C(UABV) - C(UBAV) = T(U)\, C(A)\, C(B)\, (\mathrm{rank}(A) - \mathrm{rank}(B)).

Proof. C(UXV)=C(U)+T(U)C(X)+T(U)T(X)C(V)C(UXV) = C(U) + T(U) C(X) + T(U) T(X) C(V), and T(AB)=T(BA)T(AB) = T(BA), so the difference is T(U)(C(AB)−C(BA))T(U)(C(AB) - C(BA)). Then C(AB)−C(BA)=C(A)+T(A)C(B)−C(B)−T(B)C(A)=C(B)(T(A)−1)−C(A)(T(B)−1)=C(A)C(B)(rank(A)−rank(B))C(AB) - C(BA) = C(A) + T(A) C(B) - C(B) - T(B) C(A) = C(B)(T(A) - 1) - C(A)(T(B) - 1) = C(A) C(B) (\mathrm{rank}(A) - \mathrm{rank}(B)). □\square

So, in any sequence, exchanging two adjacent blocks ABA B into BAB A does not raise the cost when rank(A)≥rank(B)\mathrm{rank}(A) \ge \mathrm{rank}(B), and lowers it when the inequality is strict.

Lemma 3 (rank of a concatenation). rank(AB)\mathrm{rank}(AB) is a weighted mean of rank(A)\mathrm{rank}(A) and rank(B)\mathrm{rank}(B) with positive weights C(A)C(A) and T(A)C(B)T(A) C(B).

Proof. T(A)T(B)−1=(T(A)−1)+T(A)(T(B)−1)=C(A) rank(A)+T(A)C(B) rank(B)T(A)T(B) - 1 = (T(A) - 1) + T(A)(T(B) - 1) = C(A)\,\mathrm{rank}(A) + T(A) C(B)\,\mathrm{rank}(B), and C(AB)=C(A)+T(A)C(B)C(AB) = C(A) + T(A) C(B). □\square

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 v≠rv \ne r let L(v)=M1,…,MkL(v) = M_1, \ldots, M_k be the list that LINEARIZE returns. Call a valid sequence ss vv-normal if the relations of the subtree of vv appear in ss as the blocks M1,…,MkM_1, \ldots, M_k, each contiguous, in this order (other relations may lie between the blocks). We show, for the nodes vv in post-order:

  • (a) the concatenation M1⋯MkM_1 \cdots M_k is a valid order of the subtree of vv that starts with vv, and rank(M1)≤⋯≤rank(Mk)\mathrm{rank}(M_1) \le \cdots \le \mathrm{rank}(M_k);
  • (b) every valid ss can be changed into a valid s′s' with C(s′)≤C(s)C(s') \le C(s) that is vv-normal and also ww-normal for every node ww, outside the subtree of vv, for which ss was ww-normal.

All changes below move a contiguous block of relations of the subtree of vv past a block XX that is the whole gap between two such blocks. So XX stays contiguous and in order, and a contiguous block of another subtree, which cannot contain a relation of the subtree of vv, lies entirely inside XX or entirely outside the moved span. This gives the second half of (b).

Proof of (a) and (b). Let c1,…,cmc_1, \ldots, c_m be the children of vv. By induction (a) and (b) hold for each cic_i; applying (b) to c1,…,cmc_1, \ldots, c_m in turn, we may assume ss is cic_i-normal for all ii.

Merge (line L9). Line L9 sorts all modules of the lists L(ci)L(c_i) by the key (rank, ii, position in L(ci)L(c_i)). This order keeps each L(ci)L(c_i) in its own order, because ranks inside L(ci)L(c_i) are nondecreasing by (a), so the merged order is a valid order of the subtree of vv minus vv, given vv first. In ss, list the child modules in their order of appearance. If this list is not the merged order, it has two neighbors PP before QQ with key(P)>key(Q)\mathrm{key}(P) > \mathrm{key}(Q). They come from different lists L(ci)L(c_i) and L(cj)L(c_j), since the list keeps the order inside each L(ci)L(c_i) and that order agrees with the keys. Let XX be the gap between PP and QQ in ss. It holds no relation of the subtree of vv: vv comes before every child module, and the child modules between PP and QQ are none. No relation of XX is an ancestor or a descendant of a relation of PP or QQ, and PP and QQ are not related either, so every reordering of PXQP X Q that keeps XX in order is valid. Note rank(P)≥rank(Q)\mathrm{rank}(P) \ge \mathrm{rank}(Q). If XX is empty, swap PP and QQ; by Lemma 2 the cost does not rise. Otherwise, if rank(X)≤rank(P)\mathrm{rank}(X) \le \mathrm{rank}(P), change PXP X into XPX P; else rank(X)>rank(P)≥rank(Q)\mathrm{rank}(X) > \mathrm{rank}(P) \ge \mathrm{rank}(Q) and change XQX Q into QXQ X. By Lemma 2 neither step raises the cost, and now PP and QQ 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 N1,N2,…N_1, N_2, \ldots.

Contraction (lines L11 to L13). Keep the invariant that the current head HH (at first the single relation vv) is contiguous in ss and the remaining merged modules follow it in order. Let NN be the first remaining module, with rank(H)>rank(N)\mathrm{rank}(H) > \mathrm{rank}(N), as line L12 requires. Let XX be the gap between HH and NN; it holds no relation of the subtree of vv. The parent of the first relation of NN is vv or lies in an earlier module of the same L(ci)L(c_i); that module comes earlier in the merged order, so it is already in HH. Hence every ancestor of a relation of NN is in HH, in NN or before vv, and no relation of XX is related to HH or NN. If XX is not empty: when rank(X)≤rank(H)\mathrm{rank}(X) \le \mathrm{rank}(H) change HXH X into XHX H; otherwise rank(X)>rank(H)>rank(N)\mathrm{rank}(X) > \mathrm{rank}(H) > \mathrm{rank}(N) and change XNX N into NXN X. By Lemma 2 the cost does not rise. Now HNH N is contiguous, which is the new head of line L13.

When the loop stops, the list of line L14 is HH followed by the remaining merged modules. Its ranks are nondecreasing: the remaining merged modules are sorted, and rank(H)≤rank(N)\mathrm{rank}(H) \le \mathrm{rank}(N) for the first of them if any is left. HH starts with vv, and the concatenation is valid because the merged order is valid after vv. This proves (a), and ss is now vv-normal, which proves (b). □\square

Theorem. For each root rr, the order of lines L3 to L6 is a cheapest order without cross products among those that start with rr, 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 rsr s without cross products. By Lemma 1, ss is valid. Apply (b) to every child cc of rr and then the merge step above with v=rv = r. Every non-root relation lies in the subtree of a child of rr, so all gaps XX are empty and ss becomes exactly the merged list that line L10 returns, with cost at most C(s)C(s). By Lemma 1 the cost of the result is ∣Rr∣C(⋅)|R_r| C(\cdot), which is what line L6 computes, since the code folds the modules with the rule C(s1s2)=C(s1)+T(s1)C(s2)C(s_1 s_2) = C(s_1) + T(s_1) C(s_2). Every order starts with some root, and line L2 tries all of them. ■\blacksquare

Where the hypotheses are used. Positive sizes and selectivities make every CC 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 ∣Rr∣C(s)|R_r| C(s).

Complexity

The algorithm runs once for each of the nn first relations. Ibaraki and Kameda do one run in O(nlog⁡n)O(n \log n) time, so the total is O(n2log⁡n)O(n^2 \log n); Krishnamurthy, Boral and Zaniolo reduce the total to O(n2)O(n^2). The version on this page sorts all modules of a subtree at every node, which costs O(n2log⁡n)O(n^2 \log n) for one run on a path-shaped tree and O(n3log⁡n)O(n^3 \log n) in total; it is simpler to check. The extra space is O(n)O(n) for the tree and the module lists. This is polynomial, against 2n−12^{n-1} orders without cross products for a chain query and 2(n−1)!2(n-1)! 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 C(s1)+T(s1)C(s2)C(s_1) + T(s_1) C(s_2) for some positive TT. CoutC_{out} 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 O(n2)O(n^2).
  • 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 BB costs 125 000 against 112 400.
  • Zero sizes. A relation with no tuples gives T=0T = 0 and a module with C=0C = 0, 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.

dbrel.pyI0RawGitHub
# 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 O(n2)O(n^2). The algorithm is known as IKKBZ after the five authors.

References

  1. 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
  2. Optimization of nonrecursive queries, the O(n^2) algorithm for tree queries with cost functions that have the adjacent sequence interchange (ASI) property
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example