Algorithm Search⌘K

Algorithmcore

Sort-based aggregation

Also called sort aggregate, stream aggregate.

Sort the rows on the grouping key with an external merge sort, and combine rows of equal key into one partial state while the runs are formed and merged.

Time
O(n log n) worst · best
Space
Θ(B p) extra
Counts
io 2 N P - N worst · averageio N best
Where
B = the number of buffer pages; N = the number of input pages; P = the number of passes; d = the number of groups; n = the number of input rows; p = the number of records per page
Properties
deterministicexactexternalnot in placeofflineiterative
Origin
Dina Bitton, David J. DeWitt, 1983

Sort-based aggregation solves the group-by aggregation problem with an external merge sort on the grouping key. When two records with the same key meet, in the sort of one run or in a merge of runs, they are replaced by one record that holds a partial state of the aggregates, such as (SUM,COUNT)(\text{SUM}, \text{COUNT}) for AVG. This early aggregation keeps each sorted run no longer than the number of groups, so the sort costs less when there are few groups. Unlike hash aggregation, it gives the groups in key order, and it is the plan of choice when the input already comes sorted on the key.

In plain words

You count votes on paper ballots. You take a pile that fits on your desk, sort it by candidate, and write one slip per candidate with that candidate's count. You put the slips on a shelf and take the next pile. Then you take a few stacks of slips at a time, which are all sorted by name, and go through them together. When two slips have the same name, you add them into one slip. You do this until one stack is left. Each slip in it gives one candidate and the final count, in name order. If there are only a few candidates, the stacks of slips stay small, and the work after the first piles is fast.

The problem

