Algorithm Search⌘K

Algorithmadvanced

SDD-1 semijoin optimization

Also called semijoin program, Bernstein-Goodman semijoin reduction.

Algorithm OPT of SDD-1: add the most profitable semijoin while its estimated benefit is larger than its cost, then send the reduced relations to the site that holds the most data.

Time
O(q^3 e) worst
Space
O(q e) extra
Where
e = the number of (relation, attribute) pairs in the profile; q = the number of candidate semijoins (ordered pairs of relations at different sites with a common attribute)
Properties
deterministicnot exactnot in placeofflineiterative
Origin
Philip A. Bernstein, Nathan Goodman, Eugene Wong, Christopher L. Reeve, James B. Rothnie Jr., 1981

SDD-1 was one of the first distributed database systems, and its query optimizer, Algorithm OPT, decides how to answer a join query over relations stored at different sites. OPT first sends semijoins between the sites to drop rows that cannot take part in the answer, and then moves what is left to one site, which computes the join. It picks the semijoins one at a time by a hill-climbing rule: the next semijoin is the one whose estimated benefit exceeds its estimated cost by the most. The answer is always exact, but the plan is only as good as the estimates, and the greedy rule is a heuristic.

In plain words

Three offices each keep one list: suppliers, shipments and parts. A question needs all three lists together, and sending a long list over the network is slow. So the offices first send short notes to each other. A note is a list of the numbers that one office holds, such as the supplier numbers in Massachusetts. The office that gets the note crosses out each row whose number is not on the note, because such a row cannot be in the answer. A note costs time to send, and it helps only if it crosses out many rows. The optimizer guesses both amounts from statistics, sends the best note first, and goes on while some note still saves more than it costs. At the end, all the short lists go to the office that has the most data, and that office computes the answer.

The problem

The query is a natural join Q=R1⋈⋯⋈RrQ = R_1 \bowtie \dots \bowtie R_r with local selections, as in the distributed query processing problem. Each relation is stored at one site, and attributes with the same name are joined. The bags and the NULLs follow the relational model: a NULL matches nothing. The plan must leave the answer at some site. Its cost is the amount of data sent between sites, counted in the units of the attribute widths; local work and the number of messages are free in this model.

A semijoin Ri⋉ARjR_i \ltimes_A R_j sends the distinct non-null values of Rj[A]R_j[A] to the site of RiR_i and keeps the rows of RiR_i whose AA value is among them. Its cost is ∣Rj[A]∣⋅w(A)|R_j[A]| \cdot w(A), or 0 when the two relations are at the same site.

The profile. OPT works before it sees the data, from a database profile. For each attribute domain XX the profile holds its size c(X)c(X) and width w(X)w(X). For each relation it holds the number of rows c(R)c(R) and, for the join attributes, the number of distinct values c(R.A)c(R.A). The estimates assume that the values of a column are a random subset of the domain, that the rows are spread evenly over the values, and that different columns are independent.

Estimates. A set of values such as R[A]R[A] has a selectivity ρ=c(R.A)/c(X)\rho = c(R.A)/c(X). A semijoin Ri⋉ARjR_i \ltimes_A R_j gives Ri[A]R_i[A] the new estimate ρ⋅c(X)\rho \cdot c(X), where ρ\rho is the product of the selectivities of the independent reductions that Ri[A]R_i[A] and Rj[A]R_j[A] have had; the paper keeps this history as a graph of labeled edges, so that one reduction is not counted twice. The new c(Ri)c(R_i) is c(Ri)⋅c(Ri.A)new/c(Ri.A)oldc(R_i) \cdot c(R_i.A)_{new}/c(R_i.A)_{old}. For every other attribute BB of RiR_i, the new c(Ri.B)c(R_i.B) is Yao's function of the new c(Ri)c(R_i) and the old c(Ri.B)c(R_i.B), the expected number of distinct values left when that many rows are kept. The paper uses a piecewise approximation: nn if n<b/2n < b/2, then (n+b)/3(n + b)/3 if n<2bn < 2b, else bb, for nn rows kept and bb distinct values before. The benefit of the semijoin is the drop in c(Ri)c(R_i) times the width of RiR_i.

The algorithm

  1. OPT(profile, selections)
  2. 1for each local selection σ on a relation R do update the estimates of R by σ
  3. 2append σ to the program P
  4. 3for each nonlocal semijoin sj = R_i ⋉_A R_j not yet in P do profit(sj) ← benefit(sj) - cost(sj)
  5. 4if no sj has profit(sj) > 0 then go to L6; else pick sj with the largest profit
  6. 5append sj to P, update the estimates of R_i by its effect, and go to L3
  7. 6S_a ← the site with the largest estimated data, the sum of c(R) · width(R) over its relations
  8. 7for each semijoin of P that reduces a relation at S_a: drop it if P without it costs less
  9. 8return P, then move every relation to S_a and join there

Lines L1 and L2 are the local work of the paper: selections at one site cost nothing and make every later estimate smaller. Lines L3 to L5 are the main loop. Line L6 chooses the assembly site so that the least data has to move, since the relations at that site stay where they are. Line L7 is the second enhancement of the paper: once the site is fixed, a semijoin that only shrinks a relation that will not move is useless, unless it helps a later semijoin. The test in line L7 replays the whole program with the estimates, so an indirect gain is kept.

The paper writes the loop of line L3 as "while some nonlocal semijoin has benefit > cost". The implementation uses each semijoin at most once. Without this rule, in a cyclic query the semijoins can keep lowering one another's estimates through Yao's function, with smaller and smaller gains, and the loop need not end. In the example below, no semijoin is chosen twice anyway.

Example

