Algorithm Search⌘K

Data structureintro

Slotted page

Also called slotted page layout, slot directory.

A page layout that keeps an array of slots at one end and variable-length records at the other. A record id is (page, slot), so records can move inside the page.

Time
O(n log n + p) worstO(1) best
Space
O(n) extra
Where
n = the number of slots in the directory; p = the page size in bytes; r = the length of the record

A slotted page stores variable-length records in a fixed-size page. A small header and an array of slots grow from the start of the page, and the records grow from the end toward them, so the free space is one gap in the middle. Each slot holds the offset and the length of one record. Other parts of the system name a record by its record id, the pair (page id, slot number), and never by its byte offset. This is why the page can move records to close holes, or grow a record, and every record id stays valid. A heap file is a set of such pages; this page is about the layout inside one page, and the heap file is about how the pages of a table are found.

In plain words

Think of a page as a box with a list taped inside the lid. The things go into the box from the bottom, and each line on the list says where one thing lies and how big it is. When you want something, you ask for "box 7, line 3", read line 3 and go to that spot.

The list grows down from the top, and the things pile up from the bottom. The box is full when they meet.

When you throw something out, you cross out its line, and its space becomes a hole. Later you can push all the things together to close the holes. The positions change, but the line numbers do not, so anyone who wrote down "box 7, line 3" still finds the same thing.

The abstract type

A slotted page is a map from small integers (slots) to byte strings (records), stored in a page of pp bytes.

  • insert(P, r): store record rr and return a slot ss that no live record uses. Fail with page full only if rr cannot fit even after compaction.
  • get(P, s): the record of slot ss, or nothing if ss is free.
  • delete(P, s): free slot ss.
  • update(P, s, r): replace the record of slot ss by rr; the slot stays the same.
  • compact(P): move the live records together; no slot and no record changes.

The guarantee that matters to the rest of the system is that a slot, once returned, names the same record until that record is deleted. Indexes store record ids, and a record id is (page id, ss).

Representation

All numbers below are 2-byte integers, which allows pages up to 64 KB. Real systems use other widths; the layout is the same.

bytes contents
0 to 1 nn, the number of slots in the directory
2 to 3 ee, the offset of the first byte of the record area (free end)
4+4s4 + 4s to 7+4s7 + 4s slot ss: the offset and the length of its record, or (0,0)(0, 0) if it is free
4+4n4 + 4n to e−1e - 1 free space
ee to p−1p - 1 records, in any order, with holes left by deletes

The offset 0 marks a free slot, since the header is at offset 0 and no record can start there.

The invariant has four parts.

  1. 4+4n≤e≤p4 + 4n \le e \le p: the directory and the record area do not overlap.
  2. Every live slot ss has an offset oso_s and length ℓs\ell_s with e≤ose \le o_s and os+ℓs≤po_s + \ell_s \le p, and the byte ranges of two live slots are disjoint.
  3. If n>0n > 0, slot n−1n - 1 is live: the directory has no free slots at its end.
  4. The bytes at [os,os+ℓs)[o_s, o_s + \ell_s) are the last record stored in slot ss.

The page has two measures of free space. The contiguous free space is e−4−4ne - 4 - 4n, the gap in the middle. The total free space is p−4−4n−∑sℓsp - 4 - 4n - \sum_s \ell_s over the live slots, the gap plus the holes. Compaction makes the two equal.

