Algorithm Search⌘K

Algorithmresearch

DPhyp

Also called hypergraph-based join enumeration, DPhyp join enumeration.

An extension of DPccp to query hypergraphs, which handles complex join predicates and the reordering of outer joins.

Time
O(3^n m^2) worst
Space
O(2^n) extra
Where
m = the number of hyperedges; n = the number of relations
Properties
deterministicexactrecursive
Origin
Guido Moerkotte, Thomas Neumann, 2008

DPhyp is a dynamic program that finds the cheapest bushy join tree without cross products when the join predicates form a hypergraph. A simple join predicate such as R.a=S.bR.a = S.b links two relations. A complex one, such as R.a+S.b=T.cR.a + S.b = T.c, needs RR and SS on one side of the join and TT on the other: it is a hyperedge {{R,S},{T}}\{\{R, S\}, \{T\}\}. DPccp cannot use such a predicate, and a system that drops it may see a query graph that is not connected. DPhyp extends the enumeration of DPccp to hyperedges. It emits every pair of disjoint connected sets that a hyperedge links, each once, in an order where the best plans of both halves are already final. Moerkotte and Neumann gave it in 2008, and they also showed how to encode the reordering limits of outer joins and antijoins as hyperedges.

In plain words

Some join conditions need three or more tables at once. Such a condition can only be checked when the join puts one group of its tables on the left and the other group on the right. The query then is not a simple graph of tables but a graph whose edges connect groups of tables.

DPhyp keeps the cheapest plan for each group of tables, as other dynamic programs for join order do. It grows groups from their smallest table, and it grows partners for each group, so that it only tries joins that can check a condition. When an edge leads to a whole group of tables, it steps into one table of that group and keeps growing from there. Some groups it reaches this way are not linked yet. It skips those, because no plan for them is in its table.

The problem

The input is a query hypergraph on relations v0,…,vn−1v_0, \ldots, v_{n-1}, with the size of each relation, and a set of hyperedges. A hyperedge is a pair {u,w}\{u, w\} of disjoint nonempty sets of relations with a selectivity. A hyperedge links two disjoint sets AA and BB if one of its sides is inside AA and the other is inside BB. A set is connected if it has one relation, or if it splits into two disjoint connected sets that a hyperedge links. The cost of a join tree is the sum of a join cost over its inner nodes, where the join cost depends only on the sets of the two inputs, for example CoutC_{out}, the size of the result. The size of a set is the product of the sizes of its relations and of the selectivities of the hyperedges inside it. The output is a cheapest bushy join tree in which a hyperedge links the two inputs of every join. A simple graph is the case where every side has one relation; then this is the problem that DPccp solves.

For sets SS and XX, N(S,X)N(S, X) is the neighborhood: take every side ww of a hyperedge whose other side is inside SS and which is disjoint from SS and XX, keep the sides ww that contain no other such side, and take the member with the smallest index of each. Bi={v0,…,vi}B_i = \{v_0, \ldots, v_i\}.

