Algorithm Search⌘K

Data structureintro

Heap file

Also called unordered file, heap-organized table.

An unordered file of records in pages, with a page directory or two linked lists to find free space. It is the default storage of a table.

Space
⌈N/D⌉ extra
Counts
io N + ⌈N/D⌉ worst · average
Where
D = the number of entries in one directory page; F = the number of pages on the free list; N = the number of data pages

A heap file stores the records of a table in pages, in no particular order. A record goes into any page that has room, and a record id (page id, slot) names it for as long as it exists. The only extra structure is the one that finds a page with free space: a page directory, with one entry (page id, free bytes) per page, or two linked lists of pages, one of the pages with free space and one of the full pages. Inside each page the records are kept in a slotted page; the slotted page is about the layout of one page, and the heap file is about how a table is spread over many pages. A heap file supports a full scan and an access by record id; any search on a value needs a scan or an index such as a B+ tree.

In plain words

A heap file is a stack of pages with records in them, in the order they happened to arrive. Nothing keeps them sorted. To find a record by its address, "page 12, slot 3", you go straight to page 12. To find a record by a value, you read every page, unless an index tells you where to look.

When you add a record, you need a page with enough room. One way is to keep a short list of all pages with the free room on each, and look it up. The other way is to keep the pages that still have room in a chain, and walk the chain until one is big enough.

The abstract type

A heap file is a bag of records with ids.

  • insert(H, r): store record rr in some page and return its record id.
  • get(H, rid): the record with id ridrid.
  • delete(H, rid): remove the record.
  • scan(H): every record with its id, each once, in some order.

The file gives no order, and an insert may go to any page with room. Updates are a delete and an insert in the worst case, or an update in place inside the slotted page; a record that grows out of its page keeps its id through a forwarding address, as on the slotted page.

Representation

The data pages have ids 0,1,…,N−10, 1, \ldots, N - 1. A record of ℓ\ell bytes costs ℓ+4\ell + 4 bytes of its page: the bytes and a slot entry.

Page directory. A chain of directory pages, each with up to DD entries (page id, free bytes). The entries are in page id order, so the entry of page qq is entry q mod Dq \bmod D of directory page ⌊q/D⌋\lfloor q / D \rfloor. The first directory page is at a known place, often the header page of the file, so an empty file still has one directory page. The invariant is that the entry of every page holds its exact free space, and every data page has one entry.

Linked lists. A header page holds the heads of two doubly linked lists. Each data page holds a pointer to the page before it and to the page after it on its list. A page is on the full list if its free space is below a limit mm, and on the free list otherwise. The invariant is that every data page is on exactly one list, the one its free space calls for.

The directory costs ⌈N/D⌉\lceil N / D \rceil extra pages; with entries of 8 bytes in 4 KB pages, DD is about 500, so a directory page covers 2 MB of data. The lists cost two pointers in each data page and one header page.

Operations

  1. DIR-INSERT(H, r) ▷ page directory form
  2. 1for each directory page j, in order do
  3. 2read directory page j
  4. 3for each entry (q, f) of page j do
  5. 4if f ≥ |r| + 4 then
  6. 5read page q; put r in q at slot s
  7. 6write page q
  8. 7f ← the free space of q; write directory page j
  9. 8return (q, s)
  10. 9q ← a new page id; put r in a new page q at slot s
  11. 10write page q
  12. 11if the last directory page has D entries then
  13. 12add a new directory page and link the old last page to it
  14. 13append (q, the free space of q) to the last directory page; write it
  15. 14return (q, s)
  16. DIR-SCAN(H)
  17. 15for each directory page j, in order do
  18. 16read directory page j
  19. 17for each entry (q, f) of page j do
  20. 18read page q
  21. 19for each live slot s of q do
  22. 20output ((q, s), the record of slot s)
  23. GET(H, (q, s))
  24. 21read page q; return the record of slot s
  25. LIST-INSERT(H, r) ▷ linked list form, limit m
  26. 22read the header page; q ← the head of the free list
  27. 23while q ≠ nil do
  28. 24read page q
  29. 25if |r| + 4 ≤ free(q) then
  30. 26put r in q at slot s; write page q
  31. 27if free(q) < m then
  32. 28unlink q from the free list; push q on the full list
  33. 29return (q, s)
  34. 30q ← next(q)
  35. 31q ← a new page id; put r in a new page q at slot s
  36. 32push q on the free list, or on the full list if free(q) < m
  37. 33return (q, s)

