Data structurecore
Decomposition storage model
Also called DSM, column-oriented storage, column store.
Store each attribute of a table in its own file of values, in record order, so that a scan reads only the columns it needs. A whole record costs one page per column.
- Space
- O(k⌈N/m⌉) extra
- Counts
- io a⌈N/m⌉ worst · average
- Where
- N = the number of records; a = the number of attributes that a scan reads; k = the number of attributes; m = the number of values in one page
- Evidence
- Proof sketchCode in 1 languages
The decomposition storage model (DSM) stores a table of attributes as separate files, one per attribute. Record is the -th value of every file. A query that reads of the attributes reads only those files, and the values it reads lie next to each other, which suits the disk and the CPU cache. The price is that a whole record is spread over pages. The N-ary storage model makes the opposite choice: whole records in one page, cheap to fetch, but a scan of one attribute reads them all. The PAX layout keeps whole records in one page, as NSM does, and groups their values by attribute inside the page, so it has the cache behavior of DSM and the I/O of NSM.
In plain words
Think of a table of people with a name, an age and a city. A column store writes all the names on one sheet, all the ages on a second sheet and all the cities on a third, in the same order of people.
To add up all the ages, you read only the age sheet. You never touch the names or the cities.
To see everything about person number 12, you look at line 12 of each of the three sheets. That is three sheets to open instead of one, and you must keep the order of the people the same on every sheet.
The abstract type
A DSM table is a sequence of records over a schema of attributes. Positions act as record ids.
append(t): add record at position and return .fetch(i, J): return the attributes in the set of the record at position .scan(J): return the attributes of all records, in position order.
Deletes and updates in place are possible but costly; see the pitfalls.
Representation
Column is a list of pages. A page has a header , with the number of entries and the start of the text area, then entries of the same size, and, for a text column, the texts at the end of the page. In the sample code an entry of an int column is the 8-byte value, and an entry of a text column is the offset and the length of its text, 2 bytes each.
The table keeps, for each column, the list of the positions of the first value of each page. Entry of page of column is attribute of record . When all values of a column have the same width, page starts at position and this list is not needed.
Copeland and Khoshafian store each column as a binary relation of pairs (surrogate, value), so each entry also holds the record id. Modern column stores leave the id out and use the position, a virtual id. The sample code does both: with ids on, an entry takes 16 bytes instead of 8, and a page holds half as many values.
Operations
APPEND(R, t)- 1
i ← N; N ← N + 1 - 2
for j ← 0 to k - 1 do - 3
P ← the last page of column j - 4
if there is no P, or the entry and the text of t[j] do not fit in P then - 5
P ← a new page of column j; append i to first_j - 6
write the entry of t[j] (with id i, if ids are stored) as entry n of P; n ← n + 1 - 7
return i FETCH(R, i, J)- 8
for each j in J do - 9
q ← the largest page number with first_j(q) ≤ i ▷ binary search - 10
v_j ← entry i - first_j(q) of page q of column j - 11
return (v_j for each j in J) SCAN(R, J)- 12
for each j in J, put a cursor before the first page of column j - 13
for i ← 0 to N - 1 do - 14
for each j in J: v_j ← the next entry of cursor j, moving to the next page of column j when a page ends - 15
output (v_j for each j in J)
SCAN reads the columns in step, all at the same position. A real system reads a block of values of one column at a time, as in vectorized execution, and often delays putting the values of a row together; this is late materialization.
Example
Take pages of 64 bytes, the schema (id int, name text, age int), and the records (962, Jane, 30) and (7658, John, 45).
| column | header | entries | text area |
|---|---|---|---|
| id | (2, 64) | 962 at bytes 4 to 11, 7658 at bytes 12 to 19 | none |
| name | (2, 56) | (60, 4) at bytes 4 to 7, (56, 4) at bytes 8 to 11 | "JohnJane" at bytes 56 to 63 |
| age | (2, 64) | 30 at bytes 4 to 11, 45 at bytes 12 to 19 | none |
A scan of the ages reads one page and, in it, the header and bytes 4 to 19. The id and name pages are not read. To fetch record 1, the table reads entry 1 of each column: three pages, one per attribute. An int page holds values, so the third record still goes to the same pages, and the eighth starts a new page of each int column.
Correctness
The invariant is that, for each column, the pages cover the positions to in order without gaps: , each page starts where the one before it ends, and entry of page is attribute of record . APPEND keeps it, because the new value goes to the last page at the position where that page ends, or to a new page whose first position is . Line L4 lets a value into a page only if its entry stays below the text area and its text stays above the entries, so no bytes of two values overlap.
FETCH is correct because the binary search at line L9 finds the one page whose range of positions holds . SCAN is correct because each cursor moves to the next page exactly when it has used all the entries of its page, so it is always at position . The proof file has the details.
Proof: A DSM table returns record i from the i-th entry of every column, and a scan of J columns reads only the pages of those columnsfull
We use the notation of the page. The table has columns and records. Column is a list of pages , and is the position of the first value of page . A page holds a header , then entries of the same size, and the texts of a text column in .
Invariant. For every column :
- , and , where every page has ; the last page ends at .
- Entry of page is the value of attribute of the record at position (and its id, if ids are stored).
- In each page, the entries , with the entry size, and the texts do not overlap, and the texts of different entries do not overlap.
Lemma 1. APPEND keeps the invariant.
Proof. Line L1 gives the new record the position . For column , the value goes to the last page if its entry and its text fit (line L4), and to a new page with otherwise (line L5). In the first case the last page gets entry , at position by part 1, and grows by one, so the last page now ends at . In the second case the new page starts at , which is where the old last page ended, and holds one entry. The test of line L4 is , so the new entry lies below the new text, and the new text lies below the old texts. The value of each column is checked to fit in an empty page before line L1, so a new page always takes it.
Theorem 1 (reconstruction). FETCH returns the attributes of the record at position .
Proof. By part 1, the pages of column cover the positions in order, so the page with the largest , found by binary search at line L9, is the one that holds position . By part 2, its entry is attribute of record .
Theorem 2 (scan). SCAN outputs, for in order, the attributes of record . It reads only the pages of the columns in , each page once, in order.
Proof. Each cursor starts before the first page of its column and moves to the next page exactly when it has used all entries of the current page. By part 1, the entry it reads for row is entry of the page that holds position , and by part 2 that is attribute of record . Every value read comes from a column in .
Theorem 3 (pages and lines). For an int column with entries of bytes (, or 16 with ids), each page holds values, so the column has pages and a scan of int columns reads pages. A page with values costs cache lines of bytes.
Proof. An int column has no texts, so a page with entries takes another one if and only if , that is, . So every page but the last holds values, which gives the page count, and Theorem 2 gives the pages of the scan. The scan reads the header and every entry of a page, which are the bytes , a range that meets lines of bytes.
For a table of int attributes stored in NSM, every page holds records, and a scan reads all pages whatever is. Theorem 3 shows that DSM without ids reads about of that, slightly less because it needs no slots.
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. A scan of columns needs buffer pages, one per cursor. The costs do not count the output. They do not separate sequential and random I/O, but this matters here: each column is read in order, and a scan of columns switches between files, which a system reads in large blocks to keep the access sequential.
| operation | page reads | CPU work |
|---|---|---|
append |
(plus writes) | plus the length of the texts |
fetch(i, J) |
for the binary searches | |
scan(J) |
for columns |
For an int column, a page of bytes holds values, or with ids. For int attributes in NSM, a page holds records, and every scan reads all pages. So a scan of attributes in DSM reads about of the pages that NSM reads, a little less because DSM needs no slots. With and , NSM holds 60 records per page and DSM 511 values per page, and a scan of one attribute of records reads 16,667 pages in NSM and 1,957 in DSM.
In the cache, a page of int values costs lines of bytes: no byte of another attribute comes into the cache. With ids, every line holds half as many values.
Variants
- Virtual ids or stored ids. Storing the id with each value, as in the binary relations of Copeland and Khoshafian, doubles the size of an int column. With dense positions the id is implicit. MonetDB stores columns as binary association tables whose head is a dense sequence of ids, which is not stored.
- A second copy sorted by value. A copy of a column as (value, id) pairs sorted by value works as an index: a range predicate becomes a search, and the ids it returns select the other attributes.
- Sorted projections. C-Store and Vertica store groups of columns, each group sorted on some of its attributes, so that the sorted columns compress well and range predicates on them read a contiguous range.
- Compression. Values of one column have one type and often few distinct values, so a column compresses far better than a row. See dictionary encoding, run-length encoding and frame of reference encoding.
- Row groups. Parquet and ORC files split a table into groups of rows and store each group by column, with a zone map per column chunk. Inside one group this is DSM, and at the scale of files it is close to PAX.
When to use it
Use DSM for analytic workloads: queries that scan a few attributes of many records, aggregate them and return a small result. Use it when the data is loaded in bulk and changed rarely. Do not use it for workloads that insert, update or fetch single whole records, where each record costs page writes or reads; use NSM there.
Pitfalls
- Tuple reconstruction. A query that needs many attributes of the qualifying records must join the columns by position. With random positions, each value is a random page read. Delay reconstruction until after the selective operators, and fetch the positions in sorted order.
- Single-row writes. An insert writes one page per column, and an update in place of a compressed column may need to rewrite a block. Systems buffer new rows in a row store and merge them into the columns in batches, as in the write store of C-Store.
- Deletes. Removing a value from the middle of a column shifts the positions of all later values, which breaks the alignment of the columns. Mark deleted positions in a bitmap and remove them only when the columns are rewritten together.
- Alignment of columns. Every column must have the same number of values in the same order. A crash in the middle of APPEND can leave the columns of different lengths, so the append must be atomic, for instance under write-ahead logging.
- Variable-width values. Without a fixed width, position is no longer at a known offset. Keep a list of first positions per page, or store fixed-width codes from a dictionary.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/decomposition-storage-model/. The authors are listed in prov/Y6XVQQ.jsonl.
"""The decomposition storage model: one file of pages per attribute.
A schema is a list of attribute types, "int" (8 bytes, signed) or "str"
(UTF-8 text). Record i of the table is the i-th value of every column. Each
column is a list of pages, and the table keeps, per column, the position of
the first value of each page, for a binary search.
A column page has a 4-byte header (n, e): the number of entries and the start
of the text area at the end of the page. Entries follow the header, each of the
same size: an 8-byte record id when ids are stored (as in the binary relations
of Copeland and Khoshafian), then the value for an int column, or the offset
and length (2 bytes each) of the text for a str column.
Every read of page bytes goes through Page.read, which logs the byte range, so
that tests can count the pages and the cache lines that an operation touches.
"""
import bisect
import struct
from typing import Iterator, List, Optional, Sequence, Set, Tuple
HEADER = struct.Struct("<HH")
INT = struct.Struct("<q")
TEXT = struct.Struct("<HH")
ID = struct.Struct("<q")
class Page:
def __init__(self, size: int) -> None:
if not 16 <= size <= 65535:
raise ValueError("page size must be from 16 to 65535 bytes")
self.size = size
self.data = bytearray(size)
HEADER.pack_into(self.data, 0, 0, size)
self.log: List[Tuple[int, int]] = []
def read(self, off: int, length: int) -> bytes:
self.log.append((off, length))
return bytes(self.data[off:off + length])
def counts(self) -> Tuple[int, int]:
return HEADER.unpack_from(self.data, 0)
class Column:
def __init__(self, typ: str, page_size: int, ids: bool) -> None:
self.typ = typ
self.page_size = page_size
self.ids = ids
self.entry = (ID.size if ids else 0) + (INT.size if typ == "int" else TEXT.size)
self.pages: List[Page] = []
self.first: List[int] = [] # first(P) for each page
def fits(self, page: Page, text: bytes) -> bool:
n, e = page.counts()
return HEADER.size + self.entry * (n + 1) + len(text) <= e
def write(self, page: Page, i: int, value: object) -> None:
n, e = page.counts()
pos = HEADER.size + self.entry * n
if self.ids:
ID.pack_into(page.data, pos, i)
pos += ID.size
if self.typ == "int":
INT.pack_into(page.data, pos, value)
else:
text = str(value).encode("utf-8")
e -= len(text)
page.data[e:e + len(text)] = text
TEXT.pack_into(page.data, pos, e, len(text))
HEADER.pack_into(page.data, 0, n + 1, e)
def value(self, page: Page, x: int, i: Optional[int] = None) -> object:
pos = HEADER.size + self.entry * x
if self.ids:
stored = ID.unpack(page.read(pos, ID.size))[0]
assert i is None or stored == i, "the id does not match the position"
pos += ID.size
if self.typ == "int":
return INT.unpack(page.read(pos, INT.size))[0]
off, length = TEXT.unpack(page.read(pos, TEXT.size))
return page.read(off, length).decode("utf-8")
class DSMTable:
def __init__(self, schema: Sequence[str], page_size: int = 4096, ids: bool = False) -> None:
if not schema or any(t not in ("int", "str") for t in schema):
raise ValueError("a schema is a non-empty list of 'int' and 'str'")
self.columns = [Column(t, page_size, ids) for t in schema]
self.N = 0
@property
def k(self) -> int:
return len(self.columns)
def append(self, t: Sequence[object]) -> int:
"""Store record t and return its position."""
if len(t) != self.k:
raise ValueError("wrong number of attributes")
texts = [str(v).encode("utf-8") if c.typ == "str" else b"" for c, v in zip(self.columns, t)]
for c, text in zip(self.columns, texts):
if HEADER.size + c.entry + len(text) > c.page_size:
raise ValueError("a value is bigger than a page")
i = self.N # @line L1
self.N += 1 # @line L1
for j, c in enumerate(self.columns): # @line L2
page = c.pages[-1] if c.pages else None # @line L3
if page is None or not c.fits(page, texts[j]): # @line L4
page = Page(c.page_size) # @line L5
c.pages.append(page) # @line L5
c.first.append(i) # @line L5
c.write(page, i, t[j]) # @line L6
return i # @line L7
def fetch(self, i: int, cols: Optional[Sequence[int]] = None) -> Tuple[object, ...]:
"""Put record i together from its columns (tuple reconstruction)."""
if not 0 <= i < self.N:
raise IndexError(i)
cols = range(self.k) if cols is None else cols
out = []
for j in cols: # @line L8
c = self.columns[j]
q = bisect.bisect_right(c.first, i) - 1 # @line L9
out.append(c.value(c.pages[q], i - c.first[q], i)) # @line L10
return tuple(out) # @line L11
def scan(self, cols: Optional[Sequence[int]] = None) -> Iterator[Tuple[object, ...]]:
"""Yield the values of the attributes cols of every record, in position order."""
cols = list(range(self.k) if cols is None else cols)
# a cursor is [column, page number, entry in the page, entries in the page]
cursors = [[self.columns[j], -1, 0, 0] for j in cols] # @line L12
for i in range(self.N): # @line L13
row = []
for cur in cursors: # @line L14
c, q, x, n = cur
if x == n: # @line L14
q += 1
n = HEADER.unpack(c.pages[q].read(0, HEADER.size))[0]
x = 0
row.append(c.value(c.pages[q], x, i)) # @line L14
cur[1:] = [q, x + 1, n]
yield tuple(row) # @line L15
# ------------------------------------------------------------ measures
def clear_logs(self) -> None:
for c in self.columns:
for page in c.pages:
page.log.clear()
def pages_touched(self) -> int:
return sum(1 for c in self.columns for page in c.pages if page.log)
def lines_touched(self, line: int) -> int:
seen: Set[Tuple[int, int, int]] = set()
for j, c in enumerate(self.columns):
for q, page in enumerate(c.pages):
for off, length in page.log:
for x in range(off // line, (off + max(length, 1) - 1) // line + 1):
seen.add((j, q, x))
return len(seen)
def check(self) -> None:
for c in self.columns:
total = 0
for q, page in enumerate(c.pages):
n, e = page.counts()
assert n >= 1 and c.first[q] == total
assert HEADER.size + c.entry * n <= e <= page.size
total += n
assert total == self.N
def values_per_page(page_size: int, ids: bool = False) -> int:
"""How many values of an int column fit in one page."""
return (page_size - HEADER.size) // ((ID.size if ids else 0) + INT.size)
test_decomposition_storage_model.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/decomposition-storage-model/. The authors are listed in prov/Y6XVQQ.jsonl.
import math
import random
import struct
import unittest
from decomposition_storage_model import DSMTable, values_per_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)
class TestDSM(unittest.TestCase):
def test_worked_example(self):
r = DSMTable(["int", "str", "int"], page_size=64)
self.assertEqual(r.append((962, "Jane", 30)), 0)
self.assertEqual(r.append((7658, "John", 45)), 1)
ids, names, ages = (c.pages[0] for c in r.columns)
self.assertEqual(struct.unpack_from("<HHqq", ids.data, 0), (2, 64, 962, 7658))
self.assertEqual(struct.unpack_from("<HHHHHH", names.data, 0), (2, 56, 60, 4, 56, 4))
self.assertEqual(bytes(names.data[56:64]), b"JohnJane")
self.assertEqual(struct.unpack_from("<HHqq", ages.data, 0), (2, 64, 30, 45))
r.clear_logs()
self.assertEqual(r.fetch(1), (7658, "John", 45))
self.assertEqual(r.pages_touched(), 3)
r.clear_logs()
self.assertEqual(list(r.scan([2])), [(30,), (45,)])
self.assertEqual(r.pages_touched(), 1)
self.assertEqual(ages.log, [(0, 4), (4, 8), (12, 8)])
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))]
r = DSMTable(types, page_size=rng.choice([64, 256, 4096]), ids=rng.random() < 0.5)
rows = []
for _ in range(rng.randrange(0, 400)):
t = random_tuple(rng, types)
self.assertEqual(r.append(t), len(rows))
rows.append(t)
r.check()
self.assertEqual(list(r.scan()), rows)
cols = sorted(rng.sample(range(len(types)), rng.randrange(1, len(types) + 1)))
self.assertEqual(list(r.scan(cols)), [tuple(t[j] for j in cols) for t in rows])
for i in rng.sample(range(len(rows)), min(20, len(rows))):
self.assertEqual(r.fetch(i), rows[i])
self.assertEqual(r.fetch(i, cols), tuple(rows[i][j] for j in cols))
def test_page_counts_and_cache_lines(self):
p, line, k = 4096, 32, 8
for ids in (False, True):
m = values_per_page(p, ids)
self.assertEqual(m, (p - 4) // (16 if ids else 8))
for n_records in (1, 511, 512, 513, 3000):
r = DSMTable(["int"] * k, page_size=p, ids=ids)
for i in range(n_records):
r.append(tuple(range(i, i + k)))
pages = math.ceil(n_records / m)
self.assertTrue(all(len(c.pages) == pages for c in r.columns))
sizes = [min(m, n_records - m * q) for q in range(pages)]
width = 16 if ids else 8
for cols in ([3], [0, 5], list(range(k))):
r.clear_logs()
self.assertEqual(sum(1 for _ in r.scan(cols)), n_records)
self.assertEqual(r.pages_touched(), len(cols) * pages)
self.assertEqual(r.lines_touched(line),
len(cols) * sum(math.ceil((4 + width * c) / line) for c in sizes))
def test_reconstruction_touches_one_page_per_column(self):
r = DSMTable(["int", "str", "int", "str"], page_size=128)
for i in range(500):
r.append((i, "v" * (i % 9), -i, str(i)))
for i in (0, 77, 499):
r.clear_logs()
self.assertEqual(r.fetch(i), (i, "v" * (i % 9), -i, str(i)))
self.assertEqual(r.pages_touched(), 4)
r.clear_logs()
r.fetch(i, [1, 2])
self.assertEqual(r.pages_touched(), 2)
def test_errors(self):
with self.assertRaises(ValueError):
DSMTable([])
r = DSMTable(["str"], page_size=64)
with self.assertRaises(ValueError):
r.append(("x" * 60,))
self.assertEqual(r.N, 0)
with self.assertRaises(IndexError):
r.fetch(0)
if __name__ == "__main__":
unittest.main()
History
Copeland and Khoshafian (1985) proposed the decomposition storage model and compared it, along several dimensions, with the n-ary storage models that systems used. Ailamaki, DeWitt, Hill and Skounakis (2001) measured DSM against NSM and PAX in the Shore storage manager, storing DSM as files of (id, value) pairs, and found that record reconstruction made DSM slow for queries on many attributes. MonetDB, from the 1990s, built its query processing on columns. C-Store and the column stores of the 2000s, surveyed by Abadi, Boncz, Harizopoulos, Idreos and Madden (2013), added compression, sorted projections and late materialization, and made column storage the standard layout for analytic databases.
References
- A decomposition storage model, the definition of the decomposed layout as binary relations of a surrogate and one attribute, and its comparison with n-ary storage
- Weaving relations for cache performance, the section on DSM and the measurements of record reconstruction
- The design and implementation of modern column-oriented database systems, the history of column stores and the chapters on column storage and tuple reconstruction
Where this leads
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag Y6XVQQ Edit this page History Report an error Markdown