The input is a file RR of NN pages with pp records per page, the grouping columns GG, and aggregates f1,…,fqf_1, \ldots, f_q on columns A1,…,AqA_1, \ldots, A_q. Each aggregate is given by three functions: INIT(v)\text{INIT}(v) makes a state from one value, MERGE(s,s′)\text{MERGE}(s, s') joins two states, and FINAL(s)\text{FINAL}(s) gives the answer. MERGE is associative and commutative, and the state of a multiset X⊎YX \uplus Y is MERGE of the states of XX and YY. This holds for the distributive aggregates (COUNT, SUM, MIN, MAX) and for the algebraic ones (AVG with the state (SUM,COUNT)(\text{SUM}, \text{COUNT})), two of the classes of aggregates that come with the data cube. The output is one row per group, γG; f1(A1),…,fq(Aq)(R)\gamma_{G;\, f_1(A_1), \ldots, f_q(A_q)}(R), sorted on GG.

The memory holds B≥3B \ge 3 pages. In the external memory model, the memory holds M/B blocks; this is the number of buffer pages B of this page. The cost is the number of page reads and page writes. The final output is not counted, because a parent operator can use it as it comes.

The algorithm

Each record is a pair (key, state). A run is a file of records sorted on the key.

  1. SORT-AGGREGATE(R, B) ▷ R has N pages
  2. 1runs ← an empty list
  3. 2for each group of B consecutive pages of R do
  4. 3X ← the records of the group as (key, INIT) pairs, sorted on the key
  5. 4if N ≤ B then return FINAL of each record of COMBINE(X) ▷ one pass, nothing is written
  6. 5if early then X ← COMBINE(X) ▷ early aggregation in pass 0
  7. 6write X as a new run; append it to runs
  8. 7while |runs| > B - 1 do
  9. 8new ← an empty list
  10. 9for each group of B - 1 consecutive runs do
  11. 10X ← the merge of the runs of the group on the key
  12. 11if early then X ← COMBINE(X); write X as a new run, append it to new, and free the group
  13. 12runs ← new
  14. 13return FINAL of each record of COMBINE(the merge of runs) ▷ the output is not written
  15. COMBINE(X) ▷ X is sorted on the key
  16. 14for each record (k, s) of X in order do
  17. 15if c exists and the key of c is k then
  18. 16c ← (k, MERGE(state of c, s))
  19. 17else output c if it exists; c ← (k, s)
  20. 18output c if it exists

A merge (lines L10 and L13) reads one page of each run at a time, so it uses B−1B - 1 input buffers and one output buffer, and it picks the smallest key with a k-way merge. COMBINE needs only the current record, so it does not use more memory. Without early aggregation, lines L5 and L11 write the records as they are, and the passes are those of a plain external merge sort.

Example

Take B=3B = 3 and p=2p = 2, and compute COUNT(*) and SUM(v) per key over 16 rows in N=8N = 8 pages: (d, 4), (b, 2), (a, 5), (c, 1), (b, 7), (a, 3), (d, 6), (c, null), (a, 2), (e, 8), (b, 1), (a, 4), (e, 3), (c, 5), (d, 2), (b, 6). A state is (count, sum), and the sum of no non-null value is null.

step input records written pages
pass 0, run 1 rows 1 to 6 a (2, 8), b (2, 9), c (1, 1), d (1, 4) 2
pass 0, run 2 rows 7 to 12 a (2, 6), b (1, 1), c (1, null), d (1, 6), e (1, 8) 3
pass 0, run 3 rows 13 to 16 b (1, 6), c (1, 5), d (1, 2), e (1, 3) 2
pass 1, merge runs 1 and 2 5 pages a (4, 14), b (3, 10), c (2, 1), d (2, 10), e (1, 8) 3
pass 1, run 3 alone 2 pages the same 4 records 2
pass 2, final merge 5 pages not written -

The output is a (4, 14), b (4, 16), c (3, 6), d (3, 12), e (2, 11). Pass 0 reads 8 pages and writes 7, pass 1 reads 7 and writes 5, and the final merge reads 5: 20 reads and 12 writes, 32 I/Os. Without early aggregation, the runs of pass 0 have 3, 3 and 2 pages, pass 1 makes runs of 6 and 2 pages, and the cost is 24 reads and 16 writes, 40 I/Os, which is 2NP−N2 N P - N with P=3P = 3.

Correctness

COMBINE gets a sequence sorted on the key, so all records of one key are adjacent. It keeps one current record cc and merges into it each next record with the same key, so it outputs one record per key, in key order, whose state is the MERGE of the states of all records of that key. Let σ(Rk)\sigma(R_k) be the MERGE of the INIT states of all rows with key kk. The invariant is that, after each pass, every run is sorted on the key, and for each key kk the MERGE of the states of all its records in all runs is σ(Rk)\sigma(R_k). Pass 0 makes this true, since each row gives one record and COMBINE keeps the MERGE. A merge keeps the order and the records, and COMBINE keeps the MERGE again, by associativity and commutativity. The loop of line L7 ends, because ⌈r/(B−1)⌉<r\lceil r/(B-1) \rceil < r for r>B−1≥2r > B - 1 \ge 2 runs. The last COMBINE then sees all records of key kk adjacent and outputs FINAL(σ(Rk))\text{FINAL}(\sigma(R_k)) once. The full proof is in the proof file.

Proof: Sort-based aggregation outputs each group once, in key order, with its correct aggregatesfull

We assume that MERGE is associative and commutative, and that state(X⊎Y)=MERGE(state(X),state(Y))\text{state}(X \uplus Y) = \text{MERGE}(\text{state}(X), \text{state}(Y)) for non-empty multisets XX and YY, where state({ ⁣{v} ⁣})=INIT(v)\text{state}(\{\!\{v\}\!\}) = \text{INIT}(v). A record is a pair (key, state). For a multiset SS of records and a key kk, write SkS_k for the records of SS with key kk, and σ(Sk)\sigma(S_k) for the MERGE of their states, in any order. By the assumptions, σ(Sk)\sigma(S_k) does not depend on the order, and σ((S⊎T)k)=MERGE(σ(Sk),σ(Tk))\sigma((S \uplus T)_k) = \text{MERGE}(\sigma(S_k), \sigma(T_k)) when both parts are non-empty. Let RR also denote the multiset of level-0 records, one per input row, with key the values of GG and state INIT of the aggregated values. The target answer for key kk is FINAL(σ(Rk))\text{FINAL}(\sigma(R_k)).

Lemma (COMBINE). Let XX be a sequence of records sorted on the key. Lines L14 to L18 output one record (k,σ(Xk))(k, \sigma(X_k)) for each key kk of XX, in the order of the keys, and nothing else.

Proof. Since XX is sorted, the records of each key kk form one block of consecutive positions. Invariant of line L14: if some records were read, cc exists, its key is the key kk of the last record read, and its state is σ\sigma of the records of kk read so far; each key read before kk was output once with σ\sigma of its whole block; no other record was output. At the first record, line L17 sets cc to it, which keeps the invariant. At a next record (k′,s)(k', s): if k′=kk' = k, line L16 sets the state of cc to MERGE of the old state and ss, which is σ\sigma of the records of kk read so far. If k′≠kk' \ne k, then the block of kk has ended, since blocks are consecutive, so the state of cc is σ(Xk)\sigma(X_k); line L17 outputs cc and starts c=(k′,s)c = (k', s). At the end, the block of the last key has ended, and line L18 outputs it. Keys are output in the order of their blocks, which is the key order. □\square

Lemma (pass 0). After the loop of line L2, the runs are sorted on the key, and for each key kk, the multiset UU of records in all runs satisfies σ(Uk)=σ(Rk)\sigma(U_k) = \sigma(R_k) whenever RkR_k is not empty, and UkU_k is empty when RkR_k is empty.

Proof. The groups of BB pages partition RR. Line L3 sorts the records of one group YY. Without early aggregation, line L6 writes them as they are, so the run is YY in sorted order. With early aggregation, line L5 replaces them by COMBINE of the sorted sequence, which is sorted by the COMBINE lemma, and holds (k,σ(Yk))(k, \sigma(Y_k)) for each key of YY. In both cases the run ZZ satisfies σ(Zk)=σ(Yk)\sigma(Z_k) = \sigma(Y_k) for each key of YY and has no other keys. Summing over the groups with the property of σ\sigma on disjoint unions gives the claim. □\square

Lemma (merge pass). If the claim of the pass 0 lemma holds before the body of line L7, it holds after line L12.

Proof. The groups of B−1B - 1 runs partition the runs. The merge of line L10 of a group WW of sorted runs is a sequence sorted on the key that holds exactly the records of the runs of WW. Line L11 writes it as it is, or writes COMBINE of it, which by the COMBINE lemma is sorted and has σ\sigma equal for each key. So the new run ZZ satisfies σ(Zk)=σ(Wk)\sigma(Z_k) = \sigma(W_k) for each key, and the union over the groups keeps σ(Uk)=σ(Rk)\sigma(U_k) = \sigma(R_k). Freeing the runs of the group removes only records that are now in ZZ. □\square

Theorem. SORT-AGGREGATE stops, and outputs each key kk of RR exactly once, in key order, with FINAL(σ(Rk))\text{FINAL}(\sigma(R_k)), and no other row. At all times it keeps at most BB pages in memory.

Proof. If N≤BN \le B, the loop of line L2 has one group, which is all of RR, and line L4 returns FINAL of COMBINE of RR sorted, which is the claim by the COMBINE lemma.

Otherwise, let rr be the number of runs. Pass 0 makes ⌈N/B⌉≥2\lceil N/B \rceil \ge 2 runs. A pass of line L7 runs only if r>B−1≥2r > B - 1 \ge 2, and makes ⌈r/(B−1)⌉\lceil r/(B-1) \rceil runs. Since B−1≥2B - 1 \ge 2 and r≥3r \ge 3, ⌈r/(B−1)⌉≤⌈r/2⌉<r\lceil r/(B-1) \rceil \le \lceil r/2 \rceil < r, so rr decreases at each pass and the loop ends with 1≤r≤B−11 \le r \le B - 1. By the pass 0 lemma and the merge pass lemma, at that time the runs are sorted, and σ(Uk)=σ(Rk)\sigma(U_k) = \sigma(R_k) for each key of RR, with no other keys. Line L13 merges all runs into one sorted sequence of UU, and COMBINE outputs (k,σ(Uk))=(k,σ(Rk))(k, \sigma(U_k)) = (k, \sigma(R_k)) once per key in key order. FINAL then gives the answer of each group.

Memory: line L3 holds the BB pages of one group. A merge holds one page of each of at most B−1B - 1 runs, plus one output page for line L11, and COMBINE holds one extra record. So the memory never holds more than BB pages. □\square

Cost. Without early aggregation, every run of every pass holds the records of the pages it came from, so each pass reads NN pages, pass 0 and each pass of line L7 write NN pages, and line L13 writes nothing. With PP passes in total, the cost is (P−1)⋅2N+N=2NP−N(P - 1) \cdot 2N + N = 2NP - N. With early aggregation, the runs are formed from the same groups of pages and runs, and each run has at most as many records as the run that the plain sort makes from the same input, so the cost is never larger. A run has at most one record per key, so at most ⌈d/p⌉\lceil d/p \rceil pages.

Complexity

  • Passes. Pass 0 makes ⌈N/B⌉\lceil N/B \rceil runs, and each merge pass divides the number of runs by B−1B - 1, so there are P=1+⌈log⁡B−1⌈N/B⌉⌉P = 1 + \lceil \log_{B-1} \lceil N/B \rceil \rceil passes in total, the last one being the final merge.
  • I/O without early aggregation. Each pass reads NN pages, and each pass but the last writes NN pages, so the cost is 2NP−N2 N P - N. If N≤BN \le B, it is NN. If B<N≤B(B−1)B < N \le B(B-1), it is 3N3N, the same as two-pass hash aggregation.
  • I/O with early aggregation. A run never holds more than one record per group, so it has at most ⌈d/p⌉\lceil d/p \rceil pages. The cost is never more than without it, and when dd is small, the runs after pass 0 are short and the merge passes cost almost nothing. The exact cost depends on how many distinct keys each group of pages holds.
  • Time. Sorting pass 0 costs O(nlog⁡(Bp))O(n \log (B p)) comparisons, and each merge pass costs O(log⁡B)O(\log B) per record, for O(nlog⁡n)O(n \log n) in total.
  • Space. The memory holds BB pages, BpB p records, at all times.

Properties

  • Order preserving. The groups come out sorted on GG, so a later ORDER BY on GG, or a sort-merge join on GG, needs no new sort.
  • Blocking. No group is output before the input is read to the end, unless the input is already sorted on GG.
  • Stable memory use. The memory does not depend on the number of groups, so a bad estimate of dd does not cause an overflow, as it can for a hash table.
  • Deterministic. The output does not depend on how ties in the merge are broken, for exact arithmetic.

Variants and improvements

  • Stream aggregation. If the input already comes sorted on GG, for example from an index or a sort-merge join, only COMBINE runs, in one pass and with one record of memory. The first group is output as soon as its last row is read.
  • Duplicate elimination. With no aggregate, the state is empty and COMBINE drops the duplicates. This is δ(R)\delta(R), and is how Bitton and DeWitt studied the method.
  • Longer runs. Replacement selection makes runs of about 2B2B pages on random input, so fewer merge passes are needed. With early aggregation, the heap can merge equal keys at once.
  • Merge order. A system can merge fewer than B−1B - 1 runs in the first merge pass so that all later passes merge full groups, as in external sorting.
  • Parallel. Each worker sorts and combines its part, and the sorted partial results are merged by key ranges. This is the combiner step of MapReduce in sorted form.

When to use it

Use sort-based aggregation when the input is already sorted on the key, when the output must be sorted on the key, or when the number of groups is not known and may be large. Use hash aggregation when the groups are few and the order does not matter, since it reads the input once and does not sort.

Pitfalls

  • AVG of averages. A partial AVG must keep (SUM,COUNT)(\text{SUM}, \text{COUNT}). Averaging partial averages gives a wrong answer when the parts have different sizes.
  • Holistic aggregates. MEDIAN or COUNT DISTINCT have no state of fixed size. For COUNT DISTINCT, sort on GG and the column, and count the changes of the column inside each group.
  • Nulls. SQL puts all rows with a null key into one group, so the sort order must place nulls together, either first or last. COUNT(*) counts every row, while the other aggregates skip null values, and SUM of only nulls is null.
  • Empty input. With no grouping columns, an empty input still gives one row, with COUNT equal to 0 and the other aggregates null. With grouping columns, it gives no row.
  • Floating point. SUM over floating point values depends on the order of the additions, so two plans can give slightly different answers.

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)
sort_based_aggregation.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sort-based-aggregation/. The authors are listed in prov/ZDF77H.jsonl.
"""Sort-based aggregation: external merge sort on the grouping key, with early aggregation.

The input is a file of N pages on a dbrel.Disk, with p records per page. The
memory holds B pages. Pass 0 reads B pages at a time, sorts their records on
the key and writes a sorted run. Each later pass merges B - 1 runs into one.
With early=True, every run holds one partial state per key: records with the
same key are combined when a run is formed and again in every merge. The last
merge does not write its output; it returns the final rows.

A partial state record takes the space of one input record. The cost model
counts page reads and page writes, and does not count the final output.

SQL semantics: GROUP BY puts all nulls of a column in one group; count_star
counts every row; the other aggregates skip nulls; sum, avg, min and max of
no non-null value give None. With an empty key, an empty input gives one row.
"""

