Algorithm Search⌘K

Data structureadvanced

PAX page layout

Also called partition attributes across, PAX.

Keep the records of a page in that page, as NSM does, but store their values by attribute in one minipage each, so that a scan of one attribute uses whole cache lines.

Space
O(k⌈N/c⌉ + N) extra
Counts
io ⌈N/c⌉ worst · average
Where
L = the size of a cache line in bytes; N = the number of records; c = the number of records that fit in one page; k = the number of attributes

PAX (partition attributes across) is a page layout. A page holds the same records as an NSM page would, but inside the page the values are grouped by attribute: one minipage holds the first attribute of every record of the page, the next minipage the second attribute, and so on. The I/O is the I/O of NSM, since a record is still in one page and a scan still reads every page. The cache behavior is that of the decomposition storage model, since a scan of one attribute reads one contiguous minipage per page and every cache line it loads is full of useful values. Putting a record together needs only the kk minipages of one page, not kk files as in DSM.

In plain words

Think of a folder that holds the forms of 60 people. NSM keeps each form whole. PAX cuts the forms apart inside the folder: one sheet with the 60 names, one sheet with the 60 ages, one with the 60 cities. The folder still holds exactly the same 60 people.

To add up the ages, you still open every folder, as before. But in each folder you read one short sheet with only ages on it, and your eyes do not pass over names and cities.

To see everything about person 12, you open one folder and read line 12 of each sheet. That is more work than one form, but much less than opening a separate folder for each sheet, as a column store must.

The abstract type

A PAX file has the abstract type of an NSM file: a table of records over a schema of kk attributes, with record ids (page, slot).

  • insert(t): store tt and return its record id.
  • get(rid): return all kk values of the record.
  • attr(rid, j): return value jj of the record.
  • delete(rid): remove the record.
  • scan(J): return the attributes in the set JJ of all records.

Representation

A page of pp bytes has room for cc records, fixed when the page is formatted. It holds:

part contents
header nn (records on the page), cc, the start of each of the kk minipages, and one presence bit per record
F-minipage, for a fixed-width attribute cc values of the attribute; the value of record ss is at startj+wsstart_j + ws for width ww
V-minipage, for a variable-width attribute cc ends of 2 bytes, then the values one after another; end ss is where the value of record ss ends

In the sample code the fixed-width attributes are 8-byte ints, the variable-width attributes are texts, minipages start at multiples of 8, and the minipage of a text attribute is sized for an expected length avgjavg_j of its values. The capacity cc is the largest number for which the header and cc records of the expected size fit in the page.

The design of Ailamaki et al. (2001) has the same parts. Their header holds the number of attributes, the attribute sizes, the offsets of the minipages, the number of records and the free space. Their F-minipages end with a bit vector of presence bits, for null values, and their V-minipages hold the offsets of the ends of the values. The sample code keeps a single presence bit per record in the header and uses it for deletes; it has no nulls.

Operations

  1. FORMAT(P)
  2. 1c ← the largest count for which the header and c records of the expected size fit in p bytes
  3. 2give minipage j the bytes for c values of attribute j, one minipage after another
  4. INSERT(P, t)
  5. 3if n = c then fail: page full
  6. 4if the value of some text attribute j is longer than the free part of minipage j then fail: page full
  7. 5for j ← 0 to k - 1 do
  8. 6if attribute j has fixed width w then write t[j] at start_j + w n
  9. 7else write t[j] after the value of record n - 1 in minipage j, and store its end as end n
  10. 8set presence bit n; n ← n + 1; return n - 1
  11. ATTR(P, s, j)
  12. 9if attribute j has fixed width w then return bytes [start_j + w s, start_j + w s + w)
  13. 10a ← end s - 1 of minipage j, or 0 if s = 0; b ← end s
  14. 11return the bytes from a to b of the values of minipage j
  15. SCAN(P, J)
  16. 12for s ← 0 to n - 1 do
  17. 13if presence bit s is set then output ATTR(P, s, j) for each j in J

The file inserts into its last page and formats a new page when the last page refuses a record. get is ATTR for every jj: Ailamaki et al. call this the mini-join of the minipages. delete clears the presence bit; the values stay until the page is rebuilt.

Example