Operations

  1. INSERT(P, r) ▷ returns the slot of r
  2. 1s ← the least free slot, or n if no slot is free
  3. 2need ← |r|, plus 4 if s = n ▷ a new slot entry also takes space
  4. 3if need > e - 4 - 4n then
  5. 4if need > the total free space then fail: page full
  6. 5COMPACT(P)
  7. 6e ← e - |r|; copy r to bytes [e, e + |r|)
  8. 7if s = n then n ← n + 1
  9. 8slot[s] ← (e, |r|)
  10. 9return s
  11. DELETE(P, s)
  12. 10slot[s] ← (0, 0)
  13. 11while n > 0 and slot[n - 1] is free do
  14. 12n ← n - 1
  15. COMPACT(P)
  16. 13L ← the live slots, sorted by offset from high to low
  17. 14e' ← p
  18. 15for each slot s in L do
  19. 16e' ← e' - ℓ_s
  20. 17move bytes [o_s, o_s + ℓ_s) to [e', e' + ℓ_s)
  21. 18slot[s] ← (e', ℓ_s)
  22. 19e ← e'

get(P, s) reads slot ss and returns the bytes it points to. update(P, s, r) writes rr in place when ∣r∣≤ℓs|r| \le \ell_s (the tail of the old record becomes a hole). When rr is longer, it frees slot ss for a moment, compacts if the gap is too small, and writes rr at the free end under the same slot. If rr does not fit even then, the record must leave the page; see the pitfalls.

COMPACT moves each record toward the end of the page, never toward the start. The records are taken from the highest offset down, and the bytes placed so far are exactly the records with higher offsets, so e′≥ose' \ge o_s at line L17. The move is a memory move that is safe when source and target overlap.

Example

Take p=64p = 64. The header uses bytes 0 to 3, and each slot entry 4 bytes.

step slots after the step nn ee gap total free
start none 0 64 60 60
insert A (10 bytes) 0: (54, 10) 1 54 46 46
insert B (6 bytes) 0: (54, 10), 1: (48, 6) 2 48 36 36
insert C (12 bytes) 0: (54, 10), 1: (48, 6), 2: (36, 12) 3 36 20 20
delete slot 1 0: (54, 10), 1: free, 2: (36, 12) 3 36 20 26
insert D (24 bytes) 0: (54, 10), 1: (18, 24), 2: (42, 12) 3 18 2 2

The delete leaves a hole of 6 bytes at offsets 48 to 53, and slot 1 stays in the directory because slot 2 after it is live. The insert of D reuses slot 1, so it needs 24 bytes. The gap has only 20, but the total free space is 26, so line L5 compacts: A stays at 54, C moves from 36 to 42, and ee becomes 42. D is then written at 18. Slot 2 still names C, at a new offset. A record id (page, 2) stored in an index before the compaction still finds C.

If D had been 27 bytes, it would need 27 bytes against 26 free, and the insert would fail with page full. The heap file would then try another page.

Correctness

Each operation keeps the four parts of the invariant.

  • INSERT writes rr at [e−∣r∣,e)[e - |r|, e), which lies in the gap because line L3 or the compaction at line L5 ensures that the gap holds needneed bytes. So the new record overlaps no live record and no slot entry, including a new entry at the end of the directory. Other slots do not change.
  • DELETE frees one slot, and lines L11 and L12 drop free slots from the end of the directory, which restores part 3.
  • COMPACT places the live records next to each other at the end of the page, in the order of their old offsets. Their lengths add up to p−e′p - e', so they are disjoint and lie in [e′,p)[e', p). The directory and nn do not change, so it keeps parts 1 and 3. A memory move copies the bytes even when the ranges overlap, which keeps part 4.

INSERT fails only when rr cannot fit. After COMPACT the gap equals the total free space, and the insert needs exactly needneed bytes of the gap. So it fails if and only if needneed is more than the total free space, which is the test at line L4. INSERT returns a free slot by line L1, so no live record loses its slot, and no operation other than DELETE frees a slot. The full proof is below.

Proof: The slotted page keeps its layout invariant, keeps record ids stable, and rejects a record only when it cannot fitfull

We use the notation of the page. The page has pp bytes, a header of 4 bytes, nn slot entries of 4 bytes, and the free end ee. A live slot ss has offset os>0o_s > 0 and length ℓs\ell_s; a free slot holds (0,0)(0, 0). Let SS be the set of live slots, G=e−4−4nG = e - 4 - 4n the gap and F=p−4−4n−∑s∈SℓsF = p - 4 - 4n - \sum_{s \in S} \ell_s the total free space. The invariant is:

  1. 4+4n≤e≤p4 + 4n \le e \le p.
  2. For s∈Ss \in S, e≤ose \le o_s and os+ℓs≤po_s + \ell_s \le p, and the intervals [os,os+ℓs)[o_s, o_s + \ell_s) for s∈Ss \in S are pairwise disjoint.
  3. n=0n = 0 or n−1∈Sn - 1 \in S.
  4. For s∈Ss \in S, the bytes at [os,os+ℓs)[o_s, o_s + \ell_s) are the record last stored in slot ss.