The algorithm

  1. DPHYP(hypergraph H with relations v_0, ..., v_(n-1))
  2. 1for each relation v do best[{v}] ← the scan of v
  3. 2for i ← n-1 down to 0 do
  4. 3EMIT-CSG({v_i})
  5. 4ENUMERATE-CSG-REC({v_i}, B_i)
  6. 5return best[all relations]
  1. ENUMERATE-CSG-REC(S1, X)
  2. 1N ← N(S1, X)
  3. 2for each nonempty subset S' of N, smaller subsets first do
  4. 3if best[S1 ∪ S'] is not empty then EMIT-CSG(S1 ∪ S')
  5. 4for each nonempty subset S' of N, smaller subsets first do ENUMERATE-CSG-REC(S1 ∪ S', X ∪ N)
  6. EMIT-CSG(S1)
  7. 5X ← S1 ∪ B_min(S1)
  8. 6N ← N(S1, X)
  9. 7for each v_i in N, by decreasing i do
  10. 8if a hyperedge links S1 and {v_i} then EMIT-CSG-CMP(S1, {v_i})
  11. 9ENUMERATE-CMP-REC(S1, {v_i}, X ∪ (B_i ∩ N))
  12. ENUMERATE-CMP-REC(S1, S2, X)
  13. 10N ← N(S2, X)
  14. 11for each nonempty subset S' of N, smaller subsets first do
  15. 12if best[S2 ∪ S'] is not empty and a hyperedge links S1 and S2 ∪ S' then EMIT-CSG-CMP(S1, S2 ∪ S')
  16. 13for each nonempty subset S' of N, smaller subsets first do ENUMERATE-CMP-REC(S1, S2 ∪ S', X ∪ N)
  17. EMIT-CSG-CMP(S1, S2)
  18. 14S ← S1 ∪ S2
  19. 15for (P1, P2) in (best[S1], best[S2]) and (best[S2], best[S1]) do
  20. 16if best[S] is empty or cost(P1 ⋈ P2) < cost(best[S]) then best[S] ← P1 ⋈ P2

The structure is that of DPccp. The main loop starts a search from each relation viv_i and only lets it grow into relations with a larger index. ENUMERATE-CSG-REC grows a set by subsets of its neighborhood, and the set XX keeps two branches from making the same set. EMIT-CSG looks for partners of a set S1S_1, only above its smallest index, so each unordered pair appears once. There are two changes. First, the neighborhood holds one representative relation of each hyperedge side, so a step can reach a set that is not connected yet; line L8 skips such a set, because it has no plan in the table, and line L9 keeps growing it. Second, line L17 tests that a hyperedge really links the two halves, because a partner can be connected but meet a hyperedge with only part of a side.

Example

Four relations AA, BB, CC and DD have 10, 20, 30 and 40 tuples. The predicates are A.k=B.kA.k = B.k with selectivity 1/10, C.k=D.kC.k = D.k with selectivity 1/10, and A.x+B.y=C.z+D.wA.x + B.y = C.z + D.w with selectivity 1/100, which is the hyperedge {{A,B},{C,D}}\{\{A, B\}, \{C, D\}\}. The cost is CoutC_{out}.

step set what happens
i=3i = 3 DD no neighbors above it
i=2i = 2 CC partner DD: pair (C,D)(C, D), best[CD]\mathrm{best}[CD] costs 120
CDCD visited at line L8; no partners above index 2
i=1i = 1 BB its only simple neighbor AA is below it, and the hyperedge needs AA too, so nothing grows
i=0i = 0 AA partner BB: pair (A,B)(A, B), best[AB]\mathrm{best}[AB] costs 20
ABAB the hyperedge gives the representative CC; {C}\{C\} alone is not linked to ABAB, but the search grows it to CDCD: pair (AB,CD)(AB, CD), best[ABCD]\mathrm{best}[ABCD] costs 120+20+24=164120 + 20 + 24 = 164
ABCABC reached from ABAB through the representative CC; not connected, so line L8 skips it
ABCDABCD reached from ABCABC; it has a plan, so EMIT-CSG runs and finds no partner

The result is (A⋈B)⋈(C⋈D)(A \bowtie B) \bowtie (C \bowtie D) with cost 164. There are three csg-cmp pairs in all. A join such as A⋈CA \bowtie C is never tried, because no predicate links AA and CC, and ABCABC is reached but never planned. If the hyperedge were split into the simple edges AA-CC, AA-DD, BB-CC and BB-DD, a simple enumerator would also try joins such as A⋈CA \bowtie C, where the predicate cannot be checked yet.

Correctness

The proof follows that of DPccp, with three changes. Connectivity has the recursive definition above. One lemma replaces the edge argument: if a set TT is connected, every split of TT into two nonempty parts is crossed by a hyperedge, so a search from inside TT always has a representative in TT to step into. The searches then visit every connected set with the right smallest index exactly once, and never visit a set before its subsets. The table test at line L8 makes this enough: by induction over the run, when a set is visited, all pairs with that union have been used, so the set is in the table exactly when it is connected. Each csg-cmp pair is then used exactly once, with final plans for both halves, and the usual argument shows that the plan for all relations is optimal. The proof file has the details.

Proof: DPhyp emits every csg-cmp pair of a hypergraph once, with final plans for both halves, and finds the cheapest plan without cross productsfull

Setting. The hypergraph HH has the relations v0,…,vn−1v_0, \ldots, v_{n-1} and a set of hyperedges. A hyperedge is an unordered pair {u,w}\{u, w\} of disjoint nonempty sets of relations. A hyperedge links two disjoint sets AA and BB if one of its sides is inside AA and the other side is inside BB. A set of relations is connected if it has one relation, or if it is the union of two disjoint connected sets that a hyperedge links. A csg-cmp pair is an unordered pair {S1,S2}\{S_1, S_2\} of disjoint connected sets that a hyperedge links. A plan without cross products is a leaf, or a join of two plans without cross products whose sets a hyperedge links. The cost of a join is c(P1)+c(P2)+j(∣S1∣,∣S2∣,∣S1∪S2∣)c(P_1) + c(P_2) + j(|S_1|, |S_2|, |S_1 \cup S_2|), where the sizes depend only on the sets. Bi={vj:j≤i}B_i = \{v_j : j \le i\}, and min⁡(S)\min(S) is the smallest index in SS.

For sets SS and XX, a candidate is a side ww of a hyperedge whose other side uu is inside SS, with ww disjoint from S∪XS \cup X. N(S,X)N(S, X) holds the member with the smallest index of each candidate that contains no other candidate. Every candidate ww contains a candidate with no smaller candidate inside it, so ww contains a member of N(S,X)N(S, X). N(S,X)N(S, X) is disjoint from S∪XS \cup X. Lines L7, L9, L16 and L18 go through the nonempty subsets of NN in increasing order as integers, so every subset comes before its proper supersets. Line L8 and the call EMIT-CSG of line L3 are the visits of a set; line L13 and the test of line L17 are the visits of a set in the complement search.

Lemma 1 (cuts). If TT is connected and SS is a nonempty proper subset of TT, a hyperedge links SS and T−ST - S.

Proof. By induction on ∣T∣|T|. Write T=T1∪T2T = T_1 \cup T_2 with T1T_1 and T2T_2 connected and linked by a hyperedge ee. If S∩T1S \cap T_1 is a nonempty proper subset of T1T_1, the induction hypothesis gives a hyperedge with one side in S∩T1⊆SS \cap T_1 \subseteq S and the other in T1−S⊆T−ST_1 - S \subseteq T - S. The same holds for T2T_2. Otherwise SS contains all or none of T1T_1, and all or none of T2T_2. As SS is nonempty and not all of TT, S=T1S = T_1 or S=T2S = T_2, and ee links SS and T−ST - S. □\square

Lemma 2 (the recursive search). Let SS be nonempty and S⊆XS \subseteq X. The call ENUMERATE-CSG-REC(S,X)(S, X) visits each set at most once, and each visited set TT has T⊋ST \supsetneq S and T∩X=ST \cap X = S. It visits every connected TT with T⊋ST \supsetneq S and T∩X=ST \cap X = S. If U⊊TU \subsetneq T are two visited sets, UU is visited first. The same holds for the sets that ENUMERATE-CMP-REC(S1,S,X)(S_1, S, X) tests at line L17.

Proof. The two procedures make the same calls and visit the same sets, so we prove it for the first one, by induction on the number of relations outside XX. Let N=N(S,X)N = N(S, X). Line L8 visits S∪S′S \cup S' for each nonempty S′⊆NS' \subseteq N. The call of line L9 for S′S' visits, by induction, sets T′T' with T′⊋S∪S′T' \supsetneq S \cup S' and T′∩(X∪N)=S∪S′T' \cap (X \cup N) = S \cup S', so T′∩N=S′T' \cap N = S' and T′T' is not inside X∪NX \cup N. The sets of line L8 are inside X∪NX \cup N. So no set is visited twice, and since N∩X=∅N \cap X = \emptyset, each visited set meets XX only in SS.

Let TT be connected with T⊋ST \supsetneq S and T∩X=ST \cap X = S. By Lemma 1 a hyperedge has one side u⊆Su \subseteq S and the other side w⊆T−Sw \subseteq T - S. Then ww is disjoint from S∪XS \cup X, so it is a candidate and contains a member of NN. So S′=T∩NS' = T \cap N is not empty. If T=S∪S′T = S \cup S', line L8 visits TT. Otherwise T⊋S∪S′T \supsetneq S \cup S' and T∩(X∪N)=S∪S′T \cap (X \cup N) = S \cup S', and the call of line L9 for S′S', whose XX is larger, visits TT by induction. Lemma 1 is the only place where the proof uses that TT is connected; SS need not be connected.

For the order, let U⊊TU \subsetneq T be visited, with SU′=U∩N⊆ST′=T∩NS'_U = U \cap N \subseteq S'_T = T \cap N. If line L8 visits TT, then U⊆X∪NU \subseteq X \cup N, so line L8 visits UU too, for a smaller subset. If a call of line L9 visits TT and line L8 visits UU, then UU comes first, because the loop of line L7 ends before the loop of line L9 starts. If both come from calls of line L9, then SU′=ST′S'_U = S'_T and the induction hypothesis applies to that call, or SU′⊊ST′S'_U \subsetneq S'_T and the call for SU′S'_U comes first. □\square

Lemma 3 (the main loop). The iteration of line L2 for ii visits {vi}\{v_i\} first and then, each at most once, sets with smallest index ii. It visits every connected set with smallest index ii. If U⊊TU \subsetneq T are visited in it, UU is visited first.

Proof. Apply Lemma 2 with S={vi}S = \{v_i\} and X=BiX = B_i: a set T⊋{vi}T \supsetneq \{v_i\} meets BiB_i only in viv_i exactly when its smallest index is ii. Line L3 visits {vi}\{v_i\} before line L4 starts. □\square

Lemma 4 (complements). Suppose that EMIT-CSG(S1)(S_1) runs, with m=min⁡(S1)m = \min(S_1), at a time when best\mathrm{best} holds every connected set with smallest index above mm and holds only connected sets. Then it calls EMIT-CSG-CMP(S1,S2)(S_1, S_2), each exactly once, for the connected sets S2S_2 that are disjoint from S1S_1, have smallest index above mm, and are linked to S1S_1 by a hyperedge.

Proof. Let X=S1∪BmX = S_1 \cup B_m and N=N(S1,X)N = N(S_1, X) (lines L10 and L11). For vi∈Nv_i \in N, let Xi=X∪(Bi∩N)X_i = X \cup (B_i \cap N), which contains viv_i. The iteration of line L12 for viv_i tests {vi}\{v_i\} at line L13, and by Lemma 2 for ENUMERATE-CMP-REC(S1,{vi},Xi)(S_1, \{v_i\}, X_i) it tests, each at most once, sets T⊋{vi}T \supsetneq \{v_i\} with T∩Xi={vi}T \cap X_i = \{v_i\}, including all connected ones. Each set tested in this iteration contains viv_i and no other member of Bi∩NB_i \cap N, so viv_i is its member of NN with the smallest index. Hence different iterations test different sets.

Let S2S_2 be a set as in the lemma. Some hyperedge has one side in S1S_1 and the other side ww in S2S_2. As S2S_2 is disjoint from S1S_1 and from BmB_m, ww is a candidate, so S2S_2 meets NN. Let viv_i be the member of S2∩NS_2 \cap N with the smallest index. Then S2∩Xi={vi}S_2 \cap X_i = \{v_i\}, so the iteration for viv_i tests S2S_2. The set is in best\mathrm{best} by the assumption (a single relation is there by line L1), and a hyperedge links it to S1S_1, so line L13 or line L17 calls EMIT-CSG-CMP(S1,S2)(S_1, S_2). Conversely, a call happens only for a tested set that is in best\mathrm{best}, so connected, and linked to S1S_1; it is disjoint from XX, so from S1S_1, and its indexes are all above mm. □\square

Lemma 5 (final plans). The following hold at every point of the run.

(a) Every set in best\mathrm{best} is connected.

(b) When line L8 visits a set TT, every csg-cmp pair with union TT has been used by EMIT-CSG-CMP already.

(c) At the start of the iteration of line L2 for ii, every connected set with smallest index above ii is in best\mathrm{best}, and every csg-cmp pair whose union has smallest index above ii has been used.

(d) Every csg-cmp pair is used at most once, as (S1,S2)(S_1, S_2) with min⁡(S1)<min⁡(S2)\min(S_1) < \min(S_2), during EMIT-CSG(S1)(S_1).

Proof. (a) EMIT-CSG-CMP(S1,S2)(S_1, S_2) runs only when both sets are in best\mathrm{best} and a hyperedge links them, so their union is connected if both are. (d) EMIT-CSG-CMP is called only from EMIT-CSG(S1)(S_1) with S2S_2 disjoint from Bmin⁡(S1)B_{\min(S_1)}, and Lemma 4 gives each S2S_2 once per call. EMIT-CSG(S1)(S_1) runs at most once, because a set is visited at most once (Lemma 3) and the sets that line L8 visits have at least two relations, while line L3 visits single relations.

(b) and (c) together, by induction over the run. (c) holds for i=n−1i = n - 1, as there is nothing above. Assume (c) for ii, and consider the sets that the iteration for ii visits, in order. Let TT be visited at line L8, and let {U1,U2}\{U_1, U_2\} be a csg-cmp pair with union TT and min⁡(U1)=i\min(U_1) = i. Then U1⊊TU_1 \subsetneq T is connected with smallest index ii, so by Lemma 3 it is visited, and before TT. If U1={vi}U_1 = \{v_i\}, line L3 calls EMIT-CSG(U1)(U_1). Otherwise U1U_1 has at least two relations, so it is the union of some csg-cmp pair; by (b) for U1U_1 that pair has been used, so U1U_1 is in best\mathrm{best} and line L8 calls EMIT-CSG(U1)(U_1). By (a) and (c), Lemma 4 applies to this call, and it uses {U1,U2}\{U_1, U_2\}, because U2U_2 has smallest index above ii. This call ends before TT is visited, which proves (b) for TT. At the end of the iteration, every connected set TT with smallest index ii and two or more relations has been visited at line L8 (Lemma 3), so all pairs with union TT have been used by (b). Such a set has at least one pair, so TT is in best\mathrm{best}, and {vi}\{v_i\} is there by line L1. This is (c) for i−1i - 1. □\square

So every csg-cmp pair is used exactly once: at most once by (d), and at least once by the argument for (b) and (c). When EMIT-CSG-CMP(S1,S2)(S_1, S_2) runs, all pairs with union S1S_1 have been used (by (b), or S1S_1 is a single relation), and all pairs with union S2S_2 have been used (by (c), as min⁡(S2)>min⁡(S1)\min(S_2) > \min(S_1)).

Theorem. If HH is connected, line L5 returns a cheapest plan without cross products for all nn relations. If HH is not connected, the set of all relations never enters best\mathrm{best}.

Proof. Let opt(S)\mathrm{opt}(S) be the least cost of a plan without cross products for a connected set SS. We show that after all pairs with union SS are used, best[S]\mathrm{best}[S] is a plan for SS without cross products of cost opt(S)\mathrm{opt}(S). For a single relation this holds by line L1. Every entry that line L21 stores joins two stored plans whose sets a hyperedge links, so it is a plan without cross products for its set. Take a cheapest plan QQ for SS with ∣S∣≥2|S| \ge 2. Its last join combines plans Q1Q_1 and Q2Q_2 for sets S1S_1 and S2S_2. By induction on the plan, the set of every plan without cross products is connected, so {S1,S2}\{S_1, S_2\} is a csg-cmp pair, and it is used. At that moment best[S1]\mathrm{best}[S_1] and best[S2]\mathrm{best}[S_2] are final, so by induction on ∣S∣|S| they cost opt(S1)≤c(Q1)\mathrm{opt}(S_1) \le c(Q_1) and opt(S2)≤c(Q2)\mathrm{opt}(S_2) \le c(Q_2). Line L20 tries both orders of the inputs and the join term depends only on the sets, so one candidate costs at most c(Q)=opt(S)c(Q) = \mathrm{opt}(S), and line L21 keeps a plan of that cost or less. No plan is cheaper than opt(S)\mathrm{opt}(S). If HH is connected, the set of all relations is connected, so it is in best\mathrm{best} at the end by (c). If HH is not connected, (a) keeps it out of best\mathrm{best}. ■\blacksquare

Notes. The test at line L8 is needed: Lemma 2 visits sets that are not connected, for example S∪{min⁡(w)}S \cup \{\min(w)\} when ww has two or more relations. The proof uses about N(S,X)N(S, X) only that it is disjoint from S∪XS \cup X and that every candidate contains one of its members; keeping only the candidates with no smaller candidate inside makes NN smaller and does not change the result. For a graph whose hyperedges all have one relation on each side, every visited set is connected, and the run makes the same calls as DPccp.

Work. In the main loop each set is visited at most once, so there are at most 2n2^n visits. In the complement search for S1S_1, each set disjoint from S1S_1 is tested at most once. So the number of tests is at most the number of pairs of disjoint sets, which is less than 3n3^n. Each call of a recursive procedure belongs to a visited or tested set, and computes one neighborhood. With mm hyperedges and the sets stored as bitmasks, one neighborhood takes O(m2)O(m^2) steps in the code of this page, which removes the candidates that contain another one by comparing pairs; a link test takes O(m)O(m) steps and a size takes O(n+m)O(n + m) steps. A connected hypergraph has m≥n−1m \ge n - 1, because each join of the recursive definition needs a hyperedge that crosses it and no other join of the same split tree. So the work is O(3nm2)O(3^n m^2), and the table holds at most 2n2^n plans.

Complexity

With the sets stored as bitmasks, each set is visited at most once in the main search, and for each S1S_1 each set disjoint from it is tested at most once in the partner search. So there are fewer than 3n3^n tests, and each costs one neighborhood, which this page computes in O(m2)O(m^2) steps for mm hyperedges. That gives O(3nm2)O(3^n m^2) time in the worst case and O(2n)O(2^n) space for the table. The bound is loose for sparse hypergraphs. For a simple graph, DPhyp makes the same calls as DPccp and does O(nc)O(n c) work for cc csg-cmp pairs, which is (n3−n)/6(n^3 - n)/6 pairs for a chain.

Properties

  • Exact. The result is a cheapest bushy plan without cross products for any cost that adds a join term which depends only on the sets of the two inputs.
  • Each pair once. Every csg-cmp pair is used exactly once. Some sets that are not connected are reached on the way and skipped.
  • Same as DPccp on graphs. On a simple graph it enumerates the same pairs in the same order.
  • Needs a connected hypergraph. If the hypergraph is not connected, there is no plan without a cross product, and the table never holds the set of all relations.

Variants and improvements

  • Non-inner joins. For an outer join or an antijoin, some orders give a different result. The 2008 paper encodes these limits in the hyperedges: the sides of the hyperedge for such a join hold the relations that must be present on each side, so that the enumeration only builds valid orders.
  • Conflict detection. Later work studies which reorderings of non-inner joins are valid and how to detect the conflicts during the enumeration, without changing the enumeration itself.
  • Physical properties. As in the Selinger enumeration, the table can keep one plan per set and interesting order without a change to the enumeration.
  • Large queries. For queries too large for exact enumeration, a heuristic such as greedy operator ordering can build a plan from the same hypergraph.

When to use it

Use it as the exact bushy join enumerator of an optimizer when the query has predicates over three or more relations, or outer joins, semijoins and antijoins whose order is limited. For a query with only simple equality predicates and inner joins, DPccp does the same work. As with any exact join enumerator, it is practical for queries with up to about 10 to 20 relations, depending on the shape of the hypergraph.

Pitfalls

  • Skipping the table test. Line L8 must test that the set has a plan. Without the test, EMIT-CSG runs for sets that are not connected.
  • Skipping the link test. Line L17 must test that a hyperedge links S1S_1 and the partner. A partner that is connected and next to S1S_1 through a representative may not hold a whole side of any hyperedge into S1S_1.
  • Subset order. As in DPccp, the subsets of NN must come smaller first, or a set can be used as a half before its best plan is final.
  • Asymmetric costs. Each unordered pair appears once, so line L20 must try both orders of the inputs when the join cost is not symmetric.
  • Selectivities of hyperedges. A hyperedge applies to a set only when both of its sides are inside the set; its selectivity must not be applied to a join that has only part of a side.

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)
dphyp.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dphyp/. The authors are listed in prov/CD2W8Y.jsonl.
"""DPhyp: join enumeration over a query hypergraph (Moerkotte and Neumann, 2008).

A hyperedge {u, w} joins two disjoint nonempty sets of relations u and w: it
is a predicate that needs all relations of u on one side of the join and all
relations of w on the other, such as R0.a + R1.b = R2.c with u = {R0, R1} and
w = {R2}. A simple edge has |u| = |w| = 1.

A set S is connected if it is one relation, or it splits into two disjoint
connected sets S1 and S2 with a hyperedge {u, w}, u within S1 and w within S2.
A csg-cmp pair is such a split. DPhyp emits every csg-cmp pair exactly once,
in an order where the plans of both halves are final, and so finds the
cheapest bushy plan without cross products.

Sets of relations are bitmasks. A plan is a relation number or a pair
(left, right). The cost of a plan is the sum of join_cost(|left|, |right|,
|result|) over its joins. The size of a set is the product of the sizes of its
relations and of the selectivities of the hyperedges inside it.
"""