Take a page of 128 bytes, the schema (ssn int, name text, age int), and an expected name length of 4 bytes, so a record is expected to take 8+(2+4)+8=228 + (2 + 4) + 8 = 22 bytes. The header takes 4+2⋅3+1=114 + 2 \cdot 3 + 1 = 11 bytes. With c=5c = 5 the minipages start at 16, 56 and 88, and the last one ends at exactly 128, so c=5c = 5 is the capacity. Insert (962, Jane, 30) and (7658, John, 45), as in the figure of the PAX paper.

bytes contents
0 to 9 n=2n = 2, c=5c = 5, starts 16, 56, 88
10 presence bits 00000011
16 to 31 962, 7658
56 to 59 ends 4, 8
66 to 73 "JaneJohn"
88 to 103 30, 45

A scan of the ages reads the header and bytes 88 to 103, which are next to each other. The texts of the names minipage start at 56+2⋅5=6656 + 2 \cdot 5 = 66 and end at 88, so they have 22 bytes, of which 8 are used. A record with a name of 15 bytes is refused, even though only 2 of the 5 places are used, and goes to a new page. A name of 14 bytes fits.

Correctness

The minipages are placed one after another after the header and the last one ends inside the page, so they do not overlap. A value of an F-minipage is at a position fixed by its slot, and the test n<cn < c at line L3 keeps it inside its minipage. In a V-minipage, each value is written right after the previous one and its end is stored, so the value of slot ss is the bytes between end s−1s - 1 and end ss, and line L4 keeps the last end inside the minipage. The presence bits tell SCAN which slots are live. So ATTR returns the value that was inserted, and SCAN returns each live record once. The proof file has the details and the cache line count.

Proof: A PAX page returns every attribute of every live record, keeps its minipages apart, and a scan of one attribute reads one contiguous range per pagefull

We use the notation of the page. The schema has kk attributes. A page of pp bytes has capacity cc, a header of H=4+2k+⌈c/8⌉H = 4 + 2k + \lceil c/8 \rceil bytes, and minipages j=0,…,k−1j = 0, \ldots, k - 1 that occupy [startj,endj)[start_j, end_j), where endj=startj+1end_j = start_{j+1} and endk−1=pend_{k-1} = p. An F-minipage holds cc values of 8 bytes. A V-minipage holds cc ends of 2 bytes at [startj,startj+2c)[start_j, start_j + 2c) and the texts from basej=startj+2cbase_j = start_j + 2c to endjend_j. Let nn be the number of records and bj(s)b_j(s) the end stored for record ss in V-minipage jj, with bj(−1)=0b_j(-1) = 0.

Lemma 1 (layout). H≤start0H \le start_0, the minipages are disjoint and lie in [H,p)[H, p), and each F-minipage jj has room for cc values: startj+8c≤endjstart_j + 8c \le end_j.

Proof. Lines L1 and L2 place the minipages one after another, each at the next multiple of 8 after the end of the previous one (after the header for j=0j = 0), and give minipage jj the size 8c8c for an int and c(2+avgj)c(2 + avg_j) for a text. Line L1 picks cc so that the last one ends at most at pp. So the starts increase, the size of minipage jj is at most endj−startjend_j - start_j, and no minipage meets the header. □\square

Invariant. (a) 0≤n≤c0 \le n \le c. (b) For every record s<ns < n and int attribute jj, the 8 bytes at startj+8sstart_j + 8s are ts[j]t_s[j], the value of attribute jj of the record inserted as ss. (c) For every text attribute jj, 0=bj(−1)≤bj(0)≤…≤bj(n−1)≤endj−basej0 = b_j(-1) \le b_j(0) \le \ldots \le b_j(n - 1) \le end_j - base_j, and the bytes [basej+bj(s−1),basej+bj(s))[base_j + b_j(s - 1), base_j + b_j(s)) are ts[j]t_s[j]. (d) Presence bit ss is 1 if and only if record ss is live.

Lemma 2. INSERT keeps the invariant, and it fails only if n=cn = c or some text does not fit in the free part of its V-minipage.

