Algorithm Search⌘K

Techniqueadvanced

Late materialization

Also called late tuple reconstruction.

In a column store, run the filters on single columns and pass lists of row positions through the plan. Fetch the other columns of a row only for the positions that survive.

Late materialization is a way to run queries on a column store, a table stored as in the decomposition storage model. A record is spread over many columns, and putting its values together into a tuple is called materialization or tuple reconstruction. Early materialization builds the tuples first, from every column the query uses, and then runs the plan on tuples, as a row store would. Late materialization runs the filters on one column at a time and passes lists of positions (row numbers) from operator to operator. It reads an output column only at the positions that passed all the filters. It is a choice of plan, not of storage: the same columns serve both. It works well with compressed columns, because a filter can often run on the codes of dictionary encoding or frame of reference encoding without decoding the values of the records that fail.

In plain words

Think of a table kept as separate lists, one list of regions, one of prices, one of quantities, all in the same order of rows.

You want the quantities of the rows with region EU and price under 50. The early way is to copy out every row with its region, price and quantity, and then throw away the rows you do not want. Most of the copying was for nothing.

The late way is to read only the region list first and write down the row numbers that say EU. Then look up the prices only at those row numbers, and cross out the ones that are too high. At the end, look up the quantities only at the row numbers that are left.

When it applies

  • The data is stored by column, and a query reads several columns of the same records.
  • The filters are selective: a large part of the records fails at least one predicate, so most values of the other columns are never needed.
  • The columns are compressed, and the predicates can be evaluated on the compressed values, for instance an equality on dictionary codes or a range on frame-of-reference offsets.
  • The positions that survive come out in increasing order, so that the output columns are read in one forward pass. This is true for scans and filters, and for the outer side of many joins.

The template

A position list PP is a sorted list of row numbers; it can also be a bitmap of NN bits or a list of ranges. A predicate cθvc \mathbin{\theta} v compares column cc with a constant; a comparison with NULL is never true.

  1. LATE(R, preds, out)
  2. 1P ← the positions 0 to N - 1
  3. 2for each predicate (c, θ, v) in preds, the most selective first do
  4. 3P ← the positions i in P with R.c[i] θ v ▷ read column c only at P
  5. 4for each column c in out do
  6. 5V_c ← the values R.c[i] for i in P, in order
  7. 6return the tuples (V_c[x] for each c in out), for x ← 0 to |P| - 1
  8. EARLY(R, preds, out)
  9. 7for i ← 0 to N - 1 do
  10. 8t ← the values of record i in every column that preds or out uses
  11. 9if t satisfies every predicate then output the columns out of t

Line L3 keeps the sorted order of PP, so every column is read forward, at increasing positions, and line L6 joins the output columns by position, with no search. The parallel form of late materialization scans each predicate column fully into a bitmap and combines the bitmaps with AND; it reads more values but scans the columns independently, which suits SIMD and several cores.

Why it works. By induction over the loop at lines L2 and L3, after the m′m'-th predicate PP is the sorted list of the records that satisfy the first m′m' predicates. After the loop it is the sorted list QQ of the records that satisfy all of them, and lines L4 to L6 output, in that order, the output columns of exactly those records. EARLY outputs the same list. So the two plans give the same bag of tuples, and in the same order. The proof file has the details.