from fractions import Fraction
from typing import Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union

Plan = Union[int, tuple]
JoinCost = Callable[[Fraction, Fraction, Fraction], Fraction]
Hyperedge = Tuple[int, int]


def c_out(left: Fraction, right: Fraction, out: Fraction) -> Fraction:
    return out


def hash_cost(left: Fraction, right: Fraction, out: Fraction) -> Fraction:
    """An asymmetric cost: the right input is the build side."""
    return out + left + 3 * right


def lowest(S: int) -> int:
    """The singleton of the member of S with the smallest index."""
    return S & -S


def members(S: int) -> List[int]:
    return [i for i in range(S.bit_length()) if S >> i & 1]


def subsets(N: int) -> Iterator[int]:
    """The nonempty subsets of N in increasing order as integers."""
    s = (0 - N) & N
    while s:
        yield s
        s = (s - N) & N


class Hypergraph:
    """Relation sizes and hyperedges, each a pair of disjoint nonempty bitmasks with a selectivity."""

    def __init__(self, card: Sequence, edges: Sequence[Tuple[int, int, Fraction]]) -> None:
        self.n = len(card)
        self.card = [Fraction(c) for c in card]
        self.edges: List[Tuple[int, int, Fraction]] = []
        for u, w, f in edges:
            if not u or not w or u & w or (u | w) >> self.n:
                raise ValueError("a hyperedge needs two disjoint nonempty sets of relations")
            self.edges.append((u, w, Fraction(f)))
        self.directed = [(u, w) for u, w, _ in self.edges] + [(w, u) for u, w, _ in self.edges]

    def size(self, S: int) -> Fraction:
        p = Fraction(1)
        for i in members(S):
            p *= self.card[i]
        for u, w, f in self.edges:
            if (u | w) & ~S == 0:
                p *= f
        return p

    def joins(self, S1: int, S2: int) -> bool:
        """True if some hyperedge has one side within S1 and the other within S2."""
        return any(u & ~S1 == 0 and w & ~S2 == 0 for u, w in self.directed)

    def neighborhood(self, S: int, X: int) -> int:
        """N(S, X): the representative min(w) of each minimal w such that {u, w}
        is a hyperedge with u within S and w disjoint from S and X."""
        cands = {w for u, w in self.directed if u & ~S == 0 and w & (S | X) == 0}
        out = 0
        for w in cands:
            if not any(v != w and v & ~w == 0 for v in cands):
                out |= lowest(w)
        return out