A delete reads the page of the record, frees the slot and writes the page. With a directory, it also reads and writes the directory page of that page, to update its free space. With the lists, a page that was full and now has mm or more free bytes moves back to the free list. A move between lists changes the pointers of the page, its old neighbors, the old head of the other list, and the header.

A scan of the list form reads the header page and walks the full list and then the free list. It visits each data page once, because each page is on exactly one list.

Example

Take pages of 100 bytes and a directory with D=2D = 2 entries per page. Insert records of 56, 46, 36, 26 and 26 bytes; they cost 60, 50, 40, 30 and 30 bytes of a page.

step goes to directory after the step reads writes
insert 56 new page 0, slot 0 (0, 40) 1 2
insert 46 new page 1, slot 0 (0, 40) (1, 50) 1 2
insert 36 page 0, slot 1 (0, 0) (1, 50) 2 2
insert 26 page 1, slot 1 (0, 0) (1, 20) 2 2
insert 26 new page 2, slot 0 (0, 0) (1, 20) / (2, 70) 1 3
delete (1, 0) (0, 0) (1, 70) / (2, 70) 2 2
insert 30 page 1, slot 0 (0, 0) (1, 36) / (2, 70) 2 2

The slash separates the two directory pages. The fifth insert finds no page with 30 free bytes, makes page 2, and needs a second directory page, so it writes the new data page and both directory pages. The last insert reuses slot 0 of page 1, so the new record has the id of the deleted one; an index must not still hold that id (see the pitfalls). A scan now reads 2 directory pages and 3 data pages.

With linked lists and m=20m = 20, the same five inserts end with pages 0 and 1 on the full list (free space 10 each) and page 2 on the free list. Here the third insert goes to page 1, the head of the free list, and not to page 0, so the record ids differ from the directory form. After the delete of (1, 0), page 1 has 60 free bytes and moves back to the head of the free list. A scan reads the header and 3 data pages.

Correctness

Each record is in exactly one slot of one page, and its id is the place of that slot, which does not change while the record exists. So get finds it with one read and scan returns it once, provided that the scan visits each data page once. With a directory, the scan visits the pages of the entries, and each data page has exactly one entry. With the lists, the scan visits the pages of the two lists, and each data page is on exactly one list.

DIR-INSERT keeps the directory exact: line L7 writes the new free space of the page that took the record, and line L13 adds the entry of a new page. It puts a record in an existing page only if the entry shows enough free space, and since the entry is exact, the record fits. LIST-INSERT does the same with the free space stored in the page itself, and lines L27 and L28 keep each page on the list that its free space calls for. The full proof is below.

Proof: Both forms of the heap file keep their free space structure exact, and their operations have the stated page I/O costsfull

We use the notation of the page. The data pages are 0,…,N−10, \ldots, N - 1. Each page qq is a slotted page with free space free(q)free(q), and a record rr fits in qq when ∣r∣+4≤free(q)|r| + 4 \le free(q). We treat the slotted page as correct (see its own page): inside one page, insert, get and delete behave as a map from slots to records, and a slot keeps its record until that record is deleted. Let MM be the abstract map from record ids to records.

The page directory form

Invariant D. (a) The directory pages hold, in order, exactly one entry for each data page, in page id order. (b) Every directory page except the last has DD entries. (c) The entry of page qq is (q,free(q))(q, free(q)).

By (a) and (b), the entry of page qq is entry q mod Dq \bmod D of directory page ⌊q/D⌋\lfloor q / D \rfloor, and there are max⁡(1,⌈N/D⌉)\max(1, \lceil N / D \rceil) directory pages.

Lemma 1. DIR-INSERT keeps Invariant D, returns a record id not in MM, and adds rr under that id. If q∗q^\ast is the least page id with ∣r∣+4≤free(q∗)|r| + 4 \le free(q^\ast), the record goes to q∗q^\ast, at a cost of ⌊q∗/D⌋+2\lfloor q^\ast / D \rfloor + 2 reads and 2 writes. If there is no such page, the record goes to the new page NN, at a cost of max⁡(1,⌈N/D⌉)\max(1, \lceil N / D \rceil) reads and 2 writes, or 3 if the last directory page had DD entries.

