Data structurecore
N-ary storage model
Also called NSM, row-oriented storage, row store.
Store each record contiguously in a slotted page, so that a whole row costs one page read. A scan of one column still reads every byte of every row.
- Space
- O(N + k) extra
- Counts
- io ⌈N/m⌉ worst · average
- Where
- N = the number of records; k = the number of attributes; m = the number of records that fit in one page
- Evidence
- Proof sketchCode in 1 languages
The N-ary storage model (NSM) stores a table as whole records. All attribute values of a record lie next to each other in one slotted page, and the pages of the table form a heap file. It is the layout of most row stores. The decomposition storage model is the opposite choice: it stores each attribute in its own file, so a scan of one attribute reads only that attribute, but a whole record must be put together from files. The PAX layout is in between: it keeps the records of a page in that page, as NSM does, but groups their values by attribute inside the page.
In plain words
Think of a table as a pile of forms, one form per person, with the name, the age and the city on each form. NSM keeps each form whole and puts the forms in folders.
If you want everything about one person, you open one folder and take out one form. This is fast.
If you want only the ages of everybody, you must still take out every form and look at one line on each. You carry the names and cities around for nothing. A column store would keep a separate sheet with only the ages on it.
The abstract type
An NSM file is a table of records over a schema of attributes, with record ids.
insert(t): store the record and return its record id (page, slot).get(rid): return all values of the record.attr(rid, j): return value of the record.delete(rid): remove the record.scan(J): return the values of the attributes in the set for every record.
Representation
A page is a slotted page: a header with the number of slots and the start of the record area, then slots of 4 bytes, each with the offset and the length of one record, then free space, and the records at the end of the page. A deleted record has the slot .
A record is a fixed part followed by a text part. The fixed part has one field per attribute, in schema order. In the sample code, an int field holds the value in 8 bytes. A text field holds, in 2 bytes, the offset inside the record where the text of that attribute ends. The text part holds the bytes of the text values in schema order.
Let be the offset of field inside the fixed part and the size of the fixed part. These numbers depend only on the schema. A text value starts where the text value before it ends, or at if it is the first text value. So any attribute is found in a constant number of steps from the start of its record, and no field of another attribute is read on the way.
Operations
ENCODE(t)- 1
fixed ← empty; text ← empty - 2
for j ← 0 to k - 1 do - 3
if attribute j is an int then append t[j] to fixed (8 bytes) - 4
else append t[j] to text; append F + |text| to fixed (2 bytes) - 5
return fixed followed by text INSERT(P, t)- 6
r ← ENCODE(t) - 7
if |r| + 4 > e - 4 - 4n then fail: page full - 8
e ← e - |r|; copy r to bytes [e, e + |r|) - 9
slot[n] ← (e, |r|); n ← n + 1 - 10
return n - 1 ATTR(P, s, j)- 11
(o, ℓ) ← slot[s] - 12
if attribute j is an int then return bytes [o + f_j, o + f_j + 8) - 13
a ← F if j is the first text attribute, else the end stored in the field of the text attribute before j - 14
b ← the end stored at o + f_j - 15
return bytes [o + a, o + b) SCAN(R, J)- 16
for each page P of R do - 17
for s ← 0 to n - 1 do - 18
if slot s is live then output ATTR(P, s, j) for each j in J
The file inserts into its last page and starts a new page when the last page is full. get is ATTR for every . delete frees the slot; the bytes of the record stay as a hole until the page is compacted, as described on the slotted page.
Example
Take a page of 64 bytes and the schema (id int, name text, age int). The fixed part has and .
| step | record bytes | slots | free bytes | ||
|---|---|---|---|---|---|
| start | 0 | 64 | 60 | ||
| insert (962, Jane, 30) | 22 at offset 42 | 1 | 42 | 0: (42, 22) | 34 |
| insert (7658, John, 45) | 22 at offset 20 | 2 | 20 | 0: (42, 22), 1: (20, 22) | 8 |
The first record holds 962 at bytes 42 to 49, the end 22 at bytes 50 and 51, the age 30 at bytes 52 to 59, and "Jane" at bytes 60 to 63. The end 22 is relative to the record: plus the 4 bytes of "Jane". A third record of 22 bytes needs 26 bytes with its slot, and only 8 are free, so the insert fails and the file starts a new page.
To read the age of record (page, 1), ATTR reads slot 1 at bytes 8 to 11, which gives , and then the 8 bytes at . It reads no other byte of the page. A scan of all the ages reads the slots and one 8-byte field of each record, but the cache brings in whole cache lines, and these lines hold the ids and names too.
Correctness
The invariant of the page is the one of the slotted page: the header, the slots and the records do not overlap, and the bytes of a live slot are the encoding of the record stored with it. Line L7 keeps it, since it allows a record only if the record and its new slot fit in the gap between the slots and the records.
The encoding is decodable because the field offsets are the same for every record and each text field stores where its text ends. The texts are stored in schema order, so the text of attribute is between the end of the text attribute before it, or , and its own end, which is what lines L13 to L15 read. A scan visits each page and each slot once, and skips the free slots, so it returns every live record once, in record id order. The proof is in the proof file.
Proof: An NSM page returns every attribute of every stored record, and a scan reads the number of pages and cache lines given on the pagefull
We use the notation of the page. The schema has attributes. Attribute has a field at offset of the fixed part, of bytes for an int and 2 bytes for a str, and is the size of the fixed part. A page of bytes has a header and slots of 4 bytes each; a live slot holds with .
Lemma 1 (the encoding). Let . For every attribute , ATTR applied to at offset 0 returns .
Proof. Lines L2 to L4 append the fields in schema order, so field starts at in , and . For an int, field is itself, which line L12 reads. For a str, let be the str attributes. When line L4 runs for , the text part holds , so the stored end , and the bytes of (with ) are . Lines L13 and L14 read exactly and , and line L15 returns those bytes.
Lemma 2 (the page). After any sequence of INSERT and DELETE, (a) ; (b) the byte ranges of the live slots are disjoint and lie in ; (c) the bytes of a live slot are the encoding of the record inserted with slot .
Proof. An empty page has and . INSERT runs line L8 only after the test of line L7, so . The new range lies above the new slot, which ends at , and below all older ranges, which lie in . So (a) and (b) hold for the new values of and , no older byte changes, and (c) holds. DELETE writes only the 4 bytes of one slot and makes it not live, which keeps (a) to (c).
Theorem 1 (round trip). For every live record id and attribute , returns , where is the record inserted as . SCAN outputs the attributes of every live record exactly once, in record id order.
Proof. Line L11 gives , and by Lemma 2(c) the bytes at are ENCODE. All offsets of lines L12 to L15 are relative to , so Lemma 1 applies. SCAN visits the pages in order and, in each, the slots in order, and line L18 skips exactly the slots that are not live. INSERT never gives a new record a slot that was used before, so each live record has one slot.
Theorem 2 (pages). If every record has the same length and records are only inserted, the file has pages for records, where .
Proof. A page with records has , so by line L7 it takes one more record if and only if , that is, if and only if , which is . So each page takes exactly records. The file opens a new page only when the last one refuses a record, so all pages but the last hold records, and the last holds from 1 to .
Theorem 3 (cache lines). Assume all attributes are ints, so , and that the line size is a power of 2, at least 8, that divides both and . A scan of one attribute of a page with records reads distinct cache lines, and a scan of all attributes reads .
Proof. The header and the slots are the bytes , which meet lines. Record lies at , which is a multiple of , so its bytes fill exactly whole lines, and the lines of different records differ. An 8-byte field at an offset that is a multiple of 8 lies in one line, because 8 divides ; so the one attribute costs one line per record, and all attributes cost lines per record. The record lines start at , a multiple of with , so they are disjoint from the lines of the slots.
So the scan of one attribute reads one line per record, while a dense array of the same values would need only lines per record. That gap is the cost that the PAX layout removes.
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 here needs only one buffer page. The costs do not count the output, and they do not separate sequential and random I/O; a scan reads the pages in file order, which is sequential when the file is contiguous on disk.
| operation | page reads | CPU work |
|---|---|---|
insert |
1 (plus a write) | for a record of bytes |
get |
1 | |
attr |
1 | plus the length of the value |
scan(J) |
plus the bytes returned |
When every record has bytes, a page holds records, so the scan reads pages whatever is. A scan of one attribute costs as much I/O as a scan of all .
The same waste happens between memory and the CPU cache. Take ints only, , and a cache line of bytes that divides and the page size. A scan of one attribute of a page with records reads cache lines, one line per record plus the slots, while the full scan reads . A dense array of the one attribute would take only lines. With , and , a page holds 60 records, and the scan of one attribute reads 68 lines against 128 for all attributes and 15 for a dense array.
The space overhead is 4 bytes of slot per record and 2 bytes per text field, plus the header of each page.
Variants
- Null bitmap. Most systems start a record with a bitmap of one bit per attribute that says whether the value is null, and leave out the fields of null values. PostgreSQL does this in its tuple header.
- Records from the start of the page. The records can also grow from the start of the page and the slots from the end. The choice does not change the costs.
- Offsets for all fields. Instead of the end of each text value, a record can store the start of every field. This costs more bytes but removes the dependency on the text attribute before.
- Vertical partitions. A table can be split into groups of attributes that queries read together, each stored in NSM. This is vertical fragmentation, and DSM is the extreme with one attribute per group.
When to use it
Use NSM when queries read or change whole records, or many attributes of few records: online transaction processing, inserts of single rows, and lookups by key through an index. A record is one page read, and an insert writes one page. Use a column layout, DSM or PAX, when most queries scan a few attributes of many records.
Pitfalls
- Wide records and narrow scans. A query that sums one int of a table with 50 attributes reads all 50 from disk and brings them through the cache. Adding an index on that attribute or a column copy helps; a faster disk does not change the ratio.
- The field offsets depend on the text before. If a record stores only lengths, as in a simple length-prefixed format, finding attribute needs a walk over all the text values before it. Store ends or offsets, as here.
- Alignment. Values that are not aligned to their size can cross a cache line or need slower loads on some CPUs. Systems often pad the fixed part, which costs space.
- Records that grow. An update that makes a record longer may not fit in its page; the slotted page then needs a forwarding address.
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/n-ary-storage-model/. The authors are listed in prov/HJWXRS.jsonl.
"""The N-ary storage model: whole records, one after another, in slotted pages.
A schema is a list of attribute types, "int" (8 bytes, signed) or "str"
(UTF-8 text of variable length). A record is encoded as a fixed part with one
field per attribute, followed by the bytes of its text values. An int field
holds the value. A str field holds, in 2 bytes, the offset inside the record of
the end of the value, so that any attribute is found in O(1) steps.
A page has a 4-byte header (n, e): the number of slots and the start of the
record area. The slots follow, 4 bytes each (offset, length), with (0, 0) for
a deleted record. Records grow from the end of the page toward the slots.
Every read of page bytes goes through Page.read, which logs the byte range, so
that tests can count the cache lines that a scan touches.
"""
import struct
from typing import Iterator, List, Optional, Sequence, Set, Tuple
HEADER = struct.Struct("<HH")
SLOT = struct.Struct("<HH")
INT = struct.Struct("<q")
END = struct.Struct("<H")
class PageFull(Exception):
"""The record does not fit in the free space of the page."""
class Schema:
def __init__(self, types: Sequence[str]) -> 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'")
self.types = list(types)
self.field: List[int] = [] # f_j, the offset of field j in the fixed part
self.prev: List[Optional[int]] = [] # the str attribute before j, if any
off, last = 0, None
for j, t in enumerate(self.types):
self.field.append(off)
self.prev.append(last)
off += INT.size if t == "int" else END.size
if t == "str":
last = j
self.fixed = off # F, the size of the fixed part
@property
def k(self) -> int:
return len(self.types)
def encode(self, t: Sequence[object]) -> bytes:
if len(t) != self.k:
raise ValueError("wrong number of attributes")
fixed, var = bytearray(), bytearray() # @line L1
for j, typ in enumerate(self.types): # @line L2
if typ == "int": # @line L3
fixed += INT.pack(t[j]) # @line L3
else:
var += str(t[j]).encode("utf-8") # @line L4
fixed += END.pack(self.fixed + len(var)) # @line L4
return bytes(fixed + var) # @line L5
class Page:
def __init__(self, size: int) -> None:
if not 8 <= size <= 65536:
raise ValueError("page size must be from 8 to 65536 bytes")
self.size = size
self.data = bytearray(size)
self._set_header(0, size if size < 65536 else 65535)
self.log: List[Tuple[int, int]] = []
def _set_header(self, n: int, e: int) -> None:
HEADER.pack_into(self.data, 0, n, e)
def read(self, off: int, length: int) -> bytes:
self.log.append((off, length))
return bytes(self.data[off:off + length])
def header(self) -> Tuple[int, int]:
return HEADER.unpack(self.read(0, HEADER.size))
def slot(self, s: int) -> Tuple[int, int]:
return SLOT.unpack(self.read(HEADER.size + SLOT.size * s, SLOT.size))
def free(self) -> int:
n, e = HEADER.unpack_from(self.data, 0)
return e - HEADER.size - SLOT.size * n
def insert(self, schema: Schema, t: Sequence[object]) -> int:
r = schema.encode(t) # @line L6
n, e = HEADER.unpack_from(self.data, 0)
if len(r) + SLOT.size > self.free(): # @line L7
raise PageFull(len(r)) # @line L7
e -= len(r) # @line L8
self.data[e:e + len(r)] = r # @line L8
SLOT.pack_into(self.data, HEADER.size + SLOT.size * n, e, len(r)) # @line L9
self._set_header(n + 1, e) # @line L9
return n # @line L10
def delete(self, s: int) -> None:
"""Free slot s. The bytes become a hole; see the slotted page for compaction."""
n, _ = HEADER.unpack_from(self.data, 0)
if not 0 <= s < n or SLOT.unpack_from(self.data, HEADER.size + SLOT.size * s)[0] == 0:
raise KeyError(s)
SLOT.pack_into(self.data, HEADER.size + SLOT.size * s, 0, 0)
def attr(self, schema: Schema, s: int, j: int, o: Optional[int] = None) -> object:
if o is None:
o, _ = self.slot(s) # @line L11
f = schema.field[j]
if schema.types[j] == "int": # @line L12
return INT.unpack(self.read(o + f, INT.size))[0] # @line L12
prev = schema.prev[j]
if prev is not None: # @line L13
a = END.unpack(self.read(o + schema.field[prev], END.size))[0] # @line L13
else:
a = schema.fixed # @line L13
b = END.unpack(self.read(o + f, END.size))[0] # @line L14
return self.read(o + a, b - a).decode("utf-8") # @line L15
def live(self) -> Iterator[Tuple[int, int]]:
n, _ = self.header()
for s in range(n): # @line L17
o, _ = self.slot(s)
if o != 0: # @line L18
yield s, o
class NSMFile:
"""A table in NSM pages. New records go to the last page, or to a new page."""
def __init__(self, schema: Sequence[str], page_size: int = 4096) -> None:
self.schema = Schema(schema)
self.page_size = page_size
self.pages: List[Page] = []
def insert(self, t: Sequence[object]) -> Tuple[int, int]:
"""Store t and return its record id (page, slot)."""
if self.pages:
try:
return len(self.pages) - 1, self.pages[-1].insert(self.schema, t)
except PageFull:
pass
page = Page(self.page_size)
s = page.insert(self.schema, t) # raises PageFull if t is bigger than a page
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, ...]:
page = self.pages[rid[0]]
o, _ = page.slot(rid[1])
if o == 0:
raise KeyError(rid)
return tuple(page.attr(self.schema, rid[1], j, o) for j in range(self.schema.k))
def scan(self, cols: Optional[Sequence[int]] = None) -> Iterator[Tuple[object, ...]]:
"""Yield the values of the attributes cols of every live record, in record id order."""
cols = range(self.schema.k) if cols is None else cols
for page in self.pages: # @line L16
for s, o in page.live(): # @line L17 L18
yield tuple(page.attr(self.schema, s, j, o) for j in cols) # @line L18
# ------------------------------------------------------------ measures
def clear_logs(self) -> None:
for page in self.pages:
page.log.clear()
def lines_touched(self, line: int) -> int:
"""The number of distinct (page, cache line) pairs read since the last clear_logs."""
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:
n, e = HEADER.unpack_from(page.data, 0)
assert HEADER.size + SLOT.size * n <= e <= page.size
spans = sorted(SLOT.unpack_from(page.data, HEADER.size + SLOT.size * s) for s in range(n))
spans = [x for x in spans if x[0] != 0]
for (o1, l1), (o2, _) in zip(spans, spans[1:]):
assert o1 + l1 <= o2
assert all(e <= o and o + ln <= page.size for o, ln in spans)
def records_per_page(page_size: int, record_length: int) -> int:
"""How many records of one length fit in an empty page."""
usable = min(page_size, 65535) - HEADER.size
return usable // (record_length + SLOT.size)
test_n_ary_storage_model.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/n-ary-storage-model/. The authors are listed in prov/HJWXRS.jsonl.
import math
import random
import unittest
from n_ary_storage_model import NSMFile, Page, PageFull, Schema, records_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 TestNSM(unittest.TestCase):
def test_worked_example(self):
schema = Schema(["int", "str", "int"])
page = Page(64)
self.assertEqual(page.insert(schema, (962, "Jane", 30)), 0)
self.assertEqual(page.insert(schema, (7658, "John", 45)), 1)
page.log.clear()
self.assertEqual(page.header(), (2, 20))
self.assertEqual(page.slot(0), (42, 22))
self.assertEqual(page.slot(1), (20, 22))
self.assertEqual(page.free(), 8)
self.assertEqual(bytes(page.data[60:64]), b"Jane")
page.log.clear()
self.assertEqual(page.attr(schema, 1, 2), 45)
self.assertEqual(page.log, [(8, 4), (30, 8)])
self.assertEqual(page.attr(schema, 0, 1), "Jane")
with self.assertRaises(PageFull):
page.insert(schema, (1, "Ann", 2))
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))]
f = NSMFile(types, page_size=rng.choice([128, 256, 4096]))
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)
rid = f.insert(t)
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_page_count(self):
for k in (1, 2, 8, 16):
s = 8 * k
for n_records in (0, 1, 59, 60, 61, 1000):
f = NSMFile(["int"] * k, page_size=4096)
for i in range(n_records):
f.insert(tuple(range(i, i + k)))
m = records_per_page(4096, s)
self.assertEqual(m, (4096 - 4) // (s + 4))
self.assertEqual(len(f.pages), math.ceil(n_records / m))
def test_cache_lines_of_a_scan(self):
p, line, k = 4096, 32, 8
s = 8 * k
m = (p - 4) // (s + 4)
self.assertEqual(m, 60)
for n_records in (60, 150, 600):
f = NSMFile(["int"] * k, page_size=p)
for i in range(n_records):
f.insert(tuple(range(i, i + k)))
sizes = [min(m, n_records - m * i) for i in range(len(f.pages))]
slot_lines = sum(math.ceil((4 + 4 * c) / line) for c in sizes)
f.clear_logs()
self.assertEqual(sum(1 for _ in f.scan([3])), n_records)
self.assertEqual(f.lines_touched(line), n_records + slot_lines)
f.clear_logs()
list(f.scan())
self.assertEqual(f.lines_touched(line), n_records * s // line + slot_lines)
def test_records_do_not_overlap_after_many_pages(self):
f = NSMFile(["str", "int"], page_size=64)
rids = [f.insert(("x" * (i % 30), i)) for i in range(200)]
f.check()
self.assertEqual([f.get(r)[1] for r in rids], list(range(200)))
with self.assertRaises(PageFull):
f.insert(("y" * 60, 0))
def test_bad_schema(self):
with self.assertRaises(ValueError):
Schema([])
with self.assertRaises(ValueError):
Schema(["float"])
if __name__ == "__main__":
unittest.main()
History
Copeland and Khoshafian (1985) proposed the decomposition storage model as the alternative to the usual layout of whole records. Ailamaki, DeWitt, Hill and Skounakis (2001) call the usual layout the N-ary storage model, "a.k.a., slotted pages", measure its cache behavior, and propose PAX. Row stores such as PostgreSQL, MySQL with InnoDB and SQLite keep whole rows in their pages, in heap pages or in the leaves of B+ trees. Abadi, Boncz, Harizopoulos, Idreos and Madden (2013) survey the column stores that replaced NSM for analytic workloads.
References
- A decomposition storage model, the comparison of the decomposed layout with the usual layout of whole records
- Weaving relations for cache performance, the section on NSM, its page layout and its cache behavior when a query reads one attribute
- Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, third edition, McGraw-Hill (2003), Chapter 9 (storing data: disks and files), the sections on record formats and page formats
- The design and implementation of modern column-oriented database systems, the introduction, the comparison of row stores and column stores
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 HJWXRS Edit this page History Report an error Markdown