Algorithm Search⌘K

Techniquecore

Frame-of-reference encoding

Also called FOR encoding.

Store the values of a block as small offsets from a base value of the block, packed in as few bits as the largest offset needs.

Frame-of-reference encoding, or FOR, compresses a column of integers block by block. Each block of BB consecutive values keeps a base, the minimum of the block, and stores each value as its offset from the base. All offsets of the block are then packed with bit packing in ww bits, the number of bits of the largest offset. Values that are large but close to each other, such as dates, timestamps, prices or keys of one range, have small offsets: a block of timestamps that spans 4,000 seconds needs 12 bits per value instead of 64. The scheme keeps two properties that matter for query processing. The value at any position is one read of ww bits plus one addition, and a range predicate on values becomes a range predicate on offsets, so a scan compares offsets and never decodes the records that fail. Goldstein, Ramakrishnan and Shaft (1998) introduced the scheme for pages of relations and indexes. It is the base of PForDelta, which applies it to the gaps of delta encoding and moves rare large values out of the block.

In plain words

Think of a list of prices that are all between 1,000 and 1,100. Each one takes four digits to write. But if you write "1,000" once at the top, you can write each price as how much it is above 1,000, and that needs at most three digits.

Frame of reference does this for each group of numbers. It finds the smallest number of the group, writes it once, and stores every number of the group as its distance from that smallest number, using only as many bits as the largest distance needs.

To read a number, add its distance to the smallest one. To find the numbers in a range, first look at the smallest and largest number of each group. Many groups are fully out of the range, or fully in it, and you never need to open them.

When it applies

  • The column holds integers, or values stored as integers, such as dates, timestamps, fixed-point prices, identifiers or dictionary codes.
  • Inside a block the values are close to each other, even if they are large. This is true for sorted or nearly sorted columns, for columns that grow with time, and for values of a small range.
  • Queries need random access to single values, for example to fetch the values at the positions of late materialization, and range predicates evaluated during the scan.
  • The values have few outliers. One far value in a block raises ww for every value of the block.

The template

The column has integers a0,…,aN−1a_0, \ldots, a_{N-1}. A range predicate keeps the positions with lo≤ai≤hilo \le a_i \le hi; either bound may be open.

  1. ENCODE(a, B)
  2. 1for each block k of the positions kB to min(N, kB + B) - 1 do
  3. 2base_k ← the minimum of the block; max_k ← the maximum of the block
  4. 3w_k ← the number of bits of max_k - base_k ▷ 0 if all values are equal
  5. 4for each position i of the block do write a[i] - base_k in w_k bits at bit (i - kB)·w_k
  6. GET(i)
  7. 5k ← ⌊i / B⌋; o ← the w_k bits at bit (i - kB)·w_k of block k
  8. 6return base_k + o
  9. SELECT(lo, hi)
  10. 7for each block k in order do
  11. 8if max_k < lo or base_k > hi then skip the block
  12. 9else if lo ≤ base_k and max_k ≤ hi then output every position of the block
  13. 10else s ← max(lo - base_k, 0); e ← hi - base_k
  14. 11output the positions i of the block with s ≤ o_i ≤ e, where o_i is the offset of i

The header of a block holds basek\mathrm{base}_k, wkw_k and, as a zone map does, maxk\mathrm{max}_k. The implementation keeps these in 17 bytes. A comparison with a constant is a range over integers: <v< v is the range up to v−1v - 1, and >v> v the range from v+1v + 1.

Why it works. The base is the minimum, so every offset is non-negative, and it is at most maxk−basek\mathrm{max}_k - \mathrm{base}_k, which has wkw_k bits, so every offset fits in its field. The fields of a block do not overlap, so GET reads back exactly the offset that was written, and adding the base gives the value. For a selection, every value of block kk is in [basek,maxk][\mathrm{base}_k, \mathrm{max}_k], so a block that misses [lo,hi][lo, hi] has no match and a block inside [lo,hi][lo, hi] matches fully. In the other blocks, lo≤ai≤hilo \le a_i \le hi is the same as lo−basek≤oi≤hi−baseklo - \mathrm{base}_k \le o_i \le hi - \mathrm{base}_k, so comparing offsets gives exactly the matching positions. The proof file has the details.