Proof. Lines L1 to L4 visit the entries in page id order, by (a), and stop at the first entry whose free value is at least ∣r∣+4|r| + 4. By (c) the value is free(q)free(q), so the loop stops at q∗q^\ast. The record fits in q∗q^\ast, and the slotted page returns a slot ss that no live record of q∗q^\ast uses, so (q∗,s)∉M(q^\ast, s) \notin M. Line L7 writes the new free space, which restores (c) for q∗q^\ast; no other entry changes. The reads are the directory pages 00 to ⌊q∗/D⌋\lfloor q^\ast / D \rfloor and the page q∗q^\ast, and the writes are q∗q^\ast and its directory page.

If the loop finds no page, every directory page was read. Line L9 makes page NN, which is empty, so the record fits (a record larger than an empty page is rejected before the insert). Lines L11 to L13 append the entry (N,free(N))(N, free(N)) after the entry of N−1N - 1, in a new directory page if the last one was full. This keeps (a), (b) and (c). The writes are page NN and the last directory page, plus the old last page when a new directory page is linked to it. □\square

Lemma 2. A delete of (q,s)∈M(q, s) \in M keeps Invariant D, removes (q,s)(q, s) from MM, and costs 2 reads and 2 writes.

Proof. The delete reads page qq, frees slot ss and writes qq. It then reads directory page ⌊q/D⌋\lfloor q / D \rfloor, sets the entry of qq to the new free(q)free(q), and writes the page. Only the entry of qq changes, and it becomes exact. □\square

Lemma 3. If Invariant D holds, DIR-SCAN outputs each pair of MM exactly once and reads N+max⁡(1,⌈N/D⌉)N + \max(1, \lceil N / D \rceil) pages.

Proof. Lines L15 to L18 read every directory page once and, by (a), every data page once. Line L19 lists the live slots of each page once. Every record id (q,s)(q, s) in MM has q<Nq < N and ss live in qq, so it is output once, and nothing else is output. □\square

The linked list form

Invariant L. (a) Every data page is on exactly one of the two lists, and the lists are doubly linked: if q′q' follows qq then prev(q′)=qprev(q') = q, and the head has no predecessor. (b) A page is on the full list if and only if free(q)<mfree(q) < m.

Lemma 4. LIST-INSERT keeps Invariant L, and adds rr under a new record id. If the first page of the free list, in list order, in which rr fits is the kk-th one, the record goes there. If that page stays on the free list, the cost is k+1k + 1 reads and 1 write. If there is no such page, the cost is at most F+2F + 2 reads and 3 writes, where FF is the length of the free list.

Proof. Lines L22 to L30 read the header and then the pages of the free list in order, and stop at the first page qq where rr fits. The slotted page gives a new slot. If free(q)free(q) is still at least mm, the lists do not change and (b) still holds for qq. The pages read are the header and the first kk pages of the list, and the only write is qq. If free(q)free(q) drops below mm, line L28 unlinks qq (its predecessor, or the header, and its successor change their pointers) and pushes it at the head of the full list (the old head and the header change). Each changed page is written once, and each list stays doubly linked. Now qq is on the full list and free(q)<mfree(q) < m, so (b) holds.

If no page of the free list fits, all FF pages were read. Line L31 makes a new page with the record in it, and line L32 pushes it on the list that (b) calls for. The new reads are at most the old head of that list (which may already have been read, as the head of the free list), and the writes are the new page, the old head and the header. □\square

Lemma 5. A delete keeps Invariant L. It costs 1 read and 1 write, or at most 5 reads and 5 writes when the page moves from the full list to the free list.

Proof. The delete reads page qq, frees the slot and writes qq. Its free space grows. A page on the free list stays there, which (b) allows. A page on the full list that now has free(q)≥mfree(q) \ge m is unlinked from the full list and pushed on the free list, as in Lemma 4; this reads and writes at most the page, its two old neighbors, the old head of the free list and the header. □\square

Lemma 6. If Invariant L holds, a scan that reads the header and walks both lists outputs each pair of MM once and reads N+1N + 1 pages.

Proof. By (a), the two walks together visit each data page exactly once, and they stop at the ends of the lists. The rest is as in Lemma 3. □\square

Summary

Theorem. Starting from an empty file, after any sequence of insert, delete, get and scan, both forms keep their invariant; get(q, s) returns M((q,s))M((q, s)) with one read; scan outputs MM; and the page I/O of each operation is the one in the table of the page.