This is the example of Section 4.3 of the paper. Suppliers S(s#,sname,location)S(s\#, sname, location), shipments Y(s#,p#)Y(s\#, p\#) and parts P(p#,pname,type)P(p\#, pname, type) are at three different sites, and every attribute has width 1. The query asks for the suppliers in Massachusetts, the micro parts and their shipments: the local selections are location=MAlocation = MA and type=microtype = micro. The domains of s#s\# and p#p\# have 10,000 values, the domain of locationlocation has 50 values and the domain of typetype has 5. The paper prints 100,000 for the first two domains, but its numbers follow only from 10,000.

relation rows distinct values of the join attributes after the local selection
S 10,000 s#: 10,000 200 rows, s#: 200
Y 100,000 s#: 1,000, p#: 1,000 no change
P 10,000 p#: 10,000 2,000 rows, p#: 2,000

The four nonlocal semijoins start with these estimates:

semijoin cost benefit
S⋉s#YS \ltimes_{s\#} Y 1,000 180×3=540180 \times 3 = 540
P⋉p#YP \ltimes_{p\#} Y 1,000 1,800×3=5,4001{,}800 \times 3 = 5{,}400
Y⋉s#SY \ltimes_{s\#} S 200 98,000×2=196,00098{,}000 \times 2 = 196{,}000
Y⋉p#PY \ltimes_{p\#} P 2,000 80,000×2=160,00080{,}000 \times 2 = 160{,}000

OPT picks four semijoins in this order.

  1. Y⋉s#SY \ltimes_{s\#} S, cost 200. The selectivity of Y.s#Y.s\# becomes 0.1×0.020.1 \times 0.02, so Y.s#Y.s\# has 20 values and YY has 20×100,000/1,000=2,00020 \times 100{,}000/1{,}000 = 2{,}000 rows. Yao's function of 2,000 rows and 1,000 values gives 1,000, so Y.p#Y.p\# keeps 1,000 values.
  2. P⋉p#YP \ltimes_{p\#} Y, cost 1,000, benefit 5,400. PP drops to 200 rows.
  3. Y⋉p#PY \ltimes_{p\#} P, cost 200, benefit 3,200. YY drops to 400 rows.
  4. S⋉s#YS \ltimes_{s\#} Y, cost 20, benefit 540. SS drops to 20 rows.

Now no semijoin is profitable. The semijoins cost 200+1,000+200+20=1,420200 + 1{,}000 + 200 + 20 = 1{,}420. The estimated data is 60 at the site of SS, 800 at the site of YY and 600 at the site of PP, so line L6 picks the site of YY, and the move costs 60+600=66060 + 600 = 660, for a total of 2,080. Line L7 then drops the third semijoin: it shrinks YY, which does not move, and no later semijoin needs it. The final program costs 1,880, as in the paper. The tests of the implementation check every number in this section.

Correctness

Every semijoin program gives the exact answer, with the right count for every row. A row that takes part in the answer agrees on the semijoin attributes with a row of the other relation that also takes part, so a semijoin never drops it; the dropped rows have no partner and add nothing to the join. This holds for any data, whatever the estimates say. The cost of a plan, on the other hand, depends on the estimates, and nothing guarantees that OPT finds the cheapest plan. The proofs are on the proof page.

Proof: A semijoin program never changes the answer, OPT ends, and a tree query has a full reducerfull

We use the line numbers of the pseudocode on the page. The query is Q=R1⋈⋯⋈RrQ = R_1 \bowtie \dots \bowtie R_r under bag semantics, after the local selections of line L1. Attributes with the same name are joined, and a NULL in a join attribute matches nothing. A semijoin Ri⋉ARjR_i \ltimes_A R_j, for a set AA of attributes common to RiR_i and RjR_j, ships the set of non-null values Rj[A]R_j[A] and keeps the rows tt of RiR_i, with their counts, for which t[A]t[A] is in that set. A program is a sequence of semijoins, followed by the move of every relation to the assembly site and the join there.

There are two separate claims. The answer is always right, for any program (Theorem 1); this is a theorem about data. The program that OPT picks is cheap only in the estimated cost model; this part is a heuristic, and the page shows that it is not optimal even for its own estimates.

Rows that take part. A row tt of RiR_i takes part in QQ if some output tuple of QQ restricts to tt on the attributes of RiR_i. Write Rk′R'_k for the current state of RkR_k while a program runs.

Theorem 1. For every semijoin program, the join of the reduced relations equals QQ, with the same count for every output tuple.

Proof. We show by induction over the program that each Rk′R'_k is a sub-bag of RkR_k (each row keeps its count or drops out) that still holds every row of RkR_k that takes part in QQ. At the start Rk′=RkR'_k = R_k. Take a step Ri⋉ARjR_i \ltimes_A R_j and a row tt of Ri′R'_i that takes part, through an output tuple uu. Let ss be the restriction of uu to the attributes of RjR_j. Then ss is a row of RjR_j that takes part, so ss is in Rj′R'_j by the induction hypothesis. The attributes AA are join attributes, so t[A]=u[A]=s[A]t[A] = u[A] = s[A], and this value has no NULL, because a NULL matches nothing. So t[A]t[A] is among the shipped values and tt stays. The step only drops rows, so Ri′R'_i stays a sub-bag of RiR_i.

At the end, every output tuple of QQ is built from rows that take part, and all of them are still present with their full counts, so the join of the Rk′R'_k produces each output tuple of QQ at least as often as QQ does. It cannot produce more, because the Rk′R'_k are sub-bags of the RkR_k and the join is monotone in the counts. □\square

The theorem does not need the profile or the estimates. A wrong estimate can make a program expensive, never wrong.

The cost of a program on data. A semijoin between relations at different sites costs ∣Rj[A]∣⋅w(A)|R_j[A]| \cdot w(A), the number of distinct non-null values shipped times their width, and it costs 0 at one site. The move costs ∣Rk′∣⋅width(Rk)|R'_k| \cdot \mathrm{width}(R_k) for each relation not at the assembly site. These are the definitions that the implementation uses, and the tests check them against a count made with the reference relational operators.

Theorem 2 (termination). The main loop of lines L3 to L5 runs at most qq times, where qq is the number of nonlocal candidate semijoins, and the pruning of line L7 replays the program at most 2q2q times.

Proof. The implementation uses each candidate at most once, so the main loop picks at most qq semijoins and then finds no candidate. In line L7, each test either removes a semijoin from the program or moves on to the next position, and both can happen at most qq times. □\square

The rule "each candidate at most once" is a choice of this implementation. The paper states the loop as "while some nonlocal semijoin has benefit > cost". With the estimates of the paper, a semijoin on AA also lowers the estimate for the other attributes of RiR_i through Yao's function, and adds a new edge to their lineage. In a cyclic query, such as the triangle R(A,B)R(A, B), S(B,C)S(B, C), T(C,A)T(C, A), the three semijoins can then keep lowering one another's estimates, and the loop can go on with smaller and smaller gains. The bound removes this. On the example of the paper, no semijoin is picked twice, so the bound does not change the result.

Theorem 3 (the greedy rule and pruning). Each step of the main loop picks a candidate of the largest estimated profit, benefit minus cost, among the unused candidates, and only if that profit is positive. Each pruning step strictly lowers the estimated cost, with the assembly site fixed. So the cost of the returned plan is at most the cost before pruning.

Proof. Lines L3 and L4 take the maximum over all unused candidates of the current estimates, and the loop stops when the maximum is not positive. Line L7 removes a semijoin only when the replay without it costs strictly less, and it then uses that smaller cost as the new cost. □\square

The example of the paper shows that the plan of the main loop is not optimal for the estimated cost: OPT returns a plan of cost 2080, and pruning finds a plan of cost 1880. So the greedy rule is a heuristic; no bound on how far it is from the best program is known to us.

Full reducers. A program fully reduces the query if it leaves in each RkR_k exactly the rows that take part in QQ. A join tree of the query is a tree on the relations such that, for every attribute XX, the relations that hold XX form a connected subtree. A query is a tree query if it has a join tree.

Theorem 4 (Bernstein and Chiu). Root a join tree at a relation R0R_0. For each edge from a child cc to its parent pp, let AcA_c be the set of attributes common to cc and pp. The program that first does p⋉Accp \ltimes_{A_c} c for every child cc, children before parents, and then c⋉Acpc \ltimes_{A_c} p for every child cc, parents before children, fully reduces the query. It has 2(r−1)2(r - 1) semijoins.

Proof. By the property of a join tree, an attribute that occurs both inside the subtree TcT_c of cc and outside it occurs in cc and in pp, so it is in AcA_c.

Upward pass. We show that after it, each Rv′R'_v holds exactly the rows of RvR_v that take part in the join QvQ_v of the relations of the subtree TvT_v. For a leaf this holds with nothing done. For an inner node vv with children c1,…,cmc_1, \dots, c_m, the children are done first. A row tt of RvR_v stays if, for each child cc, some row scs_c of Rc′R'_c agrees with tt on AcA_c; by induction scs_c extends to an output tuple ucu_c of QcQ_c. Two different subtrees TcT_{c} and Tc′T_{c'} share only attributes of vv, by the property above, and on those every ucu_c agrees with tt. So tt and all the ucu_c fit together into one output tuple of QvQ_v. Conversely, a row of RvR_v that takes part in QvQ_v is never dropped, by the argument of Theorem 1 applied to QvQ_v.

Downward pass. After the upward pass the root holds exactly the rows that take part in Q=QR0Q = Q_{R_0}. Let pp be a parent that is already fully reduced, and cc a child. A row tt of Rc′R'_c stays if some row ss of Rp′R'_p agrees with it on AcA_c. The row ss takes part in QQ through an output tuple uu, and tt takes part in QcQ_c through an output tuple ucu_c. The only attributes that TcT_c shares with the rest of the tree are in AcA_c, where tt, ss, uu and ucu_c all agree. So ucu_c on TcT_c and uu on the rest fit together into an output tuple of QQ that holds tt. A row that takes part in QQ is never dropped, by Theorem 1. By induction from the root down, every relation ends fully reduced. □\square

The semijoins of Theorem 4 must use all of AcA_c, not one attribute of it. Theorem 4 also allows NULLs: a row with a NULL in an attribute of AcA_c takes part in nothing and is dropped, while a NULL in an attribute that no other relation holds does no harm.

Cyclic queries. For the triangle R(A,B)={(0,0),(1,1)}R(A, B) = \{(0, 0), (1, 1)\}, S(B,C)={(0,0),(1,1)}S(B, C) = \{(0, 0), (1, 1)\}, T(C,A)={(0,1),(1,0)}T(C, A) = \{(0, 1), (1, 0)\}, each semijoin between two of the relations keeps every row, because each relation has both values 00 and 11 in each of its attributes. So no semijoin program changes the relations, while QQ is empty: no program fully reduces this instance. Bernstein and Goodman showed that a query has a full reducer for every database exactly when it is a tree query. The tests check Theorem 1 on random chain, star and triangle queries with NULLs and duplicates, Theorem 4 on random tree queries, and the triangle above.

Complexity

  • Steps (theorem). The main loop picks at most qq semijoins, where qq is the number of candidates, and each pass of line L3 evaluates at most qq of them. Line L7 replays the program at most 2q2q times.
  • Time. One estimate takes time linear in the size of its reduction history, which has O(qe)O(q e) edges. So this implementation does O(q3e)O(q^3 e) arithmetic operations in the worst case, counted on the word RAM with an exact rational as one word. The paper states no bound, and a careful implementation can cache the selectivities.
  • Plan cost (measurement only). The data sent by the plan is an estimate. How close it is to the real cost depends on how far the data is from the uniform and independent model.

Properties

  • Exact answer, heuristic plan. The answer is exact for any program (a theorem); the choice of the program is a heuristic.
  • Greedy. OPT seeks the largest immediate gain, does not look ahead and does not go back, and the paper says that its plans are "in general, suboptimal". The example shows this even for the estimated cost: the plan of the main loop costs 2,080, and a plan with one semijoin less costs 1,880.
  • Transmission only. The cost counts data sent. In the networks of the time this was the dominant cost; on a fast local network, the local work and the number of messages can matter more.
  • Reduce, then join. The plan has two phases: semijoins between sites, then all joins at one site.

Variants and improvements

  • Moving expensive semijoins later. The first enhancement of the paper permutes the semijoins of the program, in decreasing order of cost, so that an expensive semijoin runs after the cheaper ones that shrink the data it sends.
  • Full reducers. For a tree query, the program of Bernstein and Chiu (1981) does a semijoin up each edge of a join tree and then down each edge, 2(r−1)2(r - 1) semijoins in all, and leaves in every relation exactly the rows that take part in the answer. Bernstein and Goodman (1981) showed that cyclic queries have no full reducer in general. The Yannakakis algorithm uses the same passes for acyclic join evaluation on one site.
  • Bloom joins. A Bloom join sends a Bloom filter of the join values instead of the values. It costs a fixed number of bits and lets a few rows through by error.
  • Joins between sites. The paper suggests plans that alternate semijoins with joins at several sites, since a join can make new semijoins profitable. Later optimizers, such as the methods in the textbook of Özsu and Valduriez, search over join orders and sites with a cost model instead.

When to use it

Use semijoin reduction when the network is slow compared with local work, the join is selective, and the join columns are narrow compared with the rows. It helps most when a relation is large and only a few of its rows join, as with the shipments in the example. When most rows join, a semijoin costs data and drops almost nothing; then move the relations directly, or use a parallel hash join on a fast cluster.

Pitfalls

  • Trusting the estimates. The benefit comes from a uniform and independent model. Correlated columns or skewed values can make a semijoin that looks profitable drop nothing.
  • Counting one reduction twice. Two sets of values that come from the same earlier reduction are not independent. Multiplying their selectivities as if they were gives too small an estimate. The reduction history of the paper exists to avoid this.
  • Single attributes on a tree query. A full reducer must use all the common attributes of the two relations at once. Two semijoins on one attribute each can keep a row that a semijoin on both attributes drops.
  • Cyclic queries. No semijoin program can remove the dangling rows of some cyclic queries: in the triangle R(A,B)R(A, B), S(B,C)S(B, C), T(C,A)T(C, A) with R=S={(0,0),(1,1)}R = S = \{(0, 0), (1, 1)\} and T={(0,1),(1,0)}T = \{(0, 1), (1, 0)\}, no semijoin drops a row, but the join is empty.
  • NULLs. A NULL join value must not be sent as a value, since it matches nothing. Rows with a NULL join value are dropped by any semijoin on that attribute.

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)
sdd1_semijoin_optimization.py 349 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sdd1-semijoin-optimization/. The authors are listed in prov/ER70WT.jsonl.

"""Algorithm OPT of SDD-1: a greedy choice of semijoins before the relations move to one site.

The query is the natural join of some relations, each stored at one site, after
local selections. Attributes with the same name are joined, and each attribute
name has one domain with a size c(X) and a width w(X).

The database profile holds c(R) for each relation and c(R.A), the number of
distinct values of R.A. The estimates follow Bernstein et al. (1981):

* R[A] is a random subset of its domain. Each set of values is described by its
  lineage, a set of selection edges with labels in (0, 1]; its selectivity is the
  product of the labels, and its estimated size is the selectivity times c(X).
  At the start R[A] has one edge with label c(R.A) / c(X).
* The semijoin R_i <A] R_j maps R_i[A] to R_i[A] & R_j[A]; the new lineage is the
  union of the two lineages. The new c(R_i) is c(R_i.A)new * c(R_i) / c(R_i.A)old,
  since the tuples are spread evenly over the values. For every other attribute
  A' of R_i, c(R_i.A') becomes the piecewise form of Yao's function of the new
  c(R_i) and the old c(R_i.A'), and R_i[A'] gets an edge with the ratio new/old.
* The cost of R_i <A] R_j is c(R_j.A) * w(A), or 0 at the same site. The benefit
  is (c(R_i) before - c(R_i) after) * width(R_i).

OPT appends the most profitable nonlocal semijoin while one has benefit > cost
(each semijoin at most once: in a cyclic query the estimates can otherwise shrink
forever through Yao's function, so the loop would not end),
chooses the assembly site with the largest estimated data, and then prunes
semijoins that reduce a relation at the assembly site when the program costs
less without them. The cost counts transmitted data only; local work and the
number of messages are free.
"""

from __future__ import annotations

from collections import Counter
from dataclasses import dataclass, field
from fractions import Fraction
from collections.abc import Callable, Mapping, Sequence


def yao_approx(n, b):
    """The piecewise approximation of Yao's function: the expected number of distinct
    values left when n of the tuples are kept, for b distinct values before."""
    if n < Fraction(b) / 2:
        return Fraction(n)
    if n < 2 * b:
        return Fraction(n + b) / 3
    return Fraction(b)


# ---------------------------------------------------------------- the profile and its estimates


@dataclass
class Profile:
    domains: dict            # attribute -> (c(X), w(X)); c(X) may be None for an attribute no clause uses
    sites: dict              # relation -> site
    card: dict               # relation -> c(R)
    distinct: dict           # relation -> {attribute: c(R.A)} for the attributes with a known count
    schema: dict             # relation -> all attributes of the query in R (they make up its width)

    def width(self, r: str) -> int:
        return sum(self.domains[a][1] for a in self.schema[r])


@dataclass
class Estimate:
    """The changing estimates while a program is replayed."""
    profile: Profile
    card: dict = field(default_factory=dict)
    distinct: dict = field(default_factory=dict)
    lineage: dict = field(default_factory=dict)   # (relation, attribute) -> frozenset of edge ids
    labels: list = field(default_factory=list)    # edge id -> label

    @classmethod
    def start(cls, p: Profile) -> "Estimate":
        e = cls(p)
        for r in p.card:
            e.card[r] = Fraction(p.card[r])
            e.distinct[r] = {}
            for a, c in p.distinct[r].items():
                e.distinct[r][a] = Fraction(c)
                e.lineage[r, a] = frozenset([e._edge(Fraction(c, p.domains[a][0]))])
        return e

    def _edge(self, label: Fraction) -> int:
        self.labels.append(Fraction(label))
        return len(self.labels) - 1

    def selectivity(self, lin: frozenset) -> Fraction:
        out = Fraction(1)
        for k in lin:
            out *= self.labels[k]
        return out

    def _shrink_others(self, r: str, a: str, old_card: Fraction) -> None:
        for b in self.distinct[r]:
            if b == a:
                continue
            old = self.distinct[r][b]
            new = yao_approx(self.card[r], old)
            if old and new < old:
                self.lineage[r, b] = self.lineage[r, b] | {self._edge(new / old)}
            self.distinct[r][b] = new

    def select(self, r: str, a: str, factor) -> None:
        """A local selection on r.A that keeps the fraction factor of the values of r.A."""
        factor = Fraction(factor)
        old_card, old = self.card[r], self.distinct[r][a]
        self.lineage[r, a] = self.lineage[r, a] | {self._edge(factor)}
        self.distinct[r][a] = old * factor
        self.card[r] = old_card * factor
        self._shrink_others(r, a, old_card)

    def effect(self, i: str, j: str, a: str) -> tuple[Fraction, Fraction, frozenset]:
        """(new c(R_i), new c(R_i.A), new lineage) of R_i <A] R_j, without applying it."""
        lin = self.lineage[i, a] | self.lineage[j, a]
        new_a = self.selectivity(lin) * self.profile.domains[a][0]
        old_a = self.distinct[i][a]
        new_card = new_a * self.card[i] / old_a if old_a else Fraction(0)
        return new_card, new_a, lin

    def cost(self, i: str, j: str, a: str) -> Fraction:
        if self.profile.sites[i] == self.profile.sites[j]:
            return Fraction(0)
        return self.distinct[j][a] * self.profile.domains[a][1]

    def benefit(self, i: str, j: str, a: str) -> Fraction:
        new_card, _, _ = self.effect(i, j, a)
        return (self.card[i] - new_card) * self.profile.width(i)

    def semijoin(self, i: str, j: str, a: str) -> None:
        new_card, new_a, lin = self.effect(i, j, a)
        old_card = self.card[i]
        self.lineage[i, a] = lin
        self.distinct[i][a] = new_a
        self.card[i] = new_card
        self._shrink_others(i, a, old_card)

    def size(self, r: str) -> Fraction:
        return self.card[r] * self.profile.width(r)


def candidates(p: Profile) -> list[tuple[str, str, str]]:
    """Every nonlocal semijoin R_i <A] R_j of the query: i != j at different sites, A common."""
    out = []
    for i in sorted(p.card):
        for j in sorted(p.card):
            if i != j and p.sites[i] != p.sites[j]:
                for a in sorted(set(p.distinct[i]) & set(p.distinct[j])):
                    out.append((i, j, a))
    return out


def choose_site(est: Estimate) -> object:
    """The site with the largest estimated data of the query (the first one on a tie)."""
    size: Counter = Counter()
    for r in sorted(est.card):
        size[est.profile.sites[r]] += est.size(r)
    return max(sorted(size, key=repr), key=lambda s: size[s])


def replay(p: Profile, program: Sequence[tuple], assembly=None) -> tuple[Fraction, Fraction, object, Estimate]:
    """Replay a program through the estimates. Return (cost of the semijoins, cost of moving
    the reduced relations to the assembly site, the assembly site, the final estimates)."""
    est = Estimate.start(p)
    sj_cost = Fraction(0)
    for op in program:
        if op[0] == "select":
            est.select(op[1], op[2], op[3])
        else:
            _, i, j, a = op
            sj_cost += est.cost(i, j, a)
            est.semijoin(i, j, a)
    site = choose_site(est) if assembly is None else assembly
    move = sum((est.size(r) for r in sorted(p.card) if p.sites[r] != site), Fraction(0))
    return sj_cost, move, site, est


@dataclass
class Plan:
    program: list                 # local selections, then semijoins ("semijoin", i, j, A)
    assembly: object
    cost: Fraction                # estimated cost after pruning
    cost_before_pruning: Fraction
    trace: list                   # per step: (chosen semijoin, cost, benefit)
    pruned: list


def opt(p: Profile, selections: Sequence[tuple] = (), prune: bool = True, max_steps: int = 1000) -> Plan:
    """Algorithm OPT. selections are (relation, attribute, factor) local selections."""
    est = Estimate.start(p)
    program = []
    for r, a, f in selections:  # @line L1
        est.select(r, a, f)
        program.append(("select", r, a, Fraction(f)))  # @line L2
    cands = candidates(p)
    used = set()
    trace = []
    for _ in range(max_steps):
        best = None
        for sj in cands:  # @line L3
            if sj in used:
                continue
            profit = est.benefit(*sj) - est.cost(*sj)
            if profit > 0 and (best is None or profit > best[0]):
                best = (profit, sj)  # @line L4
        if best is None:
            break
        sj = best[1]
        used.add(sj)
        trace.append((sj, est.cost(*sj), est.benefit(*sj)))
        program.append(("semijoin",) + sj)  # @line L5
        est.semijoin(*sj)
    site = choose_site(est)  # @line L6
    sj_cost, move, _, _ = replay(p, program, site)
    before = sj_cost + move
    pruned = []
    if prune:
        k = 0
        while k < len(program):  # @line L7
            op = program[k]
            if op[0] == "semijoin" and p.sites[op[1]] == site:
                without = program[:k] + program[k + 1:]
                c, m, _, _ = replay(p, without, site)
                if c + m < sj_cost + move:
                    pruned.append(op)
                    program, sj_cost, move = without, c, m
                    continue
            k += 1
    return Plan(program, site, sj_cost + move, before, trace, pruned)  # @line L8


# ---------------------------------------------------------------- execution on data


@dataclass
class Table:
    schema: tuple
    rows: Counter                  # tuple -> count (bag semantics)

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


def _cols(t: Table, a) -> list[int]:
    return [t.col(x) for x in ((a,) if isinstance(a, str) else a)]


def semijoin_values(t: Table, a) -> set:
    """The distinct non-null values of t.A (A is one attribute or a tuple of them), which
    is what a semijoin ships."""
    ks = _cols(t, a)
    vals = {tuple(row[k] for k in ks) for row in t.rows}
    return {v for v in vals if None not in v}


def reduce_by(t: Table, a, values: set) -> Table:
    ks = _cols(t, a)
    return Table(t.schema, Counter({row: c for row, c in t.rows.items() if tuple(row[k] for k in ks) in values}))


def _width(widths: Mapping[str, int], a) -> int:
    return sum(widths[x] for x in ((a,) if isinstance(a, str) else a))


def hash_join(r: Table, s: Table) -> Table:
    common = [a for a in r.schema if a in s.schema]
    rest = [a for a in s.schema if a not in common]
    rk = [r.col(a) for a in common]
    sk = [s.col(a) for a in common]
    sr = [s.col(a) for a in rest]
    table: dict = {}
    for row, c in s.rows.items():
        key = tuple(row[k] for k in sk)
        if None not in key:
            table.setdefault(key, []).append((row, c))
    out: Counter = Counter()
    for row, c in r.rows.items():
        key = tuple(row[k] for k in rk)
        for srow, d in table.get(key, ()):
            out[row + tuple(srow[k] for k in sr)] += c * d
    return Table(r.schema + tuple(rest), out)


@dataclass
class Run:
    result: Table
    semijoin_bytes: int
    move_bytes: int
    reduced: dict


def execute(tables: Mapping[str, Table], sites: Mapping[str, object], widths: Mapping[str, int],
            program: Sequence[tuple], assembly, predicates: Mapping[str, Callable] | None = None) -> Run:
    """Run a program on data. A ("select", R, ...) step applies predicates[R]. A semijoin
    ships the distinct values of R_j.A (if the sites differ) and keeps the rows of R_i
    whose A is among them. Then all relations move to the assembly site and are joined."""
    cur = dict(tables)
    sj_bytes = 0
    for op in program:
        if op[0] == "select":
            r = op[1]
            pred = (predicates or {}).get(r)
            if pred is not None:
                t = cur[r]
                cur[r] = Table(t.schema, Counter({row: c for row, c in t.rows.items()
                                                   if pred(dict(zip(t.schema, row))) is True}))
        else:
            _, i, j, a = op
            vals = semijoin_values(cur[j], a)
            if sites[i] != sites[j]:
                sj_bytes += len(vals) * _width(widths, a)
            cur[i] = reduce_by(cur[i], a, vals)
    move = 0
    for r in sorted(cur):
        if sites[r] != assembly:
            move += sum(cur[r].rows.values()) * sum(widths[a] for a in cur[r].schema)
    names = sorted(cur)
    result = cur[names[0]]
    for r in names[1:]:
        result = hash_join(result, cur[r])
    return Run(result, sj_bytes, move, cur)


def full_reducer(parent: Mapping[str, str | None], schemas: Mapping[str, Sequence[str]]) -> list[tuple]:
    """The semijoin program of Bernstein and Chiu for a tree query given as a rooted join
    tree (parent[root] is None): semijoins from the leaves up, then from the root down.
    Each semijoin uses all the attributes that the two relations have in common."""
    children: dict = {r: [] for r in parent}
    root = None
    for r in sorted(parent):
        if parent[r] is None:
            root = r
        else:
            children[parent[r]].append(r)
    order = []

    def walk(r):
        order.append(r)
        for c in children[r]:
            walk(c)

    walk(root)
    common = lambda r: tuple(sorted(set(schemas[r]) & set(schemas[parent[r]])))
    up = [("semijoin", parent[r], r, common(r)) for r in reversed(order) if parent[r] is not None]
    down = [("semijoin", r, parent[r], common(r)) for r in order if parent[r] is not None]
    return up + down
test_sdd1_semijoin_optimization.py 229 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sdd1-semijoin-optimization/. The authors are listed in prov/ER70WT.jsonl.

import random
from collections import Counter
from fractions import Fraction as F

import pytest

import dbrel
from sdd1_semijoin_optimization import (Estimate, Profile, Table, candidates, execute, full_reducer, opt,
                                        reduce_by, replay, semijoin_values, yao_approx)


def paper_profile():
    """Section 4.3 of Bernstein et al. (1981), with 10,000 values in the domains of s# and p#."""
    domains = {"s#": (10000, 1), "p#": (10000, 1), "location": (50, 1), "type": (5, 1),
               "sname": (None, 1), "pname": (None, 1)}
    return Profile(
        domains=domains,
        sites={"S": 1, "Y": 2, "P": 3},
        card={"S": 10000, "Y": 100000, "P": 10000},
        distinct={"S": {"s#": 10000, "location": 50}, "Y": {"s#": 1000, "p#": 1000},
                  "P": {"p#": 10000, "type": 5}},
        schema={"S": ("s#", "sname", "location"), "Y": ("s#", "p#"), "P": ("p#", "pname", "type")},
    )


PAPER_SELECTIONS = [("S", "location", F(1, 50)), ("P", "type", F(1, 5))]


def test_paper_first_table():
    est = Estimate.start(paper_profile())
    for r, a, f in PAPER_SELECTIONS:
        est.select(r, a, f)
    assert est.card == {"S": 200, "Y": 100000, "P": 2000}
    table = {sj: (est.cost(*sj), est.benefit(*sj)) for sj in candidates(est.profile)}
    assert table == {
        ("S", "Y", "s#"): (1000, 180 * 3),
        ("P", "Y", "p#"): (1000, 1800 * 3),
        ("Y", "S", "s#"): (200, 98000 * 2),
        ("Y", "P", "p#"): (2000, 80000 * 2),
    }


def test_paper_example():
    plan = opt(paper_profile(), PAPER_SELECTIONS, prune=False)
    assert [(sj, c) for sj, c, _ in plan.trace] == [
        (("Y", "S", "s#"), 200), (("P", "Y", "p#"), 1000), (("Y", "P", "p#"), 200), (("S", "Y", "s#"), 20)]
    assert [b for _, _, b in plan.trace] == [196000, 5400, 3200, 540]
    assert plan.assembly == 2
    sj_cost, move, site, est = replay(paper_profile(), plan.program)
    assert (sj_cost, move, site) == (1420, 660, 2)
    assert est.card == {"S": 20, "Y": 400, "P": 200}
    assert plan.cost == 2080


def test_paper_example_pruned():
    plan = opt(paper_profile(), PAPER_SELECTIONS)
    assert plan.cost_before_pruning == 2080 and plan.cost == 1880
    assert plan.pruned == [("semijoin", "Y", "P", "p#")]
    assert [op[1:] for op in plan.program if op[0] == "semijoin"] == [
        ("Y", "S", "s#"), ("P", "Y", "p#"), ("S", "Y", "s#")]


def test_yao_approx_pieces():
    assert yao_approx(10, 100) == 10
    assert yao_approx(50, 100) == 50
    assert yao_approx(200, 100) == 100
    assert yao_approx(F(140), 100) == 80
    for b in (3, 10, 40):
        for n in range(0, 5 * b):
            v = yao_approx(n, b)
            assert v <= b and v <= max(n, F(b + n) / 3)


def random_query(rng):
    """A chain, a star or a triangle of 3 or 4 relations at random sites, with random rows."""
    shape = rng.choice(["chain", "star", "triangle"])
    if shape == "chain":
        n = rng.randint(2, 4)
        schemas = {f"R{i}": (f"A{i}", f"A{i + 1}") for i in range(n)}
    elif shape == "star":
        schemas = {"R0": ("A0", "A1", "A2"), "R1": ("A0", "B1"), "R2": ("A1", "B2"), "R3": ("A2", "B3")}
    else:
        schemas = {"R0": ("A", "B"), "R1": ("B", "C"), "R2": ("C", "A")}
    rels = {r: dbrel.random_relation(rng, s, rng.randint(0, 8), domain=3, null_rate=0.1) for r, s in schemas.items()}
    sites = {r: rng.randint(0, 2) for r in schemas}
    return schemas, rels, sites


def to_table(rel):
    return Table(rel.schema, Counter(rel.rows))


def to_rel(t):
    return dbrel.Relation(t.schema, t.rows)


def join_all(rels):
    names = sorted(rels)
    out = rels[names[0]]
    for r in names[1:]:
        out = dbrel.natural_join(out, rels[r])
    return out


def profile_of(rels, sites, widths):
    attrs = sorted({a for r in rels.values() for a in r.schema})
    domains = {a: (3, widths[a]) for a in attrs}
    distinct = {}
    for name, r in rels.items():
        distinct[name] = {a: max(1, len({t[r.index(a)] for t in r.rows if t[r.index(a)] is not None}))
                          for a in r.schema}
    return Profile(domains, dict(sites), {n: max(1, len(r)) for n, r in rels.items()}, distinct,
                   {n: r.schema for n, r in rels.items()})


@pytest.mark.parametrize("seed", range(60))
def test_opt_program_gives_the_join(seed):
    rng = random.Random(seed)
    schemas, rels, sites = random_query(rng)
    widths = {a: rng.randint(1, 3) for s in schemas.values() for a in s}
    plan = opt(profile_of(rels, sites, widths))
    run = execute({r: to_table(v) for r, v in rels.items()}, sites, widths, plan.program, plan.assembly)
    assert to_rel(run.result) == join_all(rels)


@pytest.mark.parametrize("seed", range(60))
def test_any_semijoin_program_keeps_the_join_and_counts_bytes(seed):
    rng = random.Random(1000 + seed)
    schemas, rels, sites = random_query(rng)
    widths = {a: rng.randint(1, 3) for s in schemas.values() for a in s}
    names = sorted(schemas)
    program = []
    for _ in range(rng.randint(0, 6)):
        i, j = rng.sample(names, 2)
        common = sorted(set(schemas[i]) & set(schemas[j]))
        if common:
            program.append(("semijoin", i, j, rng.choice(common)))
    run = execute({r: to_table(v) for r, v in rels.items()}, sites, widths, program, assembly=0)
    assert to_rel(run.result) == join_all(rels)
    # The same program by the reference operators, with its cost counted from the definition.
    cur = dict(rels)
    sj = 0
    for _, i, j, a in program:
        proj = dbrel.distinct(dbrel.select(dbrel.project(cur[j], [a]), lambda row: row[a] is not None))
        if sites[i] != sites[j]:
            sj += len(proj) * widths[a]
        cur[i] = dbrel.semijoin(cur[i], proj)
    assert run.semijoin_bytes == sj
    assert {r: to_rel(t) for r, t in run.reduced.items()} == cur
    assert run.move_bytes == sum(len(cur[r]) * sum(widths[a] for a in schemas[r]) for r in names if sites[r] != 0)


@pytest.mark.parametrize("seed", range(40))
def test_greedy_choice_and_stop(seed):
    rng = random.Random(2000 + seed)
    schemas, rels, sites = random_query(rng)
    widths = {a: rng.randint(1, 3) for s in schemas.values() for a in s}
    p = profile_of(rels, sites, widths)
    plan = opt(p, prune=False)
    est = Estimate.start(p)
    used = set()
    assert len(plan.trace) <= len(candidates(p))
    for sj, cost, benefit in plan.trace:
        profits = [est.benefit(*c) - est.cost(*c) for c in candidates(p) if c not in used]
        assert benefit - cost == max(profits) > 0
        assert (cost, benefit) == (est.cost(*sj), est.benefit(*sj))
        est.semijoin(*sj)
        used.add(sj)
    assert all(est.benefit(*c) <= est.cost(*c) for c in candidates(p) if c not in used)
    pruned = opt(p)
    assert pruned.cost <= plan.cost
    assert all(p.sites[op[1]] == pruned.assembly for op in pruned.pruned)


def fully_reduced(rels, reduced):
    """Each relation keeps exactly its rows that take part in the join: the rows that meet
    the full join on the attributes the relation shares with the others (a null in an
    attribute of its own does not stop a row from joining)."""
    full = join_all(rels)
    for r in rels:
        shared = [a for a in rels[r].schema if any(a in rels[s].schema for s in rels if s != r)]
        if reduced[r] != dbrel.semijoin(rels[r], dbrel.project(full, shared)):
            return False
    return True


@pytest.mark.parametrize("seed", range(40))
def test_full_reducer_for_tree_queries(seed):
    rng = random.Random(3000 + seed)
    if seed % 2:
        schemas = {"R0": ("A", "B"), "R1": ("B", "C"), "R2": ("C", "D"), "R3": ("C", "E")}
        parent = {"R0": None, "R1": "R0", "R2": "R1", "R3": "R1"}
    else:
        schemas = {"R0": ("A", "B", "C"), "R1": ("B", "C", "D"), "R2": ("D", "E")}
        parent = {"R1": None, "R0": "R1", "R2": "R1"}
    rels = {r: dbrel.random_relation(rng, s, rng.randint(1, 9), domain=3, null_rate=0.05) for r, s in schemas.items()}
    program = full_reducer(parent, schemas)
    assert len(program) == 2 * (len(schemas) - 1)
    run = execute({r: to_table(v) for r, v in rels.items()}, {r: r for r in rels}, {a: 1 for s in schemas.values() for a in s},
                  program, assembly="R0")
    assert fully_reduced(rels, {r: to_rel(t) for r, t in run.reduced.items()})


def test_cyclic_query_has_no_full_reducer_here():
    rels = {"R": dbrel.Relation(("A", "B"), [(0, 0), (1, 1)]),
            "S": dbrel.Relation(("B", "C"), [(0, 0), (1, 1)]),
            "T": dbrel.Relation(("C", "A"), [(0, 1), (1, 0)])}
    assert len(join_all(rels)) == 0
    tables = {r: to_table(v) for r, v in rels.items()}
    for i in rels:
        for j in rels:
            for a in set(rels[i].schema) & set(rels[j].schema):
                if i != j:
                    assert reduce_by(tables[i], a, semijoin_values(tables[j], a)).rows == tables[i].rows
    assert not fully_reduced(rels, rels)


def test_local_selection_and_same_site():
    p = Profile({"A": (10, 1), "B": (10, 2)}, {"R": 0, "S": 0}, {"R": 10, "S": 10},
                {"R": {"A": 10, "B": 10}, "S": {"B": 5}}, {"R": ("A", "B"), "S": ("B",)})
    assert candidates(p) == []  # both relations at one site: no nonlocal semijoin
    plan = opt(p, [("R", "A", F(1, 2))])
    assert plan.program == [("select", "R", "A", F(1, 2))] and plan.cost == 0
    rel = Table(("A", "B"), Counter({(1, 1): 2, (2, None): 1}))
    run = execute({"R": rel}, {"R": 0}, {"A": 1, "B": 1}, [("select", "R")], 0, {"R": lambda row: row["A"] == 1})
    assert run.result.rows == Counter({(1, 1): 2})

History

SDD-1, a System for Distributed Databases, was developed at Computer Corporation of America, and an overview of the system appeared in ACM Transactions on Database Systems in 1980. Bernstein, Goodman, Wong, Reeve and Rothnie described its query processor in 1981. They made the semijoin the main tool of distributed query processing, and they gave the profile model of estimates that later work used. In the same year Bernstein and Chiu studied which queries semijoins can solve and gave the full reducer of a tree query, and Bernstein and Goodman showed the limits of semijoins on cyclic queries. Yannakakis (1981) used the same passes to evaluate acyclic joins in time linear in the input and the output.

References

  1. Philip A. Bernstein, Nathan Goodman, Eugene Wong, Christopher L. Reeve and James B. Rothnie Jr., Query processing in a system for distributed databases (SDD-1), ACM Transactions on Database Systems 6(4), 1981, pages 602 to 625, Section 3 (the database profile, the selectivity of a set of values, the estimated effect of a semijoin with the piecewise Yao function, and the cost and benefit of a semijoin), Section 4.1 (Algorithm OPT), Section 4.2 (the two enhancements) and Section 4.3 (the worked example with S, Y and P)
  2. Philip A. Bernstein and Dah-Ming W. Chiu, Using semi-joins to solve relational queries, Journal of the ACM 28(1), 1981, pages 25 to 40, the full reducer of a tree query
  3. Philip A. Bernstein and Nathan Goodman, Power of natural semijoins, SIAM Journal on Computing 10(4), 1981, pages 751 to 771, the result that cyclic queries have no full reducer
  4. M. Tamer Özsu and Patrick Valduriez, Principles of Distributed Database Systems, fourth edition, Springer, 2020, Chapter 4, Distributed Query Processing, the part on semijoin based algorithms

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