Cost. Block kk with cc values takes the header plus ⌈cwk/8⌉\lceil c w_k / 8 \rceil bytes. GET is O(1)O(1): one header and one field of wkw_k bits, with no access to the other values, unlike delta encoding, which must add the gaps from the start of a block. SELECT reads every header and reads offsets only in the blocks that meet [lo,hi][lo, hi] without lying inside it. In a sorted column the blocks that meet the range are consecutive and only the first and the last of them can be partial, so a selection reads at most 2B2B offsets and ⌈N/B⌉\lceil N / B \rceil headers.

Example. Take B=4B = 4 and the 12 values below.

block values base max ww offsets
0 1000, 1003, 1001, 1007 1000 1007 3 0, 3, 1, 7
1 1012, 1010, 1015, 1011 1010 1015 3 2, 0, 5, 1
2 1020, 1020, 1020, 1020 1020 1020 0 none

Blocks 0 and 1 need 12 bits of offsets each, 2 bytes, and block 2 needs none, since all its values equal the base. GET(6) finds block 1, reads the offset 5 at bit 6 of the block, and returns 1010+5=10151010 + 5 = 1015. For 1011≤a≤10161011 \le a \le 1016, block 0 is skipped because 1007<10111007 < 1011, and block 2 because 1020>10161020 > 1016. Block 1 is partial, so the bounds become offsets s=1s = 1 and e=6e = 6, and the offsets 2, 0, 5 and 1 give positions 4, 6 and 7. The scan read 4 offsets and no value of the other two blocks. For 1000≤a≤10201000 \le a \le 1020 every block lies inside the range, and the scan outputs all 12 positions without reading an offset. On a larger scale, the sorted column 0,3,6,…0, 3, 6, \ldots of 4,096 values with B=128B = 128 has w=9w = 9 in every block, so it takes 32 blocks of 17+14417 + 144 bytes, 5,152 bytes against 32,768 bytes as 64-bit integers.

Classic examples

  • Compressed pages. Goldstein, Ramakrishnan and Shaft (1998) compress each page of a relation or an index with a frame of reference per attribute, so that a page holds more tuples and a tuple can still be decoded alone.
  • PForDelta. Zukowski, Heman, Nes and Boncz (2006) designed PFOR and PFOR-DELTA for the MonetDB/X100 column store. They choose ww so that most values fit and store the few others as exceptions, so that one outlier no longer sets the width of a whole block; see PForDelta.
  • Column stores and file formats. Column stores use frame of reference, often together with dictionary encoding and run-length encoding, for integer, date and code columns. The minimum and maximum of each block double as a zone map.
  • Inverted lists. Search engines store the gaps between document numbers with FOR-type codes of fixed width per block, which decode fast with SIMD within a register and with vector instructions.

Variations

  • Choice of base. The base can be the minimum, as here, so that offsets are non-negative, or the first value of the block, with signed offsets. A fixed base for the whole column gives one width and no block headers, but loses the local range.
  • FOR on deltas. For a sorted column, first take the gaps between neighbors with delta encoding and then pack the gaps with FOR. The gaps are smaller than the offsets from the minimum, but random access must add the gaps from the start of the block.
  • Patched FOR. PForDelta picks ww so that only a small fraction of the values of the block do not fit, and stores those as exceptions to patch in after unpacking.
  • Block size. A small BB gives tighter ranges and better skipping, at the cost of more headers. Blocks of 128 values or so are common, so that a block fits in cache and unpacks with vector code.
  • Width per block or per page. The width can be chosen per block of values, per page, or per column chunk of a file, and each choice is a trade between header space and the fit of the width.