Proof. The empty directory form has one empty directory page and no data pages, which satisfies Invariant D; the empty list form has an empty header, which satisfies Invariant L. Lemmas 1 to 6 show that each operation keeps the invariant and changes MM as its specification says. A record id (q,s)(q, s) stays in MM until its delete, since no operation moves a record to another page or another slot, so get reads page qq once and finds the record in slot ss. □\square

The I/O counts assume that an operation reads each page it needs once and writes each page it changes once, which holds when it can keep the two or three pages it uses in buffer frames for its duration. The implementation counts I/O in exactly this way, and the tests compare its counts with the formulas of Lemmas 1 to 6 on random sequences.

Complexity

The costs count page reads and writes 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. Each operation here needs only two or three buffer pages, and the costs assume that no page is in the buffer pool when the operation starts. The costs do not count the output of a scan. They do not separate sequential and random I/O, but a scan of a directory file can read the data pages in page id order, which is sequential when the pages are contiguous on disk, while the list form reads them in list order.

operation page directory linked lists
scan N+⌈N/D⌉N + \lceil N/D \rceil reads N+1N + 1 reads
get 1 read 1 read
insert into page qq ⌊q/D⌋+2\lfloor q/D \rfloor + 2 reads, 2 writes k+1k + 1 reads and 1 write, if qq is the kk-th page of the free list and stays on it
insert into a new page ⌈N/D⌉\lceil N/D \rceil reads, 2 or 3 writes at most F+2F + 2 reads and 3 writes
delete 2 reads, 2 writes 1 read and 1 write, or at most 5 of each when the page changes lists

The search for free space is the weak point of both forms. The directory scans ⌈N/D⌉\lceil N/D \rceil pages in the worst case, which is small, since one directory page covers DD data pages. The free list can hold FF pages that each have a little free space but not enough for a large record, and an insert may read all of them. This is why systems prefer a directory or a separate free space map.

Ramakrishnan and Gehrke compare a heap file with sorted and hashed files in a simpler model, where the file has NN pages and inserts go to the last page. A scan costs NN page reads, a search for one record with a given key costs N/2N/2 reads on average, a search for a range costs NN reads, and an insert costs 2: read the last page and write it back. A sorted file finds one record in about log⁡2N\log_2 N reads, but an insert must move half of the file on average.

Variants

  • Free space map. PostgreSQL keeps the free space of each heap page in a separate file (a fork of the relation), organized as a small tree of pages, so that a search for a page with xx free bytes reads a few pages and not the whole directory. This is a directory with an index on its free space values.
  • Coarse free space classes. Some systems store only a few bits per page, a class of the free space (for example less than 25%, 25% to 50%, and so on), so that a directory page covers many more data pages.
  • Append only. A heap file that never reuses space puts every insert in the last page: one read and one write, and the scan reads the records in insert order. Deleted space comes back only when the file is rewritten. A log-structured merge tree builds on files of this kind.
  • Clustered and sorted files. A file kept in the order of a key is a sorted file or a clustered index. It answers range queries on that key with a short scan, and pays for it on insert.
  • Zone maps. A heap file in insert order often has values that are nearly sorted, such as dates. A zone map with the minimum and maximum of each page or block lets a scan skip pages without an index.

When to use it

Use a heap file as the base storage of a table when most access is by full scan or through secondary indexes that store record ids, and when inserts are frequent. It is the default table organization of most relational systems. Use the page directory when records vary in size, since a list walk can read many pages that are almost full. Use an append only heap for logs and other data that is written once. Use a sorted file or a clustered index when range queries on one key dominate.

Pitfalls

  • Slot reuse under an index. When a slot is reused, an old index entry with that record id points to a different record. Delete the index entries of a record before its slot can be reused.
  • A stale directory. The directory entry must change with the page. If the system crashes between the two writes, the entry can be wrong; recovery must log both changes, or treat the free space values as hints and check the page before it uses it.
  • Long free lists. A free list with many pages that each have a few free bytes makes inserts slow. Raise the limit mm, or use a directory.
  • Directory contention. Every insert reads and writes the directory, and every insert to the same page latches it. Concurrent inserts can spread over several insert points, or choose pages at random among those with room.
  • Search by value. A heap file has no order. A search on a value scans the whole file unless an index exists. A query plan that forgets this costs NN reads per lookup.

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.