class DPhyp:
    def __init__(self, h: Hypergraph, join_cost: JoinCost = c_out,
                 on_pair: Optional[Callable[[int, int], None]] = None) -> None:
        self.h, self.join_cost, self.on_pair = h, join_cost, on_pair
        self.best: Dict[int, Tuple[Fraction, Plan]] = {}

    def solve(self) -> Tuple[Fraction, Plan]:
        h = self.h
        for v in range(h.n):
            self.best[1 << v] = (Fraction(0), v)  # @line L1
        for v in range(h.n - 1, -1, -1):  # @line L2
            self.emit_csg(1 << v)  # @line L3
            self.enumerate_csg_rec(1 << v, (1 << (v + 1)) - 1)  # @line L4
        full = (1 << h.n) - 1
        if full not in self.best:
            raise ValueError("the hypergraph is not connected")
        return self.best[full]  # @line L5

    def enumerate_csg_rec(self, S1: int, X: int) -> None:
        N = self.h.neighborhood(S1, X)  # @line L6
        for s in subsets(N):  # @line L7
            if S1 | s in self.best:  # @line L8
                self.emit_csg(S1 | s)
        for s in subsets(N):  # @line L9
            self.enumerate_csg_rec(S1 | s, X | N)

    def emit_csg(self, S1: int) -> None:
        low = lowest(S1)
        X = S1 | (low | (low - 1))  # @line L10
        N = self.h.neighborhood(S1, X)  # @line L11
        for v in reversed(members(N)):  # @line L12
            S2 = 1 << v
            if self.h.joins(S1, S2):  # @line L13
                self.emit_csg_cmp(S1, S2)
            self.enumerate_cmp_rec(S1, S2, X | (N & ((S2 << 1) - 1)))  # @line L14

    def enumerate_cmp_rec(self, S1: int, S2: int, X: int) -> None:
        N = self.h.neighborhood(S2, X)  # @line L15
        for s in subsets(N):  # @line L16
            if S2 | s in self.best and self.h.joins(S1, S2 | s):  # @line L17
                self.emit_csg_cmp(S1, S2 | s)
        for s in subsets(N):  # @line L18
            self.enumerate_cmp_rec(S1, S2 | s, X | N)

    def emit_csg_cmp(self, S1: int, S2: int) -> None:
        if self.on_pair is not None:
            self.on_pair(S1, S2)
        h, S = self.h, S1 | S2
        out = h.size(S)  # @line L19
        for A, B in ((S1, S2), (S2, S1)):  # @line L20
            cost = self.best[A][0] + self.best[B][0] + self.join_cost(h.size(A), h.size(B), out)
            if S not in self.best or cost < self.best[S][0]:  # @line L21
                self.best[S] = (cost, (self.best[A][1], self.best[B][1]))