Proof. Line L3 refuses when n=cn = c, and line L4 refuses when, for some text attribute jj, ∣t[j]∣>(endj−basej)−bj(n−1)|t[j]| > (end_j - base_j) - b_j(n - 1). Otherwise, for an int attribute, line L6 writes at startj+8nstart_j + 8n, which is inside the minipage since n<cn < c (Lemma 1), and touches no byte of another record. For a text attribute, line L7 writes the text at basej+bj(n−1)base_j + b_j(n - 1), just after the text of record n−1n - 1, and stores the end bj(n)=bj(n−1)+∣t[j]∣b_j(n) = b_j(n - 1) + |t[j]|, which is at most endj−basejend_j - base_j by line L4. The end is at startj+2n<basejstart_j + 2n < base_j, so it does not overlap the texts. Line L8 sets bit nn and increases nn. Parts (a) to (d) hold for the new record and did not change for the old ones. DELETE only clears one presence bit. □\square

Theorem 1 (round trip). For every live record ss of a page and every attribute jj, ATTR(s,j)=ts[j]\text{ATTR}(s, j) = t_s[j]. SCAN outputs the attributes JJ of every live record of the page once, in slot order.

Proof. For an int, line L9 reads the 8 bytes at startj+8sstart_j + 8s, which are ts[j]t_s[j] by part (b). For a text, line L10 reads a=bj(s−1)a = b_j(s - 1) (or 0 for s=0s = 0) and b=bj(s)b = b_j(s), and line L11 returns [basej+a,basej+b)[base_j + a, base_j + b), which is ts[j]t_s[j] by part (c). SCAN visits s=0,…,n−1s = 0, \ldots, n - 1 and, by part (d), outputs exactly the live ones. □\square

Theorem 2 (cache lines). A scan of one int attribute jj of a page with nn records reads only the header and the bytes [startj,startj+8n)[start_j, start_j + 8n). With lines of LL bytes, it touches at most ⌈H/L⌉+⌈8n/L⌉+1\lceil H/L \rceil + \lceil 8n/L \rceil + 1 lines, and exactly ⌈H/L⌉+8n/L\lceil H/L \rceil + 8n/L when LL divides HH, startjstart_j and 8n8n.

Proof. SCAN reads the header once, for nn and the presence bits. For each live record it reads, by line L9, the 8 bytes at startj+8sstart_j + 8s, and these ranges for s=0,…,n−1s = 0, \ldots, n - 1 fill [startj,startj+8n)[start_j, start_j + 8n) (a deleted record only leaves a gap). A range of xx bytes meets at most ⌈x/L⌉+1\lceil x/L \rceil + 1 lines, and exactly x/Lx/L when it starts at a multiple of LL and LL divides xx. □\square

For kk int attributes the capacity follows from Lemma 1: cc is the largest number such that the header, rounded up to a multiple of 8, plus 8kc8kc is at most pp. A table of NN such records has ⌈N/c⌉\lceil N/c \rceil pages, since each page takes records until n=cn = c, by Lemma 2. Theorem 2 is the point of the layout: in NSM the same scan touches one line per record, here it touches about 8/L8/L of a line per record.

Complexity

The page I/O is counted in the external memory model, with one page per block. In the external memory model, the memory holds M/B blocks; this is the number of buffer pages B of this page. Every operation needs one buffer page. The costs do not count the output and do not separate sequential and random I/O; a scan reads the pages in file order. The I/O is the I/O of NSM: get, attr, insert and delete read one page, and scan(J) reads all ⌈N/c⌉\lceil N/c \rceil pages whatever JJ is.

The gain is between memory and the CPU cache. A scan of one int attribute of a page with nn records reads the header and the 8n8n bytes of one minipage, so it touches about ⌈H/L⌉+8n/L\lceil H/L \rceil + 8n/L cache lines for a header of HH bytes, where NSM touches one line per record. With p=4096p = 4096, k=8k = 8 int attributes and L=32L = 32:

layout records per page lines read per page, one attribute lines per record
NSM 60 68 1.13
PAX 63 17 0.27
DSM, one column 511 128 0.25

PAX holds a few more records per page than this NSM, since it needs no slot per record, only one presence bit. The CPU work of a scan is O(n∣J∣)O(n \lvert J \rvert) per page, and get reads kk minipages, O(k)O(k) plus the length of the values.

Variants

  • Minipage boundaries. The sample code fixes the size of each V-minipage when it formats the page and starts a new page when one minipage fills. A system can instead move the minipage boundaries inside the page when the other minipages have room, at the cost of moving their values.
  • Nulls. Per-minipage presence bits, as in the paper, mark null values of fixed-width attributes without a separate null bitmap per record.
  • Row groups. Parquet and ORC split a file into groups of rows and store each group by column. This is the PAX idea at the scale of megabytes: a group holds whole records, and inside it each column is contiguous, with a zone map per column chunk.
  • Compression per minipage. Since a minipage holds values of one attribute, it can be compressed with dictionary encoding or frame of reference encoding independently of the others.