heap_file.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heap-file/. The authors are listed in prov/FWEZG7.jsonl.

"""A heap file in its two classic forms, with a count of page reads and writes.

Data pages have ids 0, 1, 2, ... and hold records of variable length. A record
costs its length plus SLOT bytes of slot entry, and a record id is the pair
(page id, slot). The file finds pages with free space in one of two ways:

* DirectoryHeapFile keeps a chain of directory pages. Each directory page
  holds up to D entries (page id, free bytes), in page id order.
* ListHeapFile keeps a header page with the heads of two doubly linked lists:
  the pages with free space and the full pages. A page is full when it has
  fewer than `min_free` free bytes.

I/O is counted per operation: an operation reads each page it needs once and
writes each page it changes once, as if it had a few private buffer frames.
"""

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

SLOT = 4
Rid = Tuple[int, int]


class DataPage:
    def __init__(self, capacity: int) -> None:
        self.capacity = capacity
        self.slots: List[Optional[bytes]] = []
        self.free = capacity
        self.prev: Optional[int] = None  # list form only
        self.next: Optional[int] = None
        self.full = False

    def fits(self, rec: bytes) -> bool:
        return len(rec) + SLOT <= self.free

    def insert(self, rec: bytes) -> int:
        s = next((i for i, r in enumerate(self.slots) if r is None), len(self.slots))
        if s == len(self.slots):
            self.slots.append(rec)
        else:
            self.slots[s] = rec
        self.free -= len(rec) + SLOT
        return s

    def delete(self, s: int) -> None:
        rec = self.slots[s]
        if rec is None:
            raise KeyError(s)
        self.slots[s] = None
        self.free += len(rec) + SLOT


class _Op:
    """The pages one operation reads and writes."""

    def __init__(self) -> None:
        self.read: Set[object] = set()
        self.written: Set[object] = set()


class _Base:
    def __init__(self, capacity: int) -> None:
        self.capacity = capacity
        self.pages: List[DataPage] = []
        self.reads = 0
        self.writes = 0
        self._op: Optional[_Op] = None

    def _begin(self) -> None:
        self._op = _Op()

    def _end(self) -> Tuple[int, int]:
        r, w = len(self._op.read), len(self._op.written)
        self.reads += r
        self.writes += w
        self._op = None
        return r, w

    def _r(self, key: object) -> None:
        self._op.read.add(key)

    def _w(self, key: object) -> None:
        self._op.written.add(key)

    def _check_size(self, rec: bytes) -> None:
        if len(rec) + SLOT > self.capacity:
            raise ValueError("the record does not fit in an empty page")

    def get(self, rid: Rid) -> bytes:
        self._begin()
        pid, s = rid
        self._r(pid)                                   # @line L21
        page = self.pages[pid] if 0 <= pid < len(self.pages) else None
        rec = page.slots[s] if page is not None and 0 <= s < len(page.slots) else None
        self.last_io = self._end()
        if rec is None:
            raise KeyError(rid)
        return rec

    def n_pages(self) -> int:
        return len(self.pages)

    def records(self) -> Dict[Rid, bytes]:
        return {(pid, s): r for pid, p in enumerate(self.pages)
                for s, r in enumerate(p.slots) if r is not None}