def dphyp(h: Hypergraph, join_cost: JoinCost = c_out,
          on_pair: Optional[Callable[[int, int], None]] = None) -> Tuple[Fraction, Plan]:
    """The cheapest plan without cross products for a connected hypergraph, and its cost."""
    return DPhyp(h, join_cost, on_pair).solve()


def plan_cost(h: Hypergraph, plan: Plan, join_cost: JoinCost = c_out) -> Fraction:
    def rec(p: Plan) -> Tuple[Fraction, int]:
        if isinstance(p, int):
            return Fraction(0), 1 << p
        cl, sl = rec(p[0])
        cr, sr = rec(p[1])
        if not h.joins(sl, sr) and not h.joins(sr, sl):
            raise ValueError("the plan has a cross product")
        return cl + cr + join_cost(h.size(sl), h.size(sr), h.size(sl | sr)), sl | sr
    return rec(plan)[0]
test_dphyp.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dphyp/. The authors are listed in prov/CD2W8Y.jsonl.

import random
import unittest
from collections import Counter
from fractions import Fraction

import dbrel
from dphyp import DPhyp, Hypergraph, c_out, dphyp, hash_cost, members, plan_cost


def connected_sets(h):
    """The connected sets by the recursive definition."""
    conn = set()
    for S in sorted(range(1, 1 << h.n), key=lambda s: bin(s).count("1")):
        if S & (S - 1) == 0:
            conn.add(S)
            continue
        A = (S - 1) & S
        while A:
            if A in conn and S & ~A in conn and h.joins(A, S & ~A):
                conn.add(S)
                break
            A = (A - 1) & S
    return conn