Cost. Count the column values that the plan reads. With mm predicates, rr output columns, and ∣Pm′∣|P_{m'}| the size of PP after the m′m'-th predicate, LATE reads N+∣P1∣+…+∣Pm−1∣+r∣Q∣N + |P_1| + \ldots + |P_{m-1}| + r \lvert Q \rvert values. EARLY reads NuN u, where uu is the number of distinct columns that the query uses, and the parallel form reads Nm+r∣Q∣N m + r \lvert Q \rvert. With one predicate and rr other output columns, LATE reads N+r∣Q∣N + r \lvert Q \rvert against N(1+r)N(1 + r).

Example. Take N=8N = 8 and the query "qty where region = EU and price < 50".

position 0 1 2 3 4 5 6 7
region EU US EU EU ASIA US EU ASIA
price 10 70 80 30 20 40 45 90
qty 1 2 3 4 5 6 7 8

LATE reads all 8 regions and gets P=(0,2,3,6)P = (0, 2, 3, 6). It reads 4 prices and keeps P=(0,3,6)P = (0, 3, 6). It reads 3 quantities and returns 1, 4 and 7. That is 8+4+3=158 + 4 + 3 = 15 values. EARLY reads all three columns of all 8 records, 24 values, for the same three rows. If the price predicate goes first, it keeps 5 positions, (0,3,4,5,6)(0, 3, 4, 5, 6), and LATE reads 16 values. The parallel form reads 8+8+3=198 + 8 + 3 = 19.

Classic examples

  • Selections in C-Store. Abadi, Myers, DeWitt and Madden (2007) compare early and late materialization in C-Store, each in a pipelined and a parallel form, and give a cost model. Late materialization wins for selective predicates and for aggregations over compressed columns; early materialization can win when most records qualify and many columns are output.
  • Operating on compressed data. Abadi, Madden and Ferreira (2006) run selections and aggregations directly on compressed columns. A filter on a run-length encoded column returns position ranges, and a sum over an encoded column can multiply a value by its run length.
  • Vectorized engines. MonetDB and engines in the style of vectorized execution pass vectors of positions, or selection vectors, between operators, which is late materialization in blocks of rows.
  • Index scans. A bitmap index scan in a row store builds a bitmap of qualifying rows from several indexes and fetches the rows only at the end, the same idea on row storage.

Variations

  • Position lists, bitmaps or ranges. A sorted list is compact when few records qualify, a bitmap when many do, and a list of ranges when the qualifying records are clustered, as after a filter on a sorted column.
  • Multi-column blocks. Abadi et al. (2007) pass blocks that hold a position list and the values of some columns at those positions, so that an operator does not need to read a column twice.
  • Late materialization in joins. A join can take only the join columns and positions, produce pairs of positions, and fetch the other columns after the join. The positions of the inner side then come out of order.
  • Zone maps first. A zone map can drop whole blocks of positions before the first column is read, and predicate pushdown moves the filters as close to the scan as possible so that they act on positions.

Pitfalls

  • Positions out of order. After a join or a sort, the positions of one side are not sorted, and fetching a column at them is random access. Sort the positions first and keep the permutation, or use early materialization for that side.
  • Reading a column twice. If an output column is also a predicate column and most records qualify, LATE reads it once to filter and again to output. Keep the values from the filter, as multi-column blocks do.
  • Unselective filters. When nearly every record qualifies, position lists cost as much as the data and save nothing. A cost model should choose the strategy per query.
  • Order of the predicates. The cost depends on which predicate runs first. Without statistics on selectivity and correlation, the plan can read far more than it needs.
  • Positions that change. Positions are valid only while the columns do not change. Updates and deletes in a column store need a stable snapshot, or a delete bitmap, so that a plan sees one version of every column.

Code

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)
late_materialization.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/late-materialization/. The authors are listed in prov/DADXAP.jsonl.

"""Early and late materialization of a select-project query on a column store.

A table is a dict from column name to a list of values, all of the same length
N; record i is the i-th value of every column. A query is a conjunction of
predicates (column, op, constant) and a list of output columns. A comparison
with None (NULL) is not true, as in SQL.

early() stitches each record from all the columns the query uses and then
filters it. late() works on position lists: it filters one column at a time,
reading each column only at the positions that are still alive, and fetches the
output columns only for the positions that pass. bitmap() is the parallel form
of late materialization: every predicate scans its whole column into a bitmap,
and the bitmaps are combined with AND.

Every function counts the column values it reads in self.reads.
"""

import operator
from typing import Dict, List, Sequence, Tuple

OPS = {"=": operator.eq, "<>": operator.ne, "<": operator.lt,
       "<=": operator.le, ">": operator.gt, ">=": operator.ge}
Pred = Tuple[str, str, object]


def holds(op: str, x: object, v: object) -> bool:
    return x is not None and v is not None and OPS[op](x, v)