Pitfalls

  • Outliers. One value far from the others sets ww for the whole block. A block of small values with one value near 2602^{60} needs 60 bits per value, no better than plain storage. Use patched FOR, or smaller blocks.
  • Updates. A new value outside [basek,maxk][\mathrm{base}_k, \mathrm{max}_k] can change the base or the width, and then every offset of the block must be rewritten. FOR suits columns that are written in batches.
  • Bounds outside the block. The translated bounds lo−baseklo - \mathrm{base}_k and hi−basekhi - \mathrm{base}_k can be negative or larger than any offset. Clamp them before comparing, or test the block range first as lines L8 and L9 do.
  • Overflow. In fixed-width machine arithmetic, maxk−basek\mathrm{max}_k - \mathrm{base}_k can overflow when the values span almost the whole signed range. Compute the difference in an unsigned type of the same width.
  • Only integers. Floating-point values and strings do not have exact small offsets. Map them to integers first, for instance by dictionary encoding or by a fixed-point scale.

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)
frame_of_reference_encoding.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/frame-of-reference-encoding/. The authors are listed in prov/PWP268.jsonl.

"""Frame of reference encoding of an integer column, in blocks of B values.

Each block k keeps a header with its base (the minimum of the block), its
maximum and its bit width w_k, the number of bits of max - base. The values of
the block are stored as the offsets value - base, packed w_k bits each, least
significant bit first. A block of equal values has w_k = 0 and no offset bits.

get(i) reads one offset and adds the base, with no access to other values.
select(lo, hi) returns the positions with lo <= value <= hi (a bound of None
is open). It skips a block whose range [base, max] misses [lo, hi], takes a
block whose range lies inside [lo, hi] without reading it, and else compares
offsets with the translated bounds lo - base and hi - base. The counters
self.offsets_read and self.blocks_skipped let tests check this.
"""

from typing import List, Optional, Sequence

HEADER_BYTES = 8 + 8 + 1   # base, maximum, width