class DirectoryHeapFile(_Base):
    """A heap file whose free space is kept in a chain of directory pages."""

    def __init__(self, capacity: int = 4096, entries_per_dir_page: int = 128) -> None:
        super().__init__(capacity)
        self.D = entries_per_dir_page
        # directory page j holds the entries of data pages j*D .. j*D + D - 1;
        # directory page 0 always exists, so an empty file has one page.
        self.directory: List[List[List[int]]] = [[]]

    def n_dir_pages(self) -> int:
        return len(self.directory)

    def insert(self, rec: bytes) -> Rid:
        self._check_size(rec)
        self._begin()
        need = len(rec) + SLOT
        for j, dpage in enumerate(self.directory):      # @line L1
            self._r(("dir", j))                         # @line L2
            for entry in dpage:                         # @line L3
                pid, free = entry
                if free >= need:                        # @line L4
                    self._r(pid)                        # @line L5
                    s = self.pages[pid].insert(rec)     # @line L5
                    self._w(pid)                        # @line L6
                    entry[1] = self.pages[pid].free     # @line L7
                    self._w(("dir", j))                 # @line L7
                    self.last_io = self._end()
                    return (pid, s)                     # @line L8
        pid = len(self.pages)                           # @line L9
        page = DataPage(self.capacity)
        s = page.insert(rec)
        self.pages.append(page)
        self._w(pid)                                    # @line L10
        if len(self.directory[-1]) == self.D:           # @line L11
            self._w(("dir", len(self.directory) - 1))   # @line L12  the old last page gets a next pointer
            self.directory.append([])                   # @line L12
        self.directory[-1].append([pid, page.free])     # @line L13
        self._w(("dir", len(self.directory) - 1))       # @line L13
        self.last_io = self._end()
        return (pid, s)                                 # @line L14

    def delete(self, rid: Rid) -> None:
        pid, s = rid
        self._begin()
        self._r(pid)
        self.pages[pid].delete(s)
        self._w(pid)
        j = pid // self.D
        self._r(("dir", j))
        self.directory[j][pid % self.D][1] = self.pages[pid].free
        self._w(("dir", j))
        self.last_io = self._end()

    def scan(self) -> Iterator[Tuple[Rid, bytes]]:
        self._begin()
        out = []
        for j, dpage in enumerate(self.directory):      # @line L15
            self._r(("dir", j))                         # @line L16
            for pid, _ in dpage:                        # @line L17
                self._r(pid)                            # @line L18
                for s, r in enumerate(self.pages[pid].slots):  # @line L19
                    if r is not None:
                        out.append(((pid, s), r))       # @line L20
        self.last_io = self._end()
        return iter(out)

    def check(self) -> None:
        flat = [e for d in self.directory for e in d]
        assert [pid for pid, _ in flat] == list(range(len(self.pages)))
        assert all(free == self.pages[pid].free for pid, free in flat)
        assert all(len(d) == self.D for d in self.directory[:-1])


class ListHeapFile(_Base):
    """A heap file with a header page and two doubly linked lists of data pages."""

    def __init__(self, capacity: int = 4096, min_free: int = 64) -> None:
        super().__init__(capacity)
        self.min_free = min_free
        self.head = {"free": None, "full": None}

    # The list moves below read and write the neighbours they change.

    def _unlink(self, pid: int) -> None:
        page = self.pages[pid]
        lst = "full" if page.full else "free"
        if page.prev is None:
            self.head[lst] = page.next
            self._w("hdr")
        else:
            self._r(page.prev)
            self.pages[page.prev].next = page.next
            self._w(page.prev)
        if page.next is not None:
            self._r(page.next)
            self.pages[page.next].prev = page.prev
            self._w(page.next)
        page.prev = page.next = None

    def _push(self, pid: int, full: bool) -> None:
        page = self.pages[pid]
        lst = "full" if full else "free"
        page.full = full
        old = self.head[lst]
        page.prev, page.next = None, old
        if old is not None:
            self._r(old)
            self.pages[old].prev = pid
            self._w(old)
        self.head[lst] = pid
        self._w("hdr")
        self._w(pid)

    def _is_full(self, page: DataPage) -> bool:
        return page.free < self.min_free

    def free_list(self) -> List[int]:
        out, p = [], self.head["free"]
        while p is not None:
            out.append(p)
            p = self.pages[p].next
        return out

    def full_list(self) -> List[int]:
        out, p = [], self.head["full"]
        while p is not None:
            out.append(p)
            p = self.pages[p].next
        return out

    def insert(self, rec: bytes) -> Rid:
        self._check_size(rec)
        self._begin()
        self._r("hdr")                                  # @line L22
        p = self.head["free"]
        while p is not None:                            # @line L23
            self._r(p)                                  # @line L24
            page = self.pages[p]
            if page.fits(rec):                          # @line L25
                s = page.insert(rec)                    # @line L26
                self._w(p)                              # @line L26
                if self._is_full(page):                 # @line L27
                    self._unlink(p)                     # @line L28
                    self._push(p, True)                 # @line L28
                self.last_io = self._end()
                return (p, s)                           # @line L29
            p = page.next                               # @line L30
        pid = len(self.pages)                           # @line L31
        page = DataPage(self.capacity)
        s = page.insert(rec)
        self.pages.append(page)
        self._push(pid, self._is_full(page))            # @line L32
        self.last_io = self._end()
        return (pid, s)                                 # @line L33

    def delete(self, rid: Rid) -> None:
        pid, s = rid
        self._begin()
        self._r(pid)
        page = self.pages[pid]
        page.delete(s)
        self._w(pid)
        if page.full and not self._is_full(page):
            self._r("hdr")
            self._unlink(pid)
            self._push(pid, False)
        self.last_io = self._end()

    def scan(self) -> Iterator[Tuple[Rid, bytes]]:
        self._begin()
        self._r("hdr")
        out = []
        for lst in ("full", "free"):
            p = self.head[lst]
            while p is not None:
                self._r(p)
                for s, r in enumerate(self.pages[p].slots):
                    if r is not None:
                        out.append(((p, s), r))
                p = self.pages[p].next
        self.last_io = self._end()
        return iter(out)

    def check(self) -> None:
        free, full = self.free_list(), self.full_list()
        assert sorted(free + full) == list(range(len(self.pages)))
        for lst in (free, full):
            for a, b in zip(lst, lst[1:]):
                assert self.pages[b].prev == a
            if lst:
                assert self.pages[lst[0]].prev is None
        assert all(not self.pages[p].full and not self._is_full(self.pages[p]) for p in free)
        assert all(self.pages[p].full and self._is_full(self.pages[p]) for p in full)