class ColumnTable:
    def __init__(self, columns: Dict[str, List[object]]) -> None:
        lengths = {len(v) for v in columns.values()}
        if len(lengths) > 1:
            raise ValueError("all columns must have the same length")
        self.columns = {c: list(v) for c, v in columns.items()}
        self.N = lengths.pop() if lengths else 0
        self.reads = 0

    def value(self, c: str, i: int) -> object:
        self.reads += 1
        return self.columns[c][i]

    # ------------------------------------------------------------ late

    def late(self, preds: Sequence[Pred], out: Sequence[str]) -> List[Tuple[object, ...]]:
        for c, op, _ in preds:
            if c not in self.columns or op not in OPS:
                raise ValueError(f"bad predicate on {c}")
        P = list(range(self.N))                               # @line L1
        for c, op, v in preds:                                # @line L2
            P = [i for i in P if holds(op, self.value(c, i), v)]  # @line L3
        cols = [[self.value(c, i) for i in P] for c in out]   # @line L4 L5
        return list(zip(*cols)) if out else [()] * len(P)     # @line L6

    def positions(self, preds: Sequence[Pred]) -> List[int]:
        """The sorted positions of the records that satisfy every predicate."""
        P = list(range(self.N))
        for c, op, v in preds:
            P = [i for i in P if holds(op, self.columns[c][i], v)]
        return P

    # ------------------------------------------------------------ bitmap

    def bitmap(self, preds: Sequence[Pred], out: Sequence[str]) -> List[Tuple[object, ...]]:
        bits = (1 << self.N) - 1
        for c, op, v in preds:
            b = 0
            for i in range(self.N):
                if holds(op, self.value(c, i), v):
                    b |= 1 << i
            bits &= b
        P = [i for i in range(self.N) if bits >> i & 1]
        cols = [[self.value(c, i) for i in P] for c in out]
        return list(zip(*cols)) if out else [()] * len(P)

    # ------------------------------------------------------------ early

    def early(self, preds: Sequence[Pred], out: Sequence[str]) -> List[Tuple[object, ...]]:
        used = list(dict.fromkeys([c for c, _, _ in preds] + list(out)))
        result = []
        for i in range(self.N):                               # @line L7
            t = {c: self.value(c, i) for c in used}           # @line L8
            if all(holds(op, t[c], v) for c, op, v in preds):  # @line L9
                result.append(tuple(t[c] for c in out))       # @line L9
        return result


def order_by_selectivity(table: ColumnTable, preds: Sequence[Pred]) -> List[Pred]:
    """The predicates, the most selective first (by an exact count, for the tests)."""
    def passing(p: Pred) -> int:
        c, op, v = p
        return sum(1 for x in table.columns[c] if holds(op, x, v))
    return sorted(preds, key=passing)
test_late_materialization.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/late-materialization/. The authors are listed in prov/DADXAP.jsonl.

import random
import unittest

import dbrel
from late_materialization import ColumnTable, order_by_selectivity


def example():
    return ColumnTable({
        "region": ["EU", "US", "EU", "EU", "ASIA", "US", "EU", "ASIA"],
        "price": [10, 70, 80, 30, 20, 40, 45, 90],
        "qty": [1, 2, 3, 4, 5, 6, 7, 8],
    })