import heapq
from collections.abc import Iterator, Sequence
from fractions import Fraction
from numbers import Number


def _vkey(v: object) -> tuple:
    """Sort order of one key value: 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)
    return (3, repr(v))


def _kkey(k: tuple) -> tuple:
    return tuple(_vkey(v) for v in k)


# name -> (state of one value, merge two states, final answer from a state)
def _sum_merge(a: tuple, b: tuple) -> tuple:
    return (a[0] + b[0], a[1] + b[1])


def _min_merge(a: object, b: object) -> object:
    return b if a is None else a if b is None else min(a, b)


def _max_merge(a: object, b: object) -> object:
    return b if a is None else a if b is None else max(a, b)


def _avg_final(s: tuple) -> object:
    total, n = s
    if n == 0:
        return None
    if isinstance(total, (int, Fraction)):
        return Fraction(total, 1) / n
    return total / n


AGGS = {
    "count_star": (lambda v: 1, lambda a, b: a + b, lambda s: s),
    "count": (lambda v: 0 if v is None else 1, lambda a, b: a + b, lambda s: s),
    "sum": (lambda v: (0, 0) if v is None else (v, 1), _sum_merge, lambda s: s[0] if s[1] else None),
    "avg": (lambda v: (0, 0) if v is None else (v, 1), _sum_merge, _avg_final),
    "min": (lambda v: v, _min_merge, lambda s: s),
    "max": (lambda v: v, _max_merge, lambda s: s),
}


class _Run:
    """A sorted run on disk: its page ids and its number of state records."""

    def __init__(self, pages: list, size: int) -> None:
        self.pages = pages
        self.size = size


def sort_aggregate(disk, in_pages: Sequence[int], key: Sequence[int], aggs: Sequence[tuple],
                   B: int, per_page: int, early: bool = True, stats: dict | None = None) -> list:
    """Return the rows key + aggregates, sorted on the key.

    disk is a dbrel.Disk; in_pages are the page ids of the input file.
    aggs is a list of (func, column). B >= 3 is the number of buffer pages and
    per_page >= 1 the number of records in a page. If stats is a dict, it gets
    "runs" (the number of runs after each pass) and "passes".
    """
    if B < 3 or per_page < 1:
        raise ValueError("need B >= 3 and per_page >= 1")
    for f, _ in aggs:
        if f not in AGGS:
            raise ValueError("unknown aggregate %r" % (f,))
    key = list(key)
    funcs = [AGGS[f] for f, _ in aggs]

    def state(r: tuple) -> tuple:
        return (tuple(r[i] for i in key),
                [init(None if c is None else r[c]) for (init, _, _), (_, c) in zip(funcs, aggs)])

    def combine(recs) -> Iterator[tuple]:
        """Merge adjacent states with equal keys. The input is sorted on the key."""
        cur = None
        for k, st in recs:  # @line L14
            if cur is not None and cur[0] == k:  # @line L15
                cur = (k, [m(x, y) for (_, m, _), x, y in zip(funcs, cur[1], st)])  # @line L16
            else:
                if cur is not None:
                    yield cur  # @line L17
                cur = (k, list(st))
        if cur is not None:
            yield cur  # @line L18

    def finalize(recs) -> list:
        out = [k + tuple(fin(s) for (_, _, fin), s in zip(funcs, st)) for k, st in recs]
        if not key and not out:
            # A scalar aggregate of an empty input still returns one row.
            out = [tuple(fin(init(None)) if f != "count_star" else 0
                         for (init, _, fin), (f, _) in zip(funcs, aggs))]
        return out

    def write_run(recs) -> _Run:
        pages, buf, size = [], [], 0
        for rec in recs:
            buf.append(rec)
            size += 1
            if len(buf) == per_page:
                pid = disk.alloc()
                disk.write_page(pid, buf)
                pages.append(pid)
                buf = []
        if buf:
            pid = disk.alloc()
            disk.write_page(pid, buf)
            pages.append(pid)
        return _Run(pages, size)

    def scan(run: _Run) -> Iterator[tuple]:
        for pid in run.pages:  # one input buffer per run
            for rec in disk.read_page(pid):
                yield rec

    def merge(group: list) -> Iterator[tuple]:
        return heapq.merge(*[scan(r) for r in group], key=lambda rec: _kkey(rec[0]))  # @line L10

    def free(group: list) -> None:
        for r in group:
            for pid in r.pages:
                disk.free(pid)

    runs: list = []  # @line L1
    pages = list(in_pages)
    history = []
    for start in range(0, len(pages), B):  # @line L2
        recs = [state(r) for pid in pages[start:start + B] for r in disk.read_page(pid)]  # @line L3
        recs.sort(key=lambda rec: _kkey(rec[0]))  # @line L3
        if len(pages) <= B:  # @line L4
            if stats is not None:
                stats.update(runs=[], passes=1)
            return finalize(combine(recs))
        runs.append(write_run(combine(recs) if early else iter(recs)))  # @line L5 L6
    history.append(len(runs))
    while len(runs) > B - 1:  # @line L7
        new = []  # @line L8
        for start in range(0, len(runs), B - 1):  # @line L9
            group = runs[start:start + B - 1]
            merged = merge(group)
            new.append(write_run(combine(merged) if early else merged))  # @line L10 L11
            free(group)
        runs = new  # @line L12
        history.append(len(runs))
    if stats is not None:
        stats.update(runs=history, passes=len(history) + (1 if runs else 0))
    out = finalize(combine(merge(runs)))  # @line L13
    free(runs)
    return out


def sort_cost(N: int, B: int) -> int:
    """Page I/Os of sort_aggregate with early=False: 2 N P - N, where P is the number of passes."""
    if N == 0:
        return 0
    r = -(-N // B)
    passes = 1
    while r > 1:
        r = -(-r // (B - 1))
        passes += 1
    return 2 * N * passes - N
test_sort_based_aggregation.py 272 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sort-based-aggregation/. The authors are listed in prov/ZDF77H.jsonl.

import random
from collections import Counter
from fractions import Fraction

import pytest

import dbrel
from dbrel import Relation
from sort_based_aggregation import sort_aggregate, sort_cost

# ---------------------------------------------------------------- the helper dbrel
# A hand example with duplicates and a null for each operator.

R = Relation(("A", "B"), [(1, "x"), (1, "x"), (2, None), (None, "y")])
S = Relation(("B", "C"), [("x", 10), ("x", 20), (None, 30)])


def test_relation_counts_and_modes() -> None:
    assert R.rows == Counter({(1, "x"): 2, (2, None): 1, (None, "y"): 1})
    assert len(R) == 4
    assert R.with_mode("set").rows == Counter({(1, "x"): 1, (2, None): 1, (None, "y"): 1})
    assert Relation(("B", "A"), [("x", 1), ("x", 1), (None, 2), ("y", None)]) == R
    assert Relation(("A", "B"), {(1, "x"): 2}) != R
    assert R.sorted_rows() == [(None, "y"), (1, "x"), (1, "x"), (2, None)]
    with pytest.raises(ValueError):
        Relation(("A", "A"), [])
    with pytest.raises(ValueError):
        Relation(("A",), [(1, 2)])
    with pytest.raises(ValueError):
        dbrel.union(R, R.with_mode("set"))


def test_three_valued_logic() -> None:
    order = {False: 0, None: 1, True: 2}
    back = {0: False, 1: None, 2: True}
    vals = [True, False, None]
    for a in vals:
        assert dbrel.tv_not(a) == back[2 - order[a]]
        for b in vals:
            assert dbrel.tv_and(a, b) is back[min(order[a], order[b])]
            assert dbrel.tv_or(a, b) is back[max(order[a], order[b])]
    assert dbrel.cmp3("=", None, None) is None
    assert dbrel.cmp3("<>", 1, None) is None
    assert dbrel.cmp3("<", 1, 2) is True and dbrel.cmp3(">=", 1, 2) is False
    assert not dbrel.is_true(None) and dbrel.is_true(True)


def test_select_keeps_only_true() -> None:
    got = dbrel.select(R, lambda t: dbrel.cmp3("=", t["B"], "x"))
    assert got.rows == Counter({(1, "x"): 2})
    # NOT (B = 'x') drops the null row too: NOT UNKNOWN is UNKNOWN.
    got = dbrel.where(R, lambda t: dbrel.tv_not(dbrel.cmp3("=", t["B"], "x")))
    assert got.rows == Counter({(None, "y"): 1})


def test_project_rename_distinct() -> None:
    assert dbrel.project(R, ["B"]).rows == Counter({("x",): 2, (None,): 1, ("y",): 1})
    assert dbrel.project(R.with_mode("set"), ["B"]).rows == Counter({("x",): 1, (None,): 1, ("y",): 1})
    assert dbrel.rename(R, {"A": "Z"}).schema == ("Z", "B")
    assert dbrel.distinct(R).rows == Counter({(1, "x"): 1, (2, None): 1, (None, "y"): 1})
    with pytest.raises(ValueError):
        dbrel.rename(R, {"Q": "Z"})


def test_union_difference_intersection() -> None:
    T = Relation(("B", "A"), [("x", 1), (None, 2), (None, 2), ("z", 3)])
    assert dbrel.union(R, T).rows == Counter({(1, "x"): 3, (2, None): 3, (None, "y"): 1, (3, "z"): 1})
    # Bag difference is monus: max(0, m - n). Two nulls are the same value here.
    assert dbrel.difference(R, T).rows == Counter({(1, "x"): 1, (None, "y"): 1})
    assert dbrel.intersection(R, T).rows == Counter({(1, "x"): 1, (2, None): 1})
    Rs, Ts = R.with_mode("set"), T.with_mode("set")
    assert dbrel.difference(Rs, Ts).rows == Counter({(None, "y"): 1})
    assert dbrel.union(Rs, Ts).rows == Counter({(1, "x"): 1, (2, None): 1, (None, "y"): 1, (3, "z"): 1})


def test_product_and_joins() -> None:
    U = Relation(("C",), [(5,), (5,)])
    assert dbrel.product(R, U).rows == Counter({(1, "x", 5): 4, (2, None, 5): 2, (None, "y", 5): 2})
    with pytest.raises(ValueError):
        dbrel.product(R, S)
    # A null in a join attribute never matches, not even another null.
    assert dbrel.natural_join(R, S).rows == Counter({(1, "x", 10): 2, (1, "x", 20): 2})
    assert dbrel.natural_join(R, U) == dbrel.product(R, U)
    got = dbrel.theta_join(R, U, lambda t: dbrel.cmp3("<", t["A"], t["C"]))
    assert got.rows == Counter({(1, "x", 5): 4, (2, None, 5): 2})
    assert dbrel.semijoin(R, S).rows == Counter({(1, "x"): 2})
    assert dbrel.antijoin(R, S).rows == Counter({(2, None): 1, (None, "y"): 1})


def test_aggregate_sql_rules() -> None:
    aggs = [("count_star", None, "n"), ("count", "A", "c"), ("count_distinct", "A", "cd"),
            ("sum", "A", "s"), ("avg", "A", "a"), ("min", "A", "lo"), ("max", "A", "hi")]
    got = dbrel.aggregate(R, ["B"], aggs)
    assert got.schema == ("B", "n", "c", "cd", "s", "a", "lo", "hi")
    # GROUP BY puts the null in its own group; the 'y' group has only a null A.
    assert got.rows == Counter({(None, 1, 1, 1, 2, Fraction(2), 2, 2): 1,
                                ("x", 2, 2, 1, 2, Fraction(1), 1, 1): 1,
                                ("y", 1, 0, 0, None, None, None, None): 1})
    # A scalar aggregate of an empty input gives one row; a grouped one gives none.
    empty = Relation(("A", "B"), [])
    assert dbrel.aggregate(empty, [], aggs).rows == Counter({(0, 0, 0, None, None, None, None): 1})
    assert len(dbrel.aggregate(empty, ["B"], aggs)) == 0
    assert dbrel.agg_value("avg", [1, 2.5]) == 1.75
    with pytest.raises(ValueError):
        dbrel.aggregate(R, [], [("median", "A", "m")])


def test_evaluate_tree() -> None:
    db = {"R": R, "S": S}
    expr = ("project", ["A", "C"],
            ("join", ("scan", "R"), ("select", lambda t: dbrel.cmp3(">", t["C"], 10), ("scan", "S"))))
    assert dbrel.evaluate(expr, db).rows == Counter({(1, 20): 2})
    assert dbrel.evaluate(expr, db, "set").rows == Counter({(1, 20): 1})
    agg = ("aggregate", ["B"], [("count_star", None, "n")], ("scan", "R"))
    assert dbrel.evaluate(agg, db) == dbrel.aggregate(R, ["B"], [("count_star", None, "n")])
    for op in ("union", "difference", "intersection"):
        assert dbrel.evaluate((op, ("scan", "R"), ("scan", "R")), db) == getattr(dbrel, op)(R, R)
    for op, f in (("semijoin", dbrel.semijoin), ("antijoin", dbrel.antijoin)):
        assert dbrel.evaluate((op, ("scan", "R"), ("scan", "S")), db) == f(R, S)
    assert dbrel.evaluate(("distinct", ("rename", {"A": "Z"}, ("scan", "R"))), db).schema == ("Z", "B")
    with pytest.raises(ValueError):
        dbrel.evaluate(("sort", ("scan", "R")), db)


def test_disk_and_paginate() -> None:
    assert dbrel.paginate(range(5), 2) == [[0, 1], [2, 3], [4]]
    d = dbrel.Disk()
    ids = d.load([(i,) for i in range(5)], 2)
    assert ids == [0, 1, 2] and d.io() == 0
    assert d.read_page(2) == [(4,)]
    pid = d.alloc()
    d.write_page(pid, [(9,)])
    assert (d.reads, d.writes, d.io()) == (1, 1, 2)
    d.free(pid)
    assert pid not in d.pages
    d.reset_counters()
    assert d.io() == 0
    with pytest.raises(KeyError):
        d.write_page(99, [])


def test_random_relation() -> None:
    a = dbrel.random_relation(random.Random(7), ("A", "B"), 50, {"A": 3, "B": ["p", "q"]}, null_rate=0.2)
    b = dbrel.random_relation(random.Random(7), ("A", "B"), 50, {"A": 3, "B": ["p", "q"]}, null_rate=0.2)
    assert a == b and len(a) == 50
    assert any(None in t for t in a.rows)
    assert all(t[0] in (0, 1, 2, None) and t[1] in ("p", "q", None) for t in a.rows)
    assert len(dbrel.random_relation(random.Random(1), ("A",), 30, 3, mode="set")) <= 3


# ---------------------------------------------------------------- sort-based aggregation

FUNCS = ["count_star", "count", "sum", "avg", "min", "max"]


def run(rows, key, aggs, B, p, early=True):
    """Load rows on a fresh disk, aggregate, and return (result, disk, stats)."""
    disk = dbrel.Disk()
    ids = disk.load(rows, p)
    stats: dict = {}
    out = sort_aggregate(disk, ids, key, aggs, B, p, early=early, stats=stats)
    assert sorted(disk.pages) == ids  # every run page was freed
    return out, disk, stats


def reference(rel, key_attrs, aggs):
    """The same query by the definition, with dbrel.aggregate."""
    sch = rel.schema
    named = [(f, None if c is None else sch[c], "o%d" % i) for i, (f, c) in enumerate(aggs)]
    return dbrel.aggregate(rel, key_attrs, named)


def early_cost(rows, key, B, p):
    """Page I/Os with early aggregation, from the distinct keys of each input page.

    A run written for a set of input pages holds one record per distinct key of
    those pages, so it has ceil(keys / p) pages. No sorting is done here.
    """
    pages = [{tuple(r[i] for i in key) for r in pg} for pg in dbrel.paginate(rows, p)]
    N = len(pages)
    if N <= B:
        return N
    runs = [set().union(*pages[i:i + B]) for i in range(0, N, B)]
    size = lambda s: -(-len(s) // p)
    cost = N + sum(size(s) for s in runs)
    while len(runs) > B - 1:
        groups = [runs[i:i + B - 1] for i in range(0, len(runs), B - 1)]
        cost += sum(size(s) for s in runs)
        runs = [set().union(*g) for g in groups]
        cost += sum(size(s) for s in runs)
    return cost + sum(size(s) for s in runs)


def test_worked_example() -> None:
    rows = [("d", 4), ("b", 2), ("a", 5), ("c", 1), ("b", 7), ("a", 3), ("d", 6), ("c", None),
            ("a", 2), ("e", 8), ("b", 1), ("a", 4), ("e", 3), ("c", 5), ("d", 2), ("b", 6)]
    aggs = [("count_star", None), ("sum", 1)]
    want = [("a", 4, 14), ("b", 4, 16), ("c", 3, 6), ("d", 3, 12), ("e", 2, 11)]
    out, disk, st = run(rows, [0], aggs, B=3, p=2, early=False)
    assert out == want
    assert (disk.reads, disk.writes) == (24, 16) and st == {"runs": [3, 2], "passes": 3}
    assert disk.io() == sort_cost(8, 3) == 40
    out, disk, st = run(rows, [0], aggs, B=3, p=2, early=True)
    assert out == want
    # Pass 0 writes runs of 4, 5 and 4 keys (2 + 3 + 2 pages); pass 1 writes 3 + 2 pages.
    assert (disk.reads, disk.writes) == (20, 12) and st == {"runs": [3, 2], "passes": 3}
    assert disk.io() == early_cost(rows, [0], 3, 2) == 32


def test_against_definition_random() -> None:
    rng = random.Random(2024)
    for trial in range(120):
        n = rng.randrange(0, 80)
        rel = dbrel.random_relation(rng, ("A", "B", "C"), n, {"A": 4, "B": ["u", "v", "w"], "C": 5},
                                    null_rate=rng.choice([0.0, 0.15]))
        rows = rel.sorted_rows()
        rng.shuffle(rows)
        key = rng.choice([[], [0], [1], [0, 1], [1, 0]])
        aggs = [(f, None if f == "count_star" else 2) for f in rng.sample(FUNCS, 3)]
        B, p = rng.choice([3, 4, 5]), rng.choice([1, 2, 3])
        early = trial % 2 == 0
        out, disk, _ = run(rows, key, aggs, B, p, early)
        want = reference(rel, [rel.schema[i] for i in key], aggs)
        got = Relation(want.schema, out)
        assert got == want, (trial, key, aggs)
        ks = [dbrel.row_key(r[:len(key)]) for r in out]
        assert ks == sorted(ks) and len(set(ks)) == len(ks)
        if early:
            assert disk.io() == early_cost(rows, key, B, p)
        else:
            assert disk.io() == sort_cost(len(dbrel.paginate(rows, p)), B)


def test_cost_formula_without_early_aggregation() -> None:
    # 2 N P - N with P = 1 + ceil(log_{B-1} ceil(N / B)); N <= B is one read pass.
    for N, B, P in [(3, 3, 1), (6, 3, 2), (8, 3, 3), (20, 3, 4), (30, 3, 5), (40, 5, 3), (100, 11, 2)]:
        rows = [(i % 7, i) for i in range(2 * N)]
        _, disk, st = run(rows, [0], [("sum", 1)], B, 2, early=False)
        assert st["passes"] == P
        assert disk.io() == sort_cost(N, B) == 2 * N * P - N


def test_early_aggregation_saves_io() -> None:
    rng = random.Random(5)
    rows = [(rng.randrange(4), rng.randrange(10)) for _ in range(120)]
    plain, d1, s1 = run(rows, [0], [("sum", 1), ("max", 1)], 3, 2, early=False)
    early, d2, s2 = run(rows, [0], [("sum", 1), ("max", 1)], 3, 2, early=True)
    assert plain == early
    # 60 pages and 6 passes. With 4 keys, each early run has at most 2 pages,
    # so each pass after the input scan moves at most 2 pages per run.
    assert d1.io() == sort_cost(60, 3) == 2 * 60 * 6 - 60 == 660
    assert d2.io() == early_cost(rows, [0], 3, 2) == 208
    assert s1["runs"] == s2["runs"] == [20, 10, 5, 3, 2]


def test_edge_cases() -> None:
    aggs = [("count_star", None), ("count", 1), ("sum", 1), ("avg", 1), ("min", 1), ("max", 1)]
    assert run([], [0], aggs, 3, 2)[0] == []
    assert run([], [], aggs, 3, 2)[0] == [(0, 0, None, None, None, None)]
    assert run([("k", 4)], [0], aggs, 3, 2)[0] == [("k", 1, 1, 4, Fraction(4), 4, 4)]
    same = [("k", i) for i in range(30)]
    assert run(same, [0], aggs, 3, 2)[0] == [("k", 30, 30, 435, Fraction(29, 2), 0, 29)]
    nulls = [(None, None), (None, 3), ("k", None), (None, None)]
    assert run(nulls, [0], aggs, 3, 1)[0] == [(None, 3, 1, 3, Fraction(3), 3, 3),
                                              ("k", 1, 0, None, None, None, None)]
    with pytest.raises(ValueError):
        run([(1, 2)], [0], aggs, 2, 2)
    with pytest.raises(ValueError):
        run([(1, 2)], [0], [("median", 1)], 3, 2)

History

Bitton and DeWitt (1983) studied duplicate elimination in large files, and showed that duplicates can be removed during the runs of an external merge sort and not only after it. Graefe's 1993 survey describes sort-based aggregation with early aggregation in the runs and compares it with hash-based aggregation. Both plans were in use in relational systems of the 1980s, and many systems still offer both, often under the names stream aggregate and hash aggregate.

References

  1. Goetz Graefe, Query evaluation techniques for large databases, ACM Computing Surveys 25(2), 73 to 169 (1993), Section 4 (aggregation and duplicate removal; sort-based aggregation with early aggregation in the runs)
  2. Dina Bitton and David J. DeWitt, Duplicate record elimination in large data files, ACM Transactions on Database Systems 8(2), 255 to 265 (1983), duplicate removal during the runs of an external merge sort
  3. Hector Garcia-Molina, Jeffrey D. Ullman and Jennifer Widom, Database Systems, The Complete Book, second edition, Pearson (2009), Chapter 15 (two-pass grouping and duplicate elimination based on sorting)
  4. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, third edition, McGraw-Hill (2003), Chapter 14, Section 14.6 (aggregate operations, with and without grouping)

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.best
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of io.average
  • a full proof of io.best
  • a full proof of io.worst
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