When to use it

Use PAX when a system stores records in pages, as a row store does, but many queries scan a few attributes of many records in memory. It changes only the layout inside the page, so the buffer pool, the record ids and the recovery code stay the same as for NSM. When the data is on disk and the scans read few attributes, a column layout such as DSM saves I/O as well, which PAX cannot do.

Pitfalls

  • No I/O saving. PAX reads every page of the table for a scan of one attribute. It speeds up the work after the page is in memory, not the reads.
  • Variable-width values. The expected sizes of the V-minipages decide the capacity. A bad guess leaves most of a page empty when one text attribute fills first.
  • Updates that grow a value. A longer value in the middle of a V-minipage shifts the values after it and changes their ends.
  • Record access touches kk places. get reads one value from each minipage, so it touches up to kk cache lines, where NSM touches ⌈s/L⌉\lceil s/L \rceil for a record of ss bytes.

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.

pax_page_layout.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pax-page-layout/. The authors are listed in prov/2CYGS7.jsonl.

"""PAX (Partition Attributes Across): a page holds whole records, by attribute.

A schema is a list of attribute types, "int" (8 bytes, signed) or "str"
(UTF-8 text). A page of p bytes holds up to c records, and its record area is
split into one minipage per attribute:

- an F-minipage (int) holds c values of 8 bytes; value s is the one of record s;
- a V-minipage (str) holds c ends of 2 bytes, then the texts one after another;
  end s is where the text of record s ends, relative to the start of the texts.

The header holds n (the number of records), c, the start of each minipage, and
one presence bit per record (0 after a delete). Minipages start at multiples
of 8. The capacity c is the largest one for which the header and c expected
records fit, where a text is expected to take `avg` bytes.

Every read of page bytes goes through PaxPage.read, which logs the byte range,
so that tests can count the cache lines a scan touches.
"""

import struct
from typing import Dict, Iterator, List, Optional, Sequence, Set, Tuple

U16 = struct.Struct("<H")
INT = struct.Struct("<q")


class PageFull(Exception):
    """The page has no room for the record."""


def _layout(types: Sequence[str], avg: Sequence[int], c: int, p: int) -> Optional[List[int]]:
    """The minipage starts for capacity c, or None if they do not fit in p bytes."""
    k = len(types)
    pos = 4 + 2 * k + (c + 7) // 8
    starts = []
    for t, a in zip(types, avg):
        pos = (pos + 7) // 8 * 8
        starts.append(pos)
        pos += c * (INT.size if t == "int" else U16.size + a)
    return starts if pos <= p else None