class TestLateMaterialization(unittest.TestCase):
    def test_worked_example(self):
        preds = [("region", "=", "EU"), ("price", "<", 50)]
        t = example()
        self.assertEqual(t.late(preds, ["qty"]), [(1,), (4,), (7,)])
        self.assertEqual(t.reads, 8 + 4 + 3)
        t = example()
        self.assertEqual(t.early(preds, ["qty"]), [(1,), (4,), (7,)])
        self.assertEqual(t.reads, 24)
        t = example()
        self.assertEqual(t.bitmap(preds, ["qty"]), [(1,), (4,), (7,)])
        self.assertEqual(t.reads, 8 + 8 + 3)
        t = example()
        t.late(list(reversed(preds)), ["qty"])
        self.assertEqual(t.reads, 8 + 5 + 3)
        self.assertEqual(order_by_selectivity(t, preds), preds)

    def test_results_against_dbrel(self):
        ops = ["=", "<>", "<", "<=", ">", ">="]
        for seed in range(200):
            rng = random.Random(seed)
            schema = ("a", "b", "c", "d")[:rng.randrange(1, 5)]
            rel = dbrel.random_relation(rng, schema, rng.randrange(0, 40), domain=5,
                                        null_rate=rng.choice([0.0, 0.2]))
            rows = [t for t in rel.sorted_rows()]
            rng.shuffle(rows)
            cols = {a: [t[j] for t in rows] for j, a in enumerate(schema)}
            preds = [(rng.choice(schema), rng.choice(ops), rng.randrange(5))
                     for _ in range(rng.randrange(0, 4))]
            out = [a for a in schema if rng.random() < 0.6] or [schema[0]]

            def pred(row, preds=preds):
                return all(dbrel.cmp3(op, row[c], v) is True for c, op, v in preds)

            expected = dbrel.project(dbrel.select(dbrel.Relation(schema, rows), pred), out)
            results = {}
            for name in ("late", "early", "bitmap"):
                table = ColumnTable(cols)
                results[name] = getattr(table, name)(preds, out)
                self.assertEqual(dbrel.Relation(out, results[name]), expected, name)
            # all three keep the records in position order
            self.assertEqual(results["late"], results["early"])
            self.assertEqual(results["late"], results["bitmap"])

    def test_read_counts(self):
        for seed in range(100):
            rng = random.Random(1000 + seed)
            n = rng.randrange(0, 60)
            cols = {c: [rng.randrange(10) for _ in range(n)] for c in "abcde"}
            preds = [(rng.choice("abcde"), rng.choice(["<", ">=", "="]), rng.randrange(10))
                     for _ in range(rng.randrange(1, 4))]
            out = rng.sample("abcde", rng.randrange(1, 4))
            sizes = []
            for m in range(len(preds)):
                sizes.append(len(ColumnTable(cols).positions(preds[:m + 1])))
            table = ColumnTable(cols)
            table.late(preds, out)
            self.assertEqual(table.reads, n + sum(sizes[:-1]) + sizes[-1] * len(out))
            table = ColumnTable(cols)
            table.early(preds, out)
            used = set(c for c, _, _ in preds) | set(out)
            self.assertEqual(table.reads, n * len(used))
            table = ColumnTable(cols)
            table.bitmap(preds, out)
            self.assertEqual(table.reads, n * len(preds) + sizes[-1] * len(out))

    def test_most_selective_first_reads_least(self):
        for seed in range(50):
            rng = random.Random(2000 + seed)
            n = 50
            cols = {c: [rng.randrange(10) for _ in range(n)] for c in "ab"}
            preds = [("a", "<", rng.randrange(10)), ("b", "<", rng.randrange(10))]
            best = order_by_selectivity(ColumnTable(cols), preds)
            t1, t2 = ColumnTable(cols), ColumnTable(cols)
            t1.late(best, ["a"])
            t2.late(list(reversed(best)), ["a"])
            self.assertLessEqual(t1.reads, t2.reads)

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            ColumnTable({"a": [1], "b": []})
        with self.assertRaises(ValueError):
            example().late([("nope", "=", 1)], ["qty"])


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

Exercises

  1. For one predicate and rr output columns, find the fraction of qualifying records above which EARLY reads fewer values than LATE when the output columns include the predicate column.
  2. Give three predicates on independent columns with selectivities 1/21/2, 1/41/4 and 1/81/8. Compute the expected values read by LATE for every order, and show that the most selective first is the best order here.
  3. Change LATE so that it keeps every value it reads, and reads a value of a column again only if it did not keep it. Prove that it never reads more values than EARLY.
  4. A join produces pairs of positions of two tables, sorted by the positions of the first. Describe how to fetch an output column of the second table with sequential reads, and give its cost.
Proof: Late materialization returns the same records, in the same order, as early materialization, and reads the number of values given on the pagefull