def brute_pairs(h):
    cs = connected_sets(h)
    return {frozenset((A, B)) for A in cs for B in cs if A & B == 0 and h.joins(A, B)}


def all_trees(h, S, memo):
    if S in memo:
        return memo[S]
    if S & (S - 1) == 0:
        memo[S] = [S.bit_length() - 1]
        return memo[S]
    out = []
    A = (S - 1) & S
    while A:
        B = S & ~A
        if h.joins(A, B):
            for ta in all_trees(h, A, memo):
                for tb in all_trees(h, B, memo):
                    out.append((ta, tb))
        A = (A - 1) & S
    memo[S] = out
    return out


def random_hypergraph(rng, n, hyper=3):
    edges = []
    for i in range(1, n):
        edges.append((1 << rng.randrange(i), 1 << i, Fraction(1, rng.choice([1, 2, 10]))))
    for _ in range(rng.randint(0, hyper)):
        if n < 2:
            break
        vs = rng.sample(range(n), rng.randint(2, n))
        cut = rng.randint(1, len(vs) - 1)
        edges.append((sum(1 << v for v in vs[:cut]), sum(1 << v for v in vs[cut:]),
                      Fraction(1, rng.choice([1, 2, 10]))))
    if n >= 2 and rng.random() < 0.5:
        edges = edges[rng.randint(0, n - 1):]
    return Hypergraph([rng.choice([1, 10, 100]) for _ in range(n)], edges)