Let MM be the abstract map from slots to records. We also claim:

  1. SS is the domain of MM, and for s∈Ss \in S, get(s) returns M(s)M(s).

Lemma 1. If the invariant holds, then G≤FG \le F, and G=FG = F when the live records fill [e,p)[e, p) with no holes.

Proof. By part 2 the live intervals are disjoint subsets of [e,p)[e, p), so ∑s∈Sℓs≤p−e\sum_{s \in S} \ell_s \le p - e, which gives F=p−4−4n−∑ℓs≥e−4−4n=GF = p - 4 - 4n - \sum \ell_s \ge e - 4 - 4n = G. Equality holds exactly when the intervals cover [e,p)[e, p). □\square

Lemma 2 (COMPACT). If the invariant holds before COMPACT, it holds after it, MM does not change, SS and nn do not change, and afterwards G=FG = F.

Proof. Let s1,…,sks_1, \ldots, s_k be the live slots in the order of line L13, so os1≥os2≥⋯≥osko_{s_1} \ge o_{s_2} \ge \cdots \ge o_{s_k}. Two offsets can be equal only if one of the records has length 0; such a record occupies no byte, and the argument below holds for any order among equal offsets. Let e0′=pe'_0 = p and ei′=ei−1′−ℓsie'_i = e'_{i-1} - \ell_{s_i}, the value of e′e' after the ii-th pass of the loop.

First, ei′≥osie'_i \ge o_{s_i} for each ii. The records s1,…,si−1s_1, \ldots, s_{i-1} have offsets above osio_{s_i}, and by disjointness their intervals lie in [osi+ℓsi,p)[o_{s_i} + \ell_{s_i}, p). So ∑j<iℓsj≤p−osi−ℓsi\sum_{j < i} \ell_{s_j} \le p - o_{s_i} - \ell_{s_i}, and ei′=p−∑j≤iℓsj≥osie'_i = p - \sum_{j \le i} \ell_{s_j} \ge o_{s_i}.

Second, the move at line L17 of record sis_i writes [ei′,ei−1′)[e'_i, e'_{i-1}). The records not moved yet, si+1,…,sks_{i+1}, \ldots, s_k, lie below osi≤ei′o_{s_i} \le e'_i, so the write does not touch them. The records moved before lie in [ei−1′,p)[e'_{i-1}, p), which is also not touched. The source [osi,osi+ℓsi)[o_{s_i}, o_{s_i} + \ell_{s_i}) may overlap the target, but a memory move copies the bytes as they were before the move (the implementation copies the source slice first). So after the pass, slot sis_i points to its own bytes, and the other moved records keep theirs. This gives part 4 after the loop.