We use the notation of the page. A table has columns of length NN; record ii is the ii-th value of every column. A query has predicates p1,…,pmp_1, \ldots, p_m, each of the form cθvc \mathbin{\theta} v on one column cc, and output columns o1,…,oro_1, \ldots, o_r. A predicate holds on record ii only if the value is not NULL and the comparison is true. Let QQ be the sorted list of the records on which every predicate holds.

Lemma 1. After iteration m′m' of the loop at lines L2 and L3, PP is the sorted list of the records on which p1,…,pm′p_1, \ldots, p_{m'} all hold.

Proof. By induction on m′m'. Before the loop, line L1 sets PP to all records in order, which is the claim for m′=0m' = 0. Line L3 keeps, in their order, exactly the records of PP on which pm′p_{m'} holds. A sublist of a sorted list is sorted, and a record is kept if and only if it satisfies p1,…,pm′−1p_1, \ldots, p_{m'-1} (by induction) and pm′p_{m'}. □\square

Theorem 1. LATE returns the list (o1[i],…,or[i])(o_1[i], \ldots, o_r[i]) for i∈Qi \in Q, in increasing order of ii. EARLY returns the same list. So both compute, as a bag, the projection on o1,…,oro_1, \ldots, o_r of the selection of the table by p1∧…∧pmp_1 \wedge \ldots \wedge p_m.

Proof. By Lemma 1 with m′=mm' = m, P=QP = Q after the loop. Lines L4 and L5 build, for each output column, the list of its values at the positions of QQ, in the order of QQ. Line L6 takes the xx-th entry of each list, which are values of the same record Q[x]Q[x]. EARLY visits the records in increasing order (line L7), reads the values of record ii from every column the query uses (line L8), and outputs the projection exactly when every predicate holds (line L9), that is, for i∈Qi \in Q in increasing order. The two lists are equal, and each record of the selection appears once in each, which is the bag semantics of selection and projection. □\square

The order of the predicates does not change QQ, since a conjunction does not depend on the order of its terms, so any order gives the same result.

Theorem 2 (values read). Let Pm′P_{m'} be the list after iteration m′m', so ∣P0∣=N|P_0| = N and Pm=QP_m = Q. LATE reads

∑m′=1m∣Pm′−1∣+r∣Q∣\sum_{m'=1}^{m} |P_{m'-1}| + r \lvert Q \rvert

values, EARLY reads NuN u values, where uu is the number of distinct columns among the predicates and the outputs, and the bitmap variant reads Nm+r∣Q∣N m + r \lvert Q \rvert.

Proof. Iteration m′m' of line L3 reads column cc of predicate pm′p_{m'} once at each position of Pm′−1P_{m'-1}. Lines L4 and L5 read each output column at each position of QQ. EARLY reads, for each of the NN records, one value of each of the uu columns. The bitmap variant scans each predicate column completely and then reads the outputs at QQ. □\square

Since ∣Pm′∣|P_{m'}| does not increase with m′m', LATE reads at most Nm+r∣Q∣N m + r \lvert Q \rvert values, the cost of the bitmap variant. For two predicates the cost is N+∣P1∣+r∣Q∣N + |P_1| + r \lvert Q \rvert, so the predicate that keeps fewer records should come first. For more predicates the best order also depends on how the predicates are correlated, and the most selective one first is a heuristic. When m=1m = 1 and the output columns differ from the predicate column, LATE reads N+r∣Q∣N + r \lvert Q \rvert against N(1+r)N(1 + r) for EARLY, so it wins whenever ∣Q∣<N\lvert Q \rvert < N. It can read more than EARLY when an output column is also a predicate column and most records qualify, because it then reads that column twice.

References

  1. Materialization strategies in a column-oriented DBMS, the early and late materialization strategies, their cost model, and the experiments on selections, aggregations and joins
  2. Integrating compression and execution in column-oriented database systems, operators that work directly on compressed columns and pass positions
  3. The design and implementation of modern column-oriented database systems, the section on late materialization and the section on joins in column stores

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 proofH2 full proof
  • correctness: no review record reviews/DADXAP/proof-correctness.yaml
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)
WritingW3 standard
  • five exercises