class PaxPage:
    def __init__(self, types: Sequence[str], size: int = 4096,
                 avg: Optional[Sequence[int]] = None) -> None:
        if not types or any(t not in ("int", "str") for t in types):
            raise ValueError("a schema is a non-empty list of 'int' and 'str'")
        if not 16 <= size <= 65535:
            raise ValueError("page size must be from 16 to 65535 bytes")
        self.types = list(types)
        self.k = len(types)
        self.size = size
        self.avg = list(avg) if avg is not None else [8] * self.k
        self.data = bytearray(size)
        self.log: List[Tuple[int, int]] = []
        per_record = sum(INT.size if t == "int" else U16.size + a for t, a in zip(self.types, self.avg))
        c = size // per_record                                # @line L1
        while c > 0 and _layout(self.types, self.avg, c, size) is None:  # @line L1
            c -= 1                                            # @line L1
        if c == 0:
            raise ValueError("not even one record fits in a page")
        self.c = c
        self.start = _layout(self.types, self.avg, c, size)   # @line L2
        self.end = self.start[1:] + [size]                    # @line L2
        self.bits = 4 + 2 * self.k                            # offset of the presence bits
        U16.pack_into(self.data, 2, c)
        for j, st in enumerate(self.start):
            U16.pack_into(self.data, 4 + 2 * j, st)

    # ------------------------------------------------------------ bytes

    def read(self, off: int, length: int) -> bytes:
        self.log.append((off, length))
        return bytes(self.data[off:off + length])

    @property
    def n(self) -> int:
        return U16.unpack_from(self.data, 0)[0]

    @property
    def header_size(self) -> int:
        return self.bits + (self.c + 7) // 8

    def _text_end(self, j: int, s: int) -> int:
        if s < 0:
            return 0
        return U16.unpack_from(self.data, self.start[j] + 2 * s)[0]

    def text_free(self, j: int) -> int:
        area = self.end[j] - self.start[j] - 2 * self.c
        return area - self._text_end(j, self.n - 1)

    def present(self, s: int, header: Optional[bytes] = None) -> bool:
        if header is None:
            header = self.read(0, self.header_size)
        return bool(header[self.bits + s // 8] >> (s % 8) & 1)

    # ------------------------------------------------------------ operations

    def insert(self, t: Sequence[object]) -> int:
        if len(t) != self.k:
            raise ValueError("wrong number of attributes")
        n = self.n
        if n == self.c:                                       # @line L3
            raise PageFull("all record places are used")      # @line L3
        texts = {j: str(v).encode("utf-8") for j, v in enumerate(t) if self.types[j] == "str"}
        for j, text in texts.items():                         # @line L4
            if len(text) > self.text_free(j):                 # @line L4
                raise PageFull(f"minipage {j} is full")       # @line L4
        for j in range(self.k):                               # @line L5
            if self.types[j] == "int":                        # @line L6
                INT.pack_into(self.data, self.start[j] + INT.size * n, t[j])  # @line L6
            else:
                a = self._text_end(j, n - 1)                  # @line L7
                base = self.start[j] + 2 * self.c             # @line L7
                self.data[base + a:base + a + len(texts[j])] = texts[j]  # @line L7
                U16.pack_into(self.data, self.start[j] + 2 * n, a + len(texts[j]))  # @line L7
        self.data[self.bits + n // 8] |= 1 << (n % 8)         # @line L8
        U16.pack_into(self.data, 0, n + 1)                    # @line L8
        return n                                              # @line L8

    def delete(self, s: int) -> None:
        if not 0 <= s < self.n or not self.data[self.bits + s // 8] >> (s % 8) & 1:
            raise KeyError(s)
        self.data[self.bits + s // 8] &= ~(1 << (s % 8)) & 0xFF

    def attr(self, s: int, j: int) -> object:
        if self.types[j] == "int":                            # @line L9
            return INT.unpack(self.read(self.start[j] + INT.size * s, INT.size))[0]  # @line L9
        if s == 0:                                            # @line L10
            a = 0                                             # @line L10
        else:
            a = U16.unpack(self.read(self.start[j] + 2 * (s - 1), 2))[0]  # @line L10
        b = U16.unpack(self.read(self.start[j] + 2 * s, 2))[0]  # @line L10
        base = self.start[j] + 2 * self.c
        return self.read(base + a, b - a).decode("utf-8")     # @line L11

    def scan(self, cols: Sequence[int]) -> Iterator[Tuple[int, Tuple[object, ...]]]:
        header = self.read(0, self.header_size)
        n = U16.unpack_from(header, 0)[0]
        for s in range(n):                                    # @line L12
            if self.present(s, header):                       # @line L13
                yield s, tuple(self.attr(s, j) for j in cols)  # @line L13


class PaxFile:
    """A table in PAX pages. New records go to the last page, or to a new page."""

    def __init__(self, types: Sequence[str], page_size: int = 4096,
                 avg: Optional[Sequence[int]] = None) -> None:
        self.types = list(types)
        self.page_size = page_size
        self.avg = avg
        self.pages: List[PaxPage] = []
        PaxPage(self.types, page_size, avg)   # check the schema and the capacity

    def _new_page(self) -> PaxPage:
        return PaxPage(self.types, self.page_size, self.avg)

    def insert(self, t: Sequence[object]) -> Tuple[int, int]:
        if self.pages:
            try:
                return len(self.pages) - 1, self.pages[-1].insert(t)
            except PageFull:
                pass
        page = self._new_page()
        s = page.insert(t)   # raises PageFull if a text is bigger than its minipage
        self.pages.append(page)
        return len(self.pages) - 1, s

    def delete(self, rid: Tuple[int, int]) -> None:
        self.pages[rid[0]].delete(rid[1])

    def get(self, rid: Tuple[int, int]) -> Tuple[object, ...]:
        """Put a record together from its minipages (the mini-join)."""
        page = self.pages[rid[0]]
        if not 0 <= rid[1] < page.n or not page.present(rid[1]):
            raise KeyError(rid)
        return tuple(page.attr(rid[1], j) for j in range(page.k))

    def scan(self, cols: Optional[Sequence[int]] = None) -> Iterator[Tuple[object, ...]]:
        cols = range(len(self.types)) if cols is None else cols
        for page in self.pages:
            for _, row in page.scan(cols):
                yield row

    # ------------------------------------------------------------ measures

    def clear_logs(self) -> None:
        for page in self.pages:
            page.log.clear()

    def lines_touched(self, line: int) -> int:
        seen: Set[Tuple[int, int]] = set()
        for i, page in enumerate(self.pages):
            for off, length in page.log:
                for x in range(off // line, (off + max(length, 1) - 1) // line + 1):
                    seen.add((i, x))
        return len(seen)

    def check(self) -> None:
        for page in self.pages:
            assert page.n <= page.c
            assert page.header_size <= page.start[0]
            for j in range(page.k):
                assert page.start[j] % 8 == 0
                if page.types[j] == "int":
                    assert page.start[j] + INT.size * page.c <= page.end[j]
                else:
                    assert page.text_free(j) >= 0


def capacity(types: Sequence[str], page_size: int, avg: Optional[Sequence[int]] = None) -> int:
    return PaxPage(types, page_size, avg).c


def counts_by_page(n_records: int, c: int) -> Dict[int, int]:
    """The records of each page when n_records fixed-size records are inserted."""
    return {q: min(c, n_records - q * c) for q in range(-(-n_records // c))}
test_pax_page_layout.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pax-page-layout/. The authors are listed in prov/2CYGS7.jsonl.

import math
import random
import struct
import unittest

from pax_page_layout import PaxFile, PaxPage, PageFull, capacity, counts_by_page


def random_tuple(rng, types):
    out = []
    for t in types:
        if t == "int":
            out.append(rng.randrange(-2 ** 63, 2 ** 63))
        else:
            out.append("".join(rng.choice("abcxyzé") for _ in range(rng.randrange(0, 12))))
    return tuple(out)


def lines_of(lo, hi, line):
    """The cache lines that meet the byte range [lo, hi)."""
    return set(range(lo // line, (hi - 1) // line + 1)) if hi > lo else set()


class TestPAX(unittest.TestCase):
    def test_worked_example(self):
        page = PaxPage(["int", "str", "int"], size=128, avg=[0, 4, 0])
        self.assertEqual(page.c, 5)
        self.assertEqual(page.start, [16, 56, 88])
        self.assertEqual(page.end, [56, 88, 128])
        self.assertEqual(page.insert((962, "Jane", 30)), 0)
        self.assertEqual(page.insert((7658, "John", 45)), 1)
        self.assertEqual(struct.unpack_from("<HHHHH", page.data, 0), (2, 5, 16, 56, 88))
        self.assertEqual(page.data[10], 0b11)
        self.assertEqual(struct.unpack_from("<qq", page.data, 16), (962, 7658))
        self.assertEqual(struct.unpack_from("<HH", page.data, 56), (4, 8))
        self.assertEqual(bytes(page.data[66:74]), b"JaneJohn")
        self.assertEqual(struct.unpack_from("<qq", page.data, 88), (30, 45))
        self.assertEqual(page.text_free(1), 14)
        page.log.clear()
        self.assertEqual([row for _, row in page.scan([2])], [(30,), (45,)])
        self.assertEqual(page.log, [(0, 11), (88, 8), (96, 8)])
        with self.assertRaises(PageFull):
            page.insert((1, "x" * 15, 2))
        self.assertEqual(page.insert((1, "x" * 14, 2)), 2)
        page.delete(0)
        self.assertEqual([row for _, row in page.scan([0, 1])], [(7658, "John"), (1, "x" * 14)])

    def test_round_trip_against_a_list(self):
        for seed in range(30):
            rng = random.Random(seed)
            types = [rng.choice(["int", "str"]) for _ in range(rng.randrange(1, 6))]
            avg = [rng.randrange(0, 12) for _ in types]
            f = PaxFile(types, page_size=rng.choice([128, 256, 4096]), avg=avg)
            model = {}
            for _ in range(300):
                if model and rng.random() < 0.2:
                    rid = rng.choice(sorted(model))
                    f.delete(rid)
                    del model[rid]
                else:
                    t = random_tuple(rng, types)
                    try:
                        rid = f.insert(t)
                    except PageFull:
                        self.assertTrue(any(len(str(v).encode()) > 0 for v in t))
                        continue
                    self.assertNotIn(rid, model)
                    model[rid] = t
                f.check()
            self.assertEqual(list(f.scan()), [model[r] for r in sorted(model)])
            for rid in rng.sample(sorted(model), min(10, len(model))):
                self.assertEqual(f.get(rid), model[rid])
            cols = sorted(rng.sample(range(len(types)), rng.randrange(1, len(types) + 1)))
            self.assertEqual(list(f.scan(cols)),
                             [tuple(model[r][j] for j in cols) for r in sorted(model)])

    def test_capacity_and_page_count(self):
        self.assertEqual(capacity(["int"] * 8, 4096), 63)
        for k in (1, 2, 8, 16):
            c = capacity(["int"] * k, 4096)
            header = 4 + 2 * k + math.ceil(c / 8)
            self.assertLessEqual(math.ceil(header / 8) * 8 + 8 * k * c, 4096)
            self.assertGreater(math.ceil((4 + 2 * k + math.ceil((c + 1) / 8)) / 8) * 8 + 8 * k * (c + 1), 4096)
            for n_records in (1, c, c + 1, 1000):
                f = PaxFile(["int"] * k, page_size=4096)
                for i in range(n_records):
                    f.insert(tuple(range(i, i + k)))
                self.assertEqual(len(f.pages), math.ceil(n_records / c))

    def test_cache_lines_of_a_scan(self):
        p, line, k = 4096, 32, 8
        c = capacity(["int"] * k, p)
        for n_records in (63, 150, 600):
            f = PaxFile(["int"] * k, page_size=p)
            for i in range(n_records):
                f.insert(tuple(range(i, i + k)))
            for cols in ([3], [0, 5], list(range(k))):
                f.clear_logs()
                self.assertEqual(sum(1 for _ in f.scan(cols)), n_records)
                expected = 0
                for q, n in counts_by_page(n_records, c).items():
                    page = f.pages[q]
                    touched = lines_of(0, page.header_size, line)
                    for j in cols:
                        touched |= lines_of(page.start[j], page.start[j] + 8 * n, line)
                    expected += len(touched)
                self.assertEqual(f.lines_touched(line), expected)
        # one attribute of a full page: one header line and 16 lines of values
        f = PaxFile(["int"] * k, page_size=p)
        for i in range(c):
            f.insert(tuple(range(k)))
        f.clear_logs()
        list(f.scan([0]))
        self.assertEqual(f.lines_touched(line), 17)

    def test_errors(self):
        with self.assertRaises(ValueError):
            PaxPage([])
        with self.assertRaises(ValueError):
            PaxPage(["int"] * 10, size=64)
        f = PaxFile(["str"], page_size=64, avg=[4])
        with self.assertRaises(PageFull):
            f.insert(("y" * 64,))
        self.assertEqual(f.pages, [])


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

History

Ailamaki, DeWitt, Hill and Skounakis (2001) proposed PAX and built it in the Shore storage manager. They report that it saves at least 75% of the stall time due to data cache accesses compared with NSM, that it runs range selections and updates on memory-resident relations 17 to 25% faster, and that it runs TPC-H queries that do I/O 11 to 48% faster, with no storage penalty and the same I/O as NSM. They compared it with NSM, which they describe as "a.k.a., slotted pages", and with DSM, stored as one file of (id, value) pairs per attribute, which needed costly record reconstruction for queries on many attributes. The row groups of Parquet and ORC follow the same idea at a larger scale.

References

  1. Weaving relations for cache performance, the abstract, the section on the design of PAX (page layout, F-minipages and V-minipages), the section on its implementation in Shore, and the evaluation
  2. A decomposition storage model, the decomposed layout that PAX applies inside one page
  3. The design and implementation of modern column-oriented database systems, the discussion of hybrid row and column layouts

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 space.extra
  • a full proof of io.average
  • 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)
WritingW4 complete
  • a review of the text: no review record reviews/2CYGS7/text.yaml