After the loop the live records are the intervals [ei′,ei−1′)[e'_i, e'_{i-1}), which are disjoint and cover [ek′,p)[e'_k, p), and line L19 sets e=ek′e = e'_k. This gives part 2 and, by Lemma 1, G=FG = F. Since F≥0F \ge 0, we have e≥4+4ne \ge 4 + 4n, which is part 1. The directory length nn and the set SS do not change, which gives part 3 and part 5. □\square

Lemma 3 (INSERT). If the invariant holds before INSERT(r)(r) and need≤Fneed \le F, then INSERT returns a slot s∉Ss \notin S, after it M′=M∪{s↦r}M' = M \cup \{s \mapsto r\}, and the invariant holds. If need>Fneed > F, INSERT fails and changes nothing.

Proof. Line L1 picks ss, the least free slot or nn, so s∉Ss \notin S. Line L2 sets need=∣r∣+4[s=n]need = |r| + 4[s = n]. If need>Fneed > F, the test at line L4 fails before any write; note that need>F≥Gneed > F \ge G, so line L3 is true and line L4 is reached. Otherwise, after lines L3 to L5, G≥needG \ge need: either G≥needG \ge need already, or COMPACT ran, which by Lemma 2 keeps the invariant and MM and makes G=F≥needG = F \ge need.

Line L6 writes rr at [e−∣r∣,e)[e - |r|, e) and lowers ee by ∣r∣|r|. Since G≥need≥∣r∣G \ge need \ge |r|, the new interval lies above 4+4n4 + 4n, so it overlaps no slot entry, and it lies below every live record, so it is disjoint from them. If s=ns = n, line L7 grows the directory to n+1n + 1 entries, whose end 4+4(n+1)4 + 4(n + 1) is at most the new ee because G≥∣r∣+4G \ge |r| + 4. Line L8 sets slot ss. So part 1 holds, part 2 holds since the new interval is disjoint from the others, and part 3 holds since slot n−1n - 1 is either the old last live slot or ss itself. Part 4 holds for ss by the write at line L6 and for the other slots because their bytes and entries did not change. □\square

Lemma 4 (DELETE). If the invariant holds and s∈Ss \in S, after DELETE(s)(s) the invariant holds and M′=MM' = M without ss.

Proof. Line L10 marks ss free, which removes it from SS. Removing an interval keeps part 2 and part 4, and ee does not change. Lines L11 and L12 lower nn until slot n−1n - 1 is live or n=0n = 0, which gives part 3; only free entries are dropped, so SS loses nothing more, and a smaller nn keeps part 1. □\square

Lemma 5 (UPDATE). If the invariant holds and s∈Ss \in S, then UPDATE(s,r)(s, r) either sets M(s)=rM(s) = r with the same slot ss and keeps the invariant, or fails without a change. It fails if and only if ∣r∣−ℓs>F|r| - \ell_s > F.

Proof. If ∣r∣≤ℓs|r| \le \ell_s, the record is written over the start of its own interval, and the new interval [os,os+∣r∣)[o_s, o_s + |r|) is contained in the old one, so the invariant holds. Otherwise, the record grows by d=∣r∣−ℓs>0d = |r| - \ell_s > 0. If d>Fd > F, UPDATE fails before any write. If not, and ∣r∣≤G|r| \le G, the record is written at the free end as in Lemma 3 (no new slot entry is needed, and the old interval simply becomes a hole). If ∣r∣>G|r| > G, slot ss is marked free for the moment, so the total free space becomes F+ℓs≥∣r∣F + \ell_s \ge |r|, and COMPACT makes G=F+ℓs≥∣r∣G = F + \ell_s \ge |r| by Lemma 2, without touching nn. The record is then written at the free end and slot ss points to it. In both cases only slot ss changes, and part 3 holds because nn did not change and ss is live again. □\square

Theorem. Starting from the empty page, after any sequence of operations the invariant holds, get returns the abstract map MM, a slot returned by INSERT names the same record until it is deleted (whatever compactions and updates of other slots happen in between), and INSERT fails if and only if ∣r∣+4[no slot is free]>F|r| + 4[\text{no slot is free}] > F.

Proof. The empty page has n=0n = 0 and e=pe = p, so the invariant holds with M=∅M = \emptyset. Each operation keeps it and changes MM as its abstract specification says, by Lemmas 2 to 5. A slot ss leaves SS only at line L10, which runs only on DELETE(s)(s), and no lemma changes the record of a slot other than the one the operation names. The failure condition is Lemma 3, with needneed written out. □\square

Running time. Line L1 scans at most nn entries. COMPACT sorts at most nn live slots and moves at most p−e′≤pp - e' \le p bytes. Lines L11 and L12 remove each slot entry at most once after it was added, and each entry was added by one INSERT, so over a sequence of operations their total work is at most the number of inserts, which gives O(1)O(1) amortized time per DELETE.

Complexity

The costs are CPU work on a page that is already in memory, in the word RAM with byte moves counted one per byte. The page I/O is the business of the buffer pool.

operation time
get O(1)O(1)
delete O(1)O(1) amortized; the trailing free slots are removed once each
insert without compaction O(n+r)O(n + r): the scan for a free slot and the copy
compact O(nlog⁡n+p)O(n \log n + p): the sort of the live slots and at most pp bytes moved
insert with compaction O(nlog⁡n+p)O(n \log n + p)

The scan at line L1 becomes O(1)O(1) if the free slots are kept in a free list or a bitmap, and the sort at line L13 is not needed if records are compacted in slot order into a second buffer of pp bytes. The space overhead is the header and 4 bytes per slot. A free slot keeps its 4 bytes until it is reused or is at the end of the directory.

Variants

  • Fixed-length records. When all records have the same length, slot ss can be the ss-th record position, and a bitmap marks the used positions. No offsets are needed. Ramakrishnan and Gehrke call the version that keeps records packed at the start "packed", and the version with a bitmap "unpacked"; only the unpacked version keeps record ids stable after a delete.
  • Forwarding addresses. When an updated record no longer fits, it moves to another page and its old slot keeps the new record id. A lookup then follows one extra pointer, and the original record id stays valid. If the record moves again, the system updates the first slot and does not make a chain.
  • Item identifiers with flags. PostgreSQL keeps a 24-byte page header, then an array of 4-byte item identifiers (offset, length and a state of unused, normal, redirect or dead), then free space, then the tuples, and an optional special space at the very end for index pages. The redirect state works as a forwarding address inside the page.
  • Slots in key order. In the nodes of a B+ tree, such as SQLite b-tree pages, the array of cell pointers is kept sorted by key, so a binary search runs on the slots. An insert then shifts the pointers after it, and the slot number is no longer a stable id. The index finds a record by key, not by slot.
  • Column layouts. PAX keeps the slotted idea for variable-length values but splits the record area of the page into one minipage per attribute. The N-ary storage model is the layout of whole records in slotted pages.

When to use it

Use a slotted page for any page that stores records of variable length and is pointed to by record ids: the pages of a heap file, of a table that secondary indexes point into, and of the overflow pages of hash tables. Use the fixed-length variant when all records have the same size, since it needs no offsets. Inside index nodes, keep the slots in key order and do not hand out slot numbers as ids.

Pitfalls

  • Reuse of a slot too early. If slot ss of a deleted record is reused while an index still holds (page, ss), the index now points to a different record. Remove the index entries before the slot is reused, or mark the slot dead and free it only after a cleanup pass.
  • Compaction under a reader. Compaction moves bytes, so a thread that holds a pointer into the page sees garbage. The page needs an exclusive latch that waits until no one else has the page pinned, as with the cleanup lock of PostgreSQL.
  • Free slots at the end. Without lines L11 and L12, a page whose last records were deleted keeps their slot entries forever, and the gap never recovers those bytes.
  • Two kinds of free space. A test for room that uses only the gap rejects records that would fit after compaction. A test that uses only the total free space forgets the 4 bytes of a new slot entry.
  • Offset width. Offsets of 2 bytes limit a page to 64 KB. The offset 0 is a good marker of a free slot only because the header is at offset 0.
  • A record bigger than a page. Such a record must be split, or moved out of line into overflow pages, with a pointer in the slotted page.

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.

slotted_page.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slotted-page/. The authors are listed in prov/C42FG6.jsonl.

"""A slotted page of P bytes, kept as a real bytearray.

Layout (all integers are 2-byte little-endian):

    offset 0          n_slots     the length of the slot directory
    offset 2          free_end    the first byte of the record area
    offset 4 + 4 s    slot s      (offset, length) of the record of slot s

The slot directory grows from the start of the page, and the records grow
from the end of the page toward it. A slot with offset 0 is free: no record
can start at offset 0, because the header is there. A record id is the pair
(page id, slot); the page does not store its own id.
"""

import struct
from typing import Dict, List, Optional, Tuple

HEADER = 4
SLOT = 4


class PageFull(Exception):
    """The page does not have enough free space, even after compaction."""


class SlottedPage:
    def __init__(self, size: int = 4096) -> None:
        if not HEADER + SLOT <= size <= 65535:
            raise ValueError("page size must be between 8 and 65535 bytes")
        self.size = size
        self.data = bytearray(size)
        self._set_header(0, size)
        self.compactions = 0

    # ------------------------------------------------------------ header and slots

    def _header(self) -> Tuple[int, int]:
        return struct.unpack_from("<HH", self.data, 0)

    def _set_header(self, n_slots: int, free_end: int) -> None:
        struct.pack_into("<HH", self.data, 0, n_slots, free_end)

    def _slot(self, s: int) -> Tuple[int, int]:
        return struct.unpack_from("<HH", self.data, HEADER + SLOT * s)

    def _set_slot(self, s: int, offset: int, length: int) -> None:
        struct.pack_into("<HH", self.data, HEADER + SLOT * s, offset, length)

    @property
    def n_slots(self) -> int:
        return self._header()[0]

    @property
    def free_end(self) -> int:
        return self._header()[1]

    def live_slots(self) -> List[int]:
        return [s for s in range(self.n_slots) if self._slot(s)[0] != 0]

    def contiguous_free(self) -> int:
        """Bytes between the end of the slot directory and the first record."""
        n, end = self._header()
        return end - (HEADER + SLOT * n)

    def total_free(self) -> int:
        """Bytes that compaction can make contiguous: P - header - slots - live records."""
        n, _ = self._header()
        used = sum(self._slot(s)[1] for s in self.live_slots())
        return self.size - HEADER - SLOT * n - used

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

    def get(self, s: int) -> Optional[bytes]:
        """The record of slot s, or None if the slot is free or does not exist."""
        if s < 0 or s >= self.n_slots:
            return None
        off, length = self._slot(s)
        if off == 0:
            return None
        return bytes(self.data[off:off + length])

    def insert(self, rec: bytes) -> int:
        """Store rec and return its slot number. Raise PageFull if it cannot fit."""
        n, _ = self._header()
        s = next((t for t in range(n) if self._slot(t)[0] == 0), n)  # @line L1
        need = len(rec) + (SLOT if s == n else 0)                     # @line L2
        if need > self.contiguous_free():                             # @line L3
            if need > self.total_free():                              # @line L4
                raise PageFull(f"need {need} bytes, {self.total_free()} free")  # @line L4
            self.compact()                                            # @line L5
        n, end = self._header()
        end -= len(rec)                                               # @line L6
        self.data[end:end + len(rec)] = rec                           # @line L6
        if s == n:                                                    # @line L7
            n += 1                                                    # @line L7
        self._set_header(n, end)
        self._set_slot(s, end, len(rec))                              # @line L8
        return s                                                      # @line L9

    def delete(self, s: int) -> None:
        """Free slot s. Its bytes become a hole that compaction reclaims."""
        if self.get(s) is None:
            raise KeyError(s)
        self._set_slot(s, 0, 0)                                       # @line L10
        n, end = self._header()
        while n > 0 and self._slot(n - 1)[0] == 0:                    # @line L11
            n -= 1                                                    # @line L12
        self._set_header(n, end)

    def compact(self) -> None:
        """Move all live records to the end of the page, with no holes between them."""
        self.compactions += 1
        n, _ = self._header()
        live = sorted(((self._slot(s)[0], s) for s in self.live_slots()), reverse=True)  # @line L13
        end = self.size                                               # @line L14
        for off, s in live:                                           # @line L15
            length = self._slot(s)[1]
            end -= length                                             # @line L16
            self.data[end:end + length] = self.data[off:off + length]  # @line L17
            self._set_slot(s, end, length)                            # @line L18
        self._set_header(n, end)                                      # @line L19

    def update(self, s: int, rec: bytes) -> None:
        """Replace the record of slot s. The slot, so the record id, stays the same."""
        old = self.get(s)
        if old is None:
            raise KeyError(s)
        off, length = self._slot(s)
        if len(rec) <= length:
            # shrink in place; the tail of the old record becomes a hole
            self.data[off:off + len(rec)] = rec
            self._set_slot(s, off, len(rec))
            return
        if len(rec) - length > self.total_free():
            raise PageFull("the record must move to another page")
        if len(rec) > self.contiguous_free():
            self._set_slot(s, 0, 0)       # the old bytes are garbage now
            self.compact()
        n, end = self._header()
        end -= len(rec)
        self.data[end:end + len(rec)] = rec
        self._set_header(n, end)
        self._set_slot(s, end, len(rec))

    def records(self) -> Dict[int, bytes]:
        return {s: self.get(s) for s in self.live_slots()}

    def check(self) -> None:
        """Raise AssertionError if the layout invariant does not hold."""
        n, end = self._header()
        dir_end = HEADER + SLOT * n
        assert dir_end <= end <= self.size
        assert n == 0 or self._slot(n - 1)[0] != 0, "a trailing slot is free"
        spans = []
        for s in range(n):
            off, length = self._slot(s)
            if off == 0:
                assert length == 0
                continue
            assert end <= off and off + length <= self.size
            spans.append((off, off + length))
        spans.sort()
        for (a, b), (c, d) in zip(spans, spans[1:]):
            assert b <= c, "two records overlap"
test_slotted_page.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slotted-page/. The authors are listed in prov/C42FG6.jsonl.

import random
import unittest

from slotted_page import HEADER, SLOT, PageFull, SlottedPage


class TestSlottedPage(unittest.TestCase):
    def test_empty_page(self):
        p = SlottedPage(64)
        self.assertEqual(p.n_slots, 0)
        self.assertEqual(p.free_end, 64)
        self.assertEqual(p.contiguous_free(), 64 - HEADER)
        self.assertIsNone(p.get(0))
        p.check()

    def test_layout_grows_from_both_ends(self):
        p = SlottedPage(64)
        a = p.insert(b"aaaaaaaaaa")
        b = p.insert(b"bbbbbb")
        self.assertEqual((a, b), (0, 1))
        self.assertEqual(p._slot(0), (54, 10))
        self.assertEqual(p._slot(1), (48, 6))
        self.assertEqual(p.free_end, 48)
        self.assertEqual(p.contiguous_free(), 48 - HEADER - 2 * SLOT)

    def test_worked_example(self):
        # The example on the page: P = 64, three inserts, a delete, a reuse, a compaction.
        p = SlottedPage(64)
        p.insert(b"A" * 10)
        p.insert(b"B" * 6)
        p.insert(b"C" * 12)
        self.assertEqual(p.free_end, 36)
        self.assertEqual(p.contiguous_free(), 20)
        p.delete(1)
        self.assertEqual(p.n_slots, 3)
        self.assertEqual(p.total_free(), 26)
        self.assertEqual(p.contiguous_free(), 20)
        s = p.insert(b"D" * 24)
        self.assertEqual(s, 1)
        self.assertEqual(p.compactions, 1)
        self.assertEqual(p._slot(0), (54, 10))
        self.assertEqual(p._slot(2), (42, 12))
        self.assertEqual(p._slot(1), (18, 24))
        self.assertEqual(p.contiguous_free(), 2)
        self.assertEqual(p.get(0), b"A" * 10)
        self.assertEqual(p.get(2), b"C" * 12)
        p.check()

    def test_trailing_free_slots_are_dropped(self):
        p = SlottedPage(128)
        for i in range(4):
            p.insert(bytes([i]) * 5)
        p.delete(1)
        p.delete(3)
        self.assertEqual(p.n_slots, 3)
        p.delete(2)
        self.assertEqual(p.n_slots, 1)
        p.check()

    def test_page_full(self):
        p = SlottedPage(32)
        p.insert(b"x" * 20)
        with self.assertRaises(PageFull):
            p.insert(b"y" * 5)
        self.assertEqual(p.records(), {0: b"x" * 20})
        self.assertEqual(p.insert(b""), 1)
        self.assertEqual(p.contiguous_free(), 0)
        p.check()

    def test_delete_missing(self):
        p = SlottedPage(64)
        with self.assertRaises(KeyError):
            p.delete(0)
        p.insert(b"a")
        p.delete(0)
        with self.assertRaises(KeyError):
            p.delete(0)

    def test_update_keeps_slot(self):
        p = SlottedPage(64)
        p.insert(b"a" * 10)
        p.insert(b"b" * 10)
        p.insert(b"c" * 10)
        p.update(1, b"B" * 3)
        self.assertEqual(p.get(1), b"B" * 3)
        p.update(1, b"Z" * 20)
        self.assertEqual(p.get(1), b"Z" * 20)
        self.assertEqual(p.records(), {0: b"a" * 10, 1: b"Z" * 20, 2: b"c" * 10})
        with self.assertRaises(PageFull):
            p.update(0, b"q" * 40)
        self.assertEqual(p.get(0), b"a" * 10)
        p.check()

    def test_random_against_dict(self):
        for seed in range(30):
            rng = random.Random(seed)
            size = rng.choice([64, 128, 256, 1024])
            p = SlottedPage(size)
            oracle = {}
            for _ in range(400):
                op = rng.random()
                if op < 0.45:
                    rec = bytes(rng.randrange(256) for _ in range(rng.randrange(0, size // 6)))
                    before = p.total_free()
                    free_slot = any(p.get(t) is None for t in range(p.n_slots))
                    need = len(rec) + (0 if free_slot else SLOT)
                    try:
                        s = p.insert(rec)
                    except PageFull:
                        self.assertGreater(need, before)
                        continue
                    self.assertLessEqual(need, before)
                    self.assertNotIn(s, oracle)
                    self.assertEqual(s, min(set(range(len(oracle) + 1)) - set(oracle)))
                    oracle[s] = rec
                elif op < 0.75 and oracle:
                    s = rng.choice(sorted(oracle))
                    p.delete(s)
                    del oracle[s]
                elif op < 0.95 and oracle:
                    s = rng.choice(sorted(oracle))
                    rec = bytes(rng.randrange(256) for _ in range(rng.randrange(0, size // 5)))
                    grow = len(rec) - len(oracle[s])
                    before = p.total_free()
                    try:
                        p.update(s, rec)
                    except PageFull:
                        self.assertGreater(grow, before)
                        continue
                    oracle[s] = rec
                else:
                    p.compact()
                    self.assertEqual(p.contiguous_free(), p.total_free())
                p.check()
                self.assertEqual(p.records(), oracle)
                used = sum(len(r) for r in oracle.values())
                self.assertEqual(p.total_free(), size - HEADER - SLOT * p.n_slots - used)
                self.assertEqual(p.n_slots, max(oracle) + 1 if oracle else 0)


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

History

The layout is part of relational practice from the early systems on, and it appears in the standard texts: Gray and Reuter (1993) in their tuple-oriented file system, Ramakrishnan and Gehrke in their chapter on storing data, and Hellerstein, Stonebraker and Hamilton (2007) in their survey of the architecture of database systems. Ailamaki, DeWitt, Hill and Skounakis (2001) describe the standard row layout as "a.k.a., slotted pages" when they introduce PAX. Today PostgreSQL heap pages and SQLite b-tree pages are slotted pages, and Petrov (2019) explains the layout as the base of the page formats of storage engines.

References

  1. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, third edition, McGraw-Hill (2003), Chapter 9 (storing data: disks and files), the sections on page formats for fixed-length and variable-length records
  2. Architecture of a database system, the section on storage management
  3. Alex Petrov, Database Internals, O'Reilly (2019), the chapter on file formats, the section on slotted pages and cell layout
  4. Jim Gray and Andreas Reuter, Transaction Processing, Concepts and Techniques, Morgan Kaufmann (1993), the chapter on the tuple-oriented file system, page and tuple layout
  5. PostgreSQL documentation, Database page layout, the page header, the array of item identifiers and the tuples at the end of the page

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
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/C42FG6/text.yaml