class Block:
    __slots__ = ("base", "max", "w", "count", "bits")

    def __init__(self, values: Sequence[int]) -> None:
        self.base = min(values)                               # @line L2
        self.max = max(values)                                # @line L2
        self.w = (self.max - self.base).bit_length()          # @line L3
        self.count = len(values)
        self.bits = bytearray((self.count * self.w + 7) // 8)
        for j, v in enumerate(values):                        # @line L4
            off, pos = v - self.base, j * self.w              # @line L4
            for b in range(self.w):
                if off >> b & 1:
                    self.bits[(pos + b) >> 3] |= 1 << ((pos + b) & 7)

    def offset(self, j: int) -> int:
        pos, x = j * self.w, 0                                # @line L5
        for b in range(self.w):                               # @line L5
            x |= (self.bits[(pos + b) >> 3] >> ((pos + b) & 7) & 1) << b  # @line L5
        return x


class FORColumn:
    def __init__(self, values: Sequence[int], B: int = 128) -> None:
        if B < 1:
            raise ValueError("block size must be at least 1")
        for v in values:
            if not isinstance(v, int) or isinstance(v, bool):
                raise TypeError("frame of reference encoding needs integers")
        self.B = B
        self.n = len(values)
        self.blocks: List[Block] = [Block(values[s:s + B])   # @line L1
                                    for s in range(0, self.n, B)]
        self.offsets_read = 0
        self.blocks_skipped = 0

    def get(self, i: int) -> int:
        if not 0 <= i < self.n:
            raise IndexError(i)
        blk = self.blocks[i // self.B]                        # @line L5
        self.offsets_read += 1
        return blk.base + blk.offset(i % self.B)              # @line L6

    def decode_all(self) -> List[int]:
        out = []
        for blk in self.blocks:
            out.extend(blk.base + blk.offset(j) for j in range(blk.count))
        return out

    def size_bytes(self) -> int:
        return sum(HEADER_BYTES + len(blk.bits) for blk in self.blocks)

    def select(self, lo: Optional[int], hi: Optional[int]) -> List[int]:
        out: List[int] = []
        for k, blk in enumerate(self.blocks):                 # @line L7
            first = k * self.B
            if (lo is not None and blk.max < lo) or (hi is not None and blk.base > hi):  # @line L8
                self.blocks_skipped += 1                      # @line L8
                continue
            if (lo is None or lo <= blk.base) and (hi is None or blk.max <= hi):  # @line L9
                out.extend(range(first, first + blk.count))   # @line L9
                continue
            s = 0 if lo is None else max(lo - blk.base, 0)    # @line L10
            e = blk.max - blk.base if hi is None else hi - blk.base  # @line L10
            for j in range(blk.count):                        # @line L11
                self.offsets_read += 1
                if s <= blk.offset(j) <= e:                   # @line L11
                    out.append(first + j)                     # @line L11
        return out

    def select_op(self, op: str, v: int) -> List[int]:
        """A comparison with a constant, as a range of integers."""
        ranges = {"=": (v, v), "<": (None, v - 1), "<=": (None, v),
                  ">": (v + 1, None), ">=": (v, None)}
        if op not in ranges:
            raise ValueError(f"unknown comparison {op}")
        return self.select(*ranges[op])
test_frame_of_reference_encoding.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/frame-of-reference-encoding/. The authors are listed in prov/PWP268.jsonl.

import random
import unittest

import dbrel
from frame_of_reference_encoding import HEADER_BYTES, FORColumn

EXAMPLE = [1000, 1003, 1001, 1007, 1012, 1010, 1015, 1011, 1020, 1020, 1020, 1020]
OPS = ["=", "<", "<=", ">", ">="]


def relation(values):
    return dbrel.Relation(("pos", "v"), list(enumerate(values)))


def expected_range(values, lo, hi):
    def pred(row):
        a = True if lo is None else dbrel.cmp3(">=", row["v"], lo)
        b = True if hi is None else dbrel.cmp3("<=", row["v"], hi)
        return dbrel.tv_and(a, b)
    return sorted(p for p, _ in dbrel.select(relation(values), pred).rows)


def expected_op(values, op, v):
    sel = dbrel.select(relation(values), lambda row: dbrel.cmp3(op, row["v"], v))
    return sorted(p for p, _ in sel.rows)


class TestFrameOfReference(unittest.TestCase):
    def test_worked_example(self):
        col = FORColumn(EXAMPLE, B=4)
        heads = [(b.base, b.max, b.w) for b in col.blocks]
        self.assertEqual(heads, [(1000, 1007, 3), (1010, 1015, 3), (1020, 1020, 0)])
        self.assertEqual([col.blocks[1].offset(j) for j in range(4)], [2, 0, 5, 1])
        self.assertEqual([len(b.bits) for b in col.blocks], [2, 2, 0])
        self.assertEqual(col.size_bytes(), 3 * HEADER_BYTES + 4)
        self.assertEqual(col.get(6), 1015)
        self.assertEqual(col.offsets_read, 1)

        col.offsets_read = 0
        self.assertEqual(col.select(1011, 1016), [4, 6, 7])
        self.assertEqual(col.blocks_skipped, 2)
        self.assertEqual(col.offsets_read, 4)

        col.offsets_read = col.blocks_skipped = 0
        self.assertEqual(col.select(1000, 1020), list(range(12)))
        self.assertEqual((col.offsets_read, col.blocks_skipped), (0, 0))
        self.assertEqual(col.decode_all(), EXAMPLE)

    def test_round_trip_and_size(self):
        for seed in range(150):
            rng = random.Random(seed)
            n = rng.randrange(0, 400)
            B = rng.choice([1, 2, 7, 64, 128])
            spread = rng.choice([0, 1, 5, 300, 10 ** 6, 2 ** 70])
            start = rng.randrange(-10 ** 9, 10 ** 9)
            values = [start + rng.randrange(spread + 1) for _ in range(n)]
            col = FORColumn(values, B)
            self.assertEqual(col.decode_all(), values)
            self.assertEqual([col.get(i) for i in range(n)], values)
            self.assertEqual(len(col.blocks), (n + B - 1) // B)
            for k, blk in enumerate(col.blocks):
                part = values[k * B:(k + 1) * B]
                self.assertEqual(blk.base, min(part))
                self.assertEqual(blk.w, (max(part) - min(part)).bit_length())
                self.assertEqual(len(blk.bits), (len(part) * blk.w + 7) // 8)

    def test_sorted_input_has_small_widths(self):
        values = list(range(0, 4096 * 3, 3))
        col = FORColumn(values, B=128)
        self.assertTrue(all(b.w == (127 * 3).bit_length() for b in col.blocks))
        self.assertEqual(col.size_bytes(), 32 * (HEADER_BYTES + 128 * 9 // 8))

    def test_selections_against_dbrel(self):
        for seed in range(200):
            rng = random.Random(1000 + seed)
            n = rng.randrange(0, 120)
            B = rng.choice([1, 3, 8, 16])
            if rng.random() < 0.5:
                values = sorted(rng.randrange(-50, 50) for _ in range(n))
            else:
                values = [rng.randrange(-50, 50) for _ in range(n)]
            col = FORColumn(values, B)
            for _ in range(6):
                lo = rng.choice([None] + list(range(-60, 60)))
                hi = rng.choice([None] + list(range(-60, 60)))
                self.assertEqual(col.select(lo, hi), expected_range(values, lo, hi), (lo, hi))
                op, v = rng.choice(OPS), rng.randrange(-60, 60)
                self.assertEqual(col.select_op(op, v), expected_op(values, op, v), (op, v))

    def test_skipping_on_sorted_input(self):
        values = list(range(1000))
        col = FORColumn(values, B=100)
        self.assertEqual(col.select(250, 349), list(range(250, 350)))
        self.assertEqual(col.blocks_skipped, 8)
        self.assertEqual(col.offsets_read, 200)

    def test_errors(self):
        with self.assertRaises(TypeError):
            FORColumn([1, 2.5])
        with self.assertRaises(ValueError):
            FORColumn([1], B=0)
        with self.assertRaises(ValueError):
            FORColumn([1]).select_op("<>", 1)
        with self.assertRaises(IndexError):
            FORColumn([1]).get(1)


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

Exercises

  1. A block of 128 timestamps covers 3,600 seconds. Compute its size with FOR and a 17-byte header, and compare it with 64-bit storage.
  2. Give a block of BB values in which one outlier makes FOR no better than plain storage, and compute how many bits PForDelta needs for the same block with one exception of 64 bits.
  3. Prove that if the column is sorted, SELECT reads at most 2B2B offsets, and give an unsorted column where it must read all NN offsets for a range that matches one value.
  4. Change SELECT so that it sums the matching values instead of listing them. Show that a block inside the range can add c⋅basekc \cdot \mathrm{base}_k plus the sum of its offsets, and say when the sum of the offsets can be kept in the header.
Proof: Frame of reference encoding decodes every value back, and its range selection with block skipping returns exactly the matching positionsfull

We use the notation of the page. The column is a list of integers a0,…,aN−1a_0, \ldots, a_{N-1}, cut into blocks of BB consecutive values; block kk holds the positions kBkB to min⁡(N,kB+B)−1\min(N, kB + B) - 1 (line L1). Its header has basek=min⁡\mathrm{base}_k = \min and maxk=max⁡\mathrm{max}_k = \max of its values (line L2), and wkw_k, the number of bits of maxk−basek\mathrm{max}_k - \mathrm{base}_k (line L3), which is 0 when all values are equal.

Lemma 1 (offsets fit). For every position ii in block kk, the offset oi=ai−baseko_i = a_i - \mathrm{base}_k satisfies 0≤oi≤maxk−basek<2wk0 \le o_i \le \mathrm{max}_k - \mathrm{base}_k < 2^{w_k}.

Proof. The base is the minimum and maxk\mathrm{max}_k the maximum of the block, so basek≤ai≤maxk\mathrm{base}_k \le a_i \le \mathrm{max}_k. A non-negative integer with ww bits is less than 2w2^w, and 0 has 0 bits, so the bound holds with wk=0w_k = 0 as well. □\square

Lemma 2 (round trip). GET(i)(i) returns aia_i.

Proof. Line L4 writes the wkw_k bits of oio_i at the bit positions (i−kB)wk(i - kB) w_k to (i−kB)wk+wk−1(i - kB) w_k + w_k - 1 of the bit array of block kk. These ranges are disjoint for different positions of the block, and the array starts with all bits 0, so each field holds exactly the bits of its offset, which fit by Lemma 1. Line L5 finds the block k=⌊i/B⌋k = \lfloor i / B \rfloor and reads the same field, so it returns oio_i, and line L6 returns basek+oi=ai\mathrm{base}_k + o_i = a_i. □\square

GET reads one header and wkw_k bits, so its cost does not depend on NN or on the other values of the block. Block kk uses ⌈ckwk/8⌉\lceil c_k w_k / 8 \rceil bytes for its offsets, where ckc_k is its number of values.

Theorem 1 (selection). For bounds lo≤hilo \le hi, each an integer or open, SELECT(lo,hi)(lo, hi) returns, in increasing order, exactly the positions ii with lo≤ai≤hilo \le a_i \le hi.

Proof. Take one block kk; the blocks are visited in order at line L7 and the positions inside a block in order, so the output is sorted if each block contributes exactly its matching positions. Every value of the block lies in [basek,maxk][\mathrm{base}_k, \mathrm{max}_k]. There are three cases.

If maxk<lo\mathrm{max}_k < lo or basek>hi\mathrm{base}_k > hi (line L8), every value of the block is below lolo or above hihi, so no position matches, and skipping the block is correct.

Else, if lo≤baseklo \le \mathrm{base}_k and maxk≤hi\mathrm{max}_k \le hi (line L9), every value is in [lo,hi][lo, hi], so every position matches, and line L9 outputs them all without reading an offset.

Else, line L10 sets s=max⁡(lo−basek,0)s = \max(lo - \mathrm{base}_k, 0) and e=hi−baseke = hi - \mathrm{base}_k, with s=0s = 0 for an open lolo and e=maxk−baseke = \mathrm{max}_k - \mathrm{base}_k for an open hihi. Since oi≥0o_i \ge 0 and ai=basek+oia_i = \mathrm{base}_k + o_i,

lo≤ai≤hi  ⟺  lo−basek≤oi≤hi−basek  ⟺  s≤oi≤e,lo \le a_i \le hi \iff lo - \mathrm{base}_k \le o_i \le hi - \mathrm{base}_k \iff s \le o_i \le e,

where the last step uses oi≥0o_i \ge 0 for the lower bound and oi≤maxk−baseko_i \le \mathrm{max}_k - \mathrm{base}_k for an open upper bound. By Lemma 2 line L11 reads oio_i correctly, so it outputs exactly the matching positions of the block. □\square

A comparison with a constant is a range: =v= v is [v,v][v, v], <v< v is (−∞,v−1](-\infty, v - 1], ≤v\le v is (−∞,v](-\infty, v], >v> v is [v+1,∞)[v + 1, \infty) and ≥v\ge v is [v,∞)[v, \infty), since the values are integers. If lo>hilo > hi, every block falls in the first or the third case and no position is output, which is also correct.

Theorem 2 (cost). SELECT reads every header once and reads offsets only in the blocks of the third case, that is, the blocks whose range [basek,maxk][\mathrm{base}_k, \mathrm{max}_k] meets [lo,hi][lo, hi] without lying inside it. If the column is sorted, at most two blocks are in the third case, so SELECT reads at most 2B2B offsets.

Proof. The first claim is the case analysis above. In a sorted column, basek\mathrm{base}_k and maxk\mathrm{max}_k do not decrease with kk, and maxk≤basek+1\mathrm{max}_k \le \mathrm{base}_{k+1}. A block meets [lo,hi][lo, hi] if and only if maxk≥lo\mathrm{max}_k \ge lo and basek≤hi\mathrm{base}_k \le hi. The blocks with maxk≥lo\mathrm{max}_k \ge lo are a suffix of the blocks and those with basek≤hi\mathrm{base}_k \le hi are a prefix, so the blocks that meet [lo,hi][lo, hi] form a run of consecutive blocks. Let kk be in the run but be neither its first nor its last block. Then k−1k - 1 and k+1k + 1 are in the run, so basek≥maxk−1≥lo\mathrm{base}_k \ge \mathrm{max}_{k-1} \ge lo and maxk≤basek+1≤hi\mathrm{max}_k \le \mathrm{base}_{k+1} \le hi, and block kk lies inside [lo,hi][lo, hi]. So only the first and the last block of the run can be in the third case. □\square

References

  1. Compressing relations and indexes, the frame of reference scheme, with a minimum per page and per attribute and offsets in the bits that the range needs
  2. Super-scalar RAM-CPU cache compression, the PFOR and PFOR-DELTA schemes, which extend frame of reference with exceptions
  3. The design and implementation of modern column-oriented database systems, the section on compression 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/PWP268/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