def simple(n, pairs):
    return Hypergraph([10] * n, [(1 << i, 1 << j, Fraction(1, 2)) for i, j in pairs])


def leaves(t):
    return [t] if isinstance(t, int) else leaves(t[0]) + leaves(t[1])


class Recorder(DPhyp):
    def __init__(self, h):
        super().__init__(h)
        self.csgs = []

    def emit_csg(self, S1):
        self.csgs.append(S1)
        super().emit_csg(S1)


class TestDPhyp(unittest.TestCase):
    def test_every_cut_of_a_connected_set_is_crossed(self):
        rng = random.Random(1)
        for _ in range(100):
            h = random_hypergraph(rng, rng.randint(2, 6))
            for T in connected_sets(h):
                S = (T - 1) & T
                while S:
                    self.assertTrue(h.joins(S, T & ~S))
                    S = (S - 1) & T

    def test_pairs_once_and_plans_final_when_used(self):
        rng = random.Random(2)
        for _ in range(400):
            h = random_hypergraph(rng, rng.randint(1, 7))
            want = brute_pairs(h)
            total = Counter(A | B for A, B in want)
            done, got = Counter(), []

            def check(S1, S2):
                got.append(frozenset((S1, S2)))
                self.assertLess(S1 & -S1, S2 & -S2)
                self.assertEqual(done[S1], total[S1])
                self.assertEqual(done[S2], total[S2])
                done[S1 | S2] += 1

            r = DPhyp(h, on_pair=check)
            try:
                r.solve()
            except ValueError:
                self.assertNotIn((1 << h.n) - 1, connected_sets(h))
            self.assertEqual(len(got), len(set(got)))
            self.assertEqual(set(got), want)

    def test_each_connected_set_is_emitted_once(self):
        rng = random.Random(3)
        for _ in range(150):
            h = random_hypergraph(rng, rng.randint(1, 7))
            r = Recorder(h)
            try:
                r.solve()
            except ValueError:
                pass
            self.assertEqual(sorted(r.csgs), sorted(connected_sets(h)))

    def test_simple_graphs_give_the_dpccp_counts(self):
        for n in range(2, 9):
            chain = simple(n, [(i, i + 1) for i in range(n - 1)])
            star = simple(n, [(0, i) for i in range(1, n)])
            clique = simple(n, [(i, j) for i in range(n) for j in range(i + 1, n)])
            for h, want in ((chain, (n ** 3 - n) // 6), (star, (n - 1) * 2 ** (n - 2)),
                            (clique, (3 ** n - 2 ** (n + 1) + 1) // 2)):
                pairs = []
                dphyp(h, on_pair=lambda a, b: pairs.append((a, b)))
                self.assertEqual(len(pairs), want)

    def test_optimal_against_all_trees(self):
        rng = random.Random(4)
        tried = 0
        while tried < 60:
            h = random_hypergraph(rng, rng.randint(1, 5 if tried % 10 else 6))
            full = (1 << h.n) - 1
            trees = all_trees(h, full, {})
            if not trees:
                with self.assertRaises(ValueError):
                    dphyp(h)
                continue
            tried += 1
            for join_cost in (c_out, hash_cost):
                cost, plan = dphyp(h, join_cost)
                self.assertIn(plan, trees)
                self.assertEqual(plan_cost(h, plan, join_cost), cost)
                self.assertEqual(min(plan_cost(h, t, join_cost) for t in trees), cost)

    def test_plan_runs_and_gives_the_join(self):
        rng = random.Random(5)
        runs = 0
        while runs < 25:
            h = random_hypergraph(rng, rng.randint(1, 4))
            try:
                _, plan = dphyp(h)
            except ValueError:
                continue
            runs += 1
            db = {v: dbrel.random_relation(rng, ["id%d" % v, "x%d" % v], rng.randint(0, 4), domain=3,
                                           null_rate=0.1) for v in range(h.n)}

            def pred_of(u, w):
                def pred(row):
                    xs = [row["x%d" % i] for i in members(u) + members(w)]
                    if any(x is None for x in xs):
                        return None
                    return (sum(row["x%d" % i] for i in members(u)) - sum(row["x%d" % j] for j in members(w))) % 3 == 0
                return pred

            def conj(preds):
                def pred(row):
                    v = True
                    for p in preds:
                        v = dbrel.tv_and(v, p(row))
                    return v
                return pred

            def run(p):
                if isinstance(p, int):
                    return db[p], 1 << p
                (left, sl), (right, sr) = run(p[0]), run(p[1])
                S = sl | sr
                preds = [pred_of(u, w) for u, w, _ in h.edges
                         if (u | w) & ~S == 0 and (u | w) & ~sl and (u | w) & ~sr]
                self.assertTrue(preds)
                return dbrel.theta_join(left, right, conj(preds)), S

            naive = db[0]
            for v in range(1, h.n):
                naive = dbrel.product(naive, db[v])
            naive = dbrel.select(naive, conj([pred_of(u, w) for u, w, _ in h.edges]))
            self.assertEqual(run(plan)[0], naive)

    def test_worked_example(self):
        A, B, C, D = 1, 2, 4, 8
        h = Hypergraph([10, 20, 30, 40], [(A, B, Fraction(1, 10)), (C, D, Fraction(1, 10)),
                                          (A | B, C | D, Fraction(1, 100))])
        pairs = []
        cost, plan = dphyp(h, on_pair=lambda a, b: pairs.append((a, b)))
        self.assertEqual(pairs, [(C, D), (A, B), (A | B, C | D)])
        self.assertEqual(cost, 164)
        self.assertEqual(plan, ((0, 1), (2, 3)))
        r = Recorder(h)
        r.solve()
        self.assertEqual(r.csgs, [D, C, C | D, B, A, A | B, A | B | C | D])

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            Hypergraph([1, 2], [(1, 1, Fraction(1))])
        with self.assertRaises(ValueError):
            dphyp(Hypergraph([1, 2, 3], [(1, 2, Fraction(1, 2))]))
        self.assertEqual(dphyp(Hypergraph([5], [])), (0, 0))


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

History

The dynamic programs for join order since System R used simple query graphs. In 2006 Moerkotte and Neumann gave DPccp, which enumerates only the connected subgraph and complement pairs of such a graph. In 2008, in the paper Dynamic programming strikes back, they extended it to hypergraphs, so that complex predicates and the reordering limits of non-inner joins fit in the same enumeration. Later work refined the way that these reordering limits are turned into hyperedges.

References

  1. Dynamic programming strikes back, the query hypergraph, the neighborhood of a set, the procedures Solve, EmitCsg, EnumerateCsgRec, EnumerateCmpRec and EmitCsgCmp, and the treatment of non-inner joins
  2. Analysis of two existing and one new dynamic programming algorithm for the generation of optimal bushy join trees without cross products, the algorithm DPccp for simple query graphs, which DPhyp generalizes

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