test_heap_file.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heap-file/. The authors are listed in prov/FWEZG7.jsonl.

import math
import random
import unittest

from heap_file import SLOT, DirectoryHeapFile, ListHeapFile


def rand_rec(rng, hi):
    return bytes(rng.randrange(256) for _ in range(rng.randrange(1, hi)))


class TestDirectoryHeapFile(unittest.TestCase):
    def test_worked_example(self):
        # The example on the page: pages of 100 bytes, D = 2 entries per directory page.
        h = DirectoryHeapFile(capacity=100, entries_per_dir_page=2)
        sizes = [56, 46, 36, 26, 26]
        ios = []
        rids = []
        for n in sizes:
            rids.append(h.insert(b"x" * n))
            ios.append(h.last_io)
        self.assertEqual(rids, [(0, 0), (1, 0), (0, 1), (1, 1), (2, 0)])
        self.assertEqual(ios, [(1, 2), (1, 2), (2, 2), (2, 2), (1, 3)])
        self.assertEqual([e for d in h.directory for e in d], [[0, 0], [1, 20], [2, 70]])
        self.assertEqual(h.n_dir_pages(), 2)
        h.delete((1, 0))
        self.assertEqual(h.last_io, (2, 2))
        self.assertEqual(h.directory[0][1], [1, 70])
        self.assertEqual(h.insert(b"y" * 30), (1, 0))
        self.assertEqual(h.last_io, (2, 2))
        self.assertEqual(h.directory[0][1], [1, 36])
        before = h.reads
        self.assertEqual(len(list(h.scan())), 5)
        self.assertEqual(h.reads - before, 2 + 3)

    def test_get_costs_one_read(self):
        h = DirectoryHeapFile(capacity=64, entries_per_dir_page=4)
        rid = h.insert(b"abc")
        self.assertEqual(h.get(rid), b"abc")
        self.assertEqual(h.last_io, (1, 0))
        with self.assertRaises(KeyError):
            h.get((0, 5))

    def test_record_too_big(self):
        h = DirectoryHeapFile(capacity=32)
        with self.assertRaises(ValueError):
            h.insert(b"z" * 29)
        h.insert(b"z" * 28)

    def test_random_against_oracle(self):
        for seed in range(12):
            rng = random.Random(seed)
            cap = rng.choice([64, 128, 256])
            d = rng.choice([1, 2, 3, 8])
            h = DirectoryHeapFile(capacity=cap, entries_per_dir_page=d)
            oracle = {}
            free = []  # the oracle's own record of free bytes per page
            for _ in range(300):
                if rng.random() < 0.65 or not oracle:
                    rec = rand_rec(rng, cap // 3)
                    need = len(rec) + SLOT
                    fit = next((p for p, f in enumerate(free) if f >= need), None)
                    last_full = len(h.directory[-1]) == d
                    rid = h.insert(rec)
                    if fit is None:
                        self.assertEqual(rid[0], len(free))
                        free.append(cap)
                        self.assertEqual(h.last_io, (h.n_dir_pages() - (1 if last_full else 0), 3 if last_full else 2))
                    else:
                        self.assertEqual(rid[0], fit)
                        self.assertEqual(h.last_io, (fit // d + 2, 2))
                    free[rid[0]] -= need
                    oracle[rid] = rec
                else:
                    rid = rng.choice(sorted(oracle))
                    h.delete(rid)
                    self.assertEqual(h.last_io, (2, 2))
                    free[rid[0]] += len(oracle.pop(rid)) + SLOT
                h.check()
            self.assertEqual(h.records(), oracle)
            n = h.n_pages()
            self.assertEqual(h.n_dir_pages(), max(1, math.ceil(n / d)))
            before = h.reads
            self.assertEqual(dict(h.scan()), oracle)
            self.assertEqual(h.reads - before, n + h.n_dir_pages())
            for rid, rec in oracle.items():
                self.assertEqual(h.get(rid), rec)


class TestListHeapFile(unittest.TestCase):
    def test_worked_example(self):
        h = ListHeapFile(capacity=100, min_free=20)
        sizes = [56, 46, 36, 26, 26]
        rids = [h.insert(b"x" * n) for n in sizes]
        self.assertEqual(rids, [(0, 0), (1, 0), (1, 1), (0, 1), (2, 0)])
        self.assertEqual(h.full_list(), [0, 1])
        self.assertEqual(h.free_list(), [2])
        h.delete((1, 0))
        self.assertEqual(h.full_list(), [0])
        self.assertEqual(h.free_list(), [1, 2])
        before = h.reads
        self.assertEqual(len(list(h.scan())), 4)
        self.assertEqual(h.reads - before, 1 + 3)

    def test_random_against_oracle(self):
        for seed in range(12):
            rng = random.Random(100 + seed)
            cap = rng.choice([64, 128, 256])
            h = ListHeapFile(capacity=cap, min_free=rng.choice([8, 16, 24]))
            oracle = {}
            for _ in range(300):
                if rng.random() < 0.65 or not oracle:
                    rec = rand_rec(rng, cap // 3)
                    fl = h.free_list()
                    fit = next((i for i, p in enumerate(fl) if h.pages[p].fits(rec)), None)
                    rid = h.insert(rec)
                    r, w = h.last_io
                    if fit is None:
                        self.assertEqual(rid[0], h.n_pages() - 1)
                        self.assertLessEqual(r, 1 + len(fl) + 1)
                    else:
                        self.assertEqual(rid[0], fl[fit])
                        self.assertLessEqual(r, 1 + (fit + 1) + 2)
                        if rid[0] in h.free_list():
                            self.assertEqual((r, w), (fit + 2, 1))
                    self.assertLessEqual(w, 5)
                    oracle[rid] = rec
                else:
                    rid = rng.choice(sorted(oracle))
                    h.delete(rid)
                    del oracle[rid]
                    r, w = h.last_io
                    self.assertLessEqual(r, 5)
                    self.assertLessEqual(w, 5)
                h.check()
            self.assertEqual(h.records(), oracle)
            before = h.reads
            self.assertEqual(dict(h.scan()), oracle)
            self.assertEqual(h.reads - before, 1 + h.n_pages())


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

History

The heap file, also called the entry-sequenced file, is the simplest file organization of relational systems, and Gray and Reuter (1993) treat it together with the free space administration of the tuple-oriented file system. Ramakrishnan and Gehrke give the two implementations of a heap file, with a page directory and with two linked lists, and the cost comparison of heap, sorted and hashed files that most database courses use. Oracle calls the default table a heap-organized table, in contrast with its index-organized table, and PostgreSQL names its table files heap files and keeps their free space in a free space map.

References

  1. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, third edition, McGraw-Hill (2003), Chapter 8 (overview of storage and indexing), the cost comparison of file organizations; Chapter 9 (storing data: disks and files), files of records and the two implementations of heap files
  2. Jim Gray and Andreas Reuter, Transaction Processing, Concepts and Techniques, Morgan Kaufmann (1993), the chapters on file and buffer management and on the tuple-oriented file system, the entry-sequenced file and free space administration
  3. Hector Garcia-Molina, Jeffrey D. Ullman and Jennifer Widom, Database Systems, The Complete Book, second edition, Pearson (2009), the chapter on data storage, the representation of records and of blocks
  4. PostgreSQL documentation, Free space map, the free space map of a relation, a separate fork with the free space of each heap page

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/FWEZG7/text.yaml