Algorithm Search⌘K

Data structureintro

Buffer pool

Also called buffer manager, database buffer cache.

A fixed set of memory frames that cache disk pages, with a page table, pin counts, dirty bits and a replacement policy that picks a victim among the unpinned frames.

Time
O(n B) worst
Space
O(B) extra
Counts
io 2n worst
Where
B = the number of frames (buffer pages); n = the number of page requests

A buffer pool is the part of main memory where a database system keeps copies of disk pages. It has a fixed number BB of frames, each the size of one page. A page table maps the id of each page in memory to its frame. Each frame has a pin count, the number of callers that use the page now, and a dirty bit, set when the copy in memory differs from the copy on disk. When a requested page is not in the pool, a replacement policy such as LRU or CLOCK picks a victim among the frames with pin count zero; a dirty victim is written back first. The component that does all this is the buffer manager. DBMIN is one policy for this pool: it gives each open file of a query its own set of frames and its own policy, and this page is about the pool and the general policies.

In plain words

The disk is slow and memory is small. The buffer pool is a shelf in memory with room for a fixed number of pages. When some part of the database needs a page, it asks the pool. If the page is on the shelf, it gets it at once. If not, the pool reads it from disk and puts it on the shelf, and when the shelf is full it first takes a page off.

Two rules keep this safe. A page that someone is using now is pinned, and the pool never takes a pinned page off. A page that someone changed is marked dirty, and the pool writes it back to disk before it drops it.

Which unpinned page to drop is a choice. A common choice is the page that was used the longest time ago.

The abstract type

The pool serves the rest of the system with four calls.

  • fetch(p): make page pp present in a frame, increase its pin count, and return the frame. Fail if pp is absent and all frames are pinned.
  • unpin(p, d): decrease the pin count of pp; if dd is true, the caller changed the page, so set its dirty bit.
  • new_page(): allocate a page on disk and fetch it without a read.
  • flush(p): write pp to disk if it is dirty, and clear its dirty bit.

A caller must unpin every page it fetched, once per fetch. The guarantee is that while a page is pinned, its frame does not change, and that every change a caller makes and reports reaches the disk before the frame is reused.

Representation

  • An array of BB frames. A frame holds a page id (or nothing), the bytes of the page, a pin count, a dirty bit, and whatever the policy needs: a time of last use for LRU, a reference bit for CLOCK, the times of the last KK uses for LRU-K.
  • A page table, a hash table from page id to frame number, for the pages now in the pool.
  • The state of the policy: a list in order of last use for LRU, a clock hand for CLOCK, queues for 2Q.

The invariant is that the page table and the frames agree: table[p]=ftable[p] = f if and only if frame ff holds page pp, each page is in at most one frame, and a frame with a page whose dirty bit is clear holds the same bytes as the disk.

Operations

  1. FETCH(p)
  2. 1if p is in the page table then
  3. 2f ← table[p]; pin(f) ← pin(f) + 1; record a use of f
  4. 3return f
  5. 4if a frame f is free then use it
  6. 5else
  7. 6f ← VICTIM(), a frame with pin(f) = 0
  8. 7if there is none then fail: all frames are pinned
  9. 8if dirty(f) then write page(f) to disk
  10. 9remove page(f) from the page table
  11. 10read p from disk into f
  12. 11page(f) ← p; pin(f) ← 1; dirty(f) ← false; table[p] ← f
  13. 12record a use of f; return f
  14. UNPIN(p, d)
  15. 13f ← table[p]; pin(f) ← pin(f) - 1
  16. 14dirty(f) ← dirty(f) or d
  17. VICTIM() for CLOCK ▷ called only if some frame has pin 0
  18. 15loop
  19. 16f ← the frame at the hand; move the hand to the next frame
  20. 17if pin(f) = 0 then
  21. 18if ref(f) then ref(f) ← false
  22. 19else return f

A use of a frame sets its reference bit for CLOCK, and moves it to the most recent end of the list for LRU. VICTIM for LRU returns the unpinned frame with the oldest last use.

Example

Take B=3B = 3 frames and the requests 1 2 3 1 4 1 2 5 1 2, each fetched and unpinned at once, so no frame is pinned when a victim is chosen.

request 1 2 3 1 4 1 2 5 1 2
LRU miss miss miss hit miss, drop 2 hit miss, drop 3 miss, drop 4 hit hit
CLOCK miss miss miss hit miss, drop 1 miss, drop 2 miss, drop 3 miss, drop 4 hit hit

LRU has 6 misses. When 4 arrives, the order of last use is 2, 3, 1, so 2 goes. CLOCK has 7 misses. When 4 arrives, all three reference bits are set, so the hand goes once around the frames, clears each bit, and comes back to frame 0, which holds page 1: CLOCK drops page 1 although it was used one request before. This is the cost of a single bit: CLOCK forgets the order of uses inside one turn of the hand. Both end with pages 1, 2 and 5 in the pool.

A loop over 5 pages with B=4B = 4 frames misses on every request with LRU, because the page that comes next is always the one that was used longest ago. This sequential flooding is the classic case where the order of last use is the wrong guide for a database. A policy that drops the most recently used page, MRU, keeps 3 of the 4 frames useful on each pass, which is what DBMIN gives a looping scan.

Correctness

The page table and the frames change together at lines L9 and L11, so they keep agreeing. A frame is reused only at line L6, and VICTIM returns only a frame with pin count zero, so a pinned page never leaves its frame. For CLOCK, the loop ends: some frame has pin count zero, and the first time the hand passes it, it either returns it or clears its bit, so it returns it at the latest on the next turn. A dirty bit is set at line L14 whenever a caller reports a change, and is cleared only at line L11 after a read or by flush after a write, and line L8 writes a dirty victim before its frame is reused. So no reported change is lost. The full proof is below.

Proof: The buffer pool never evicts a pinned page, never loses a reported change, and its CLOCK victim search endsfull

We use the notation of the page: BB frames, the page table tabletable, and for each frame ff its page page(f)page(f) (or none), its pin count pin(f)pin(f), its dirty bit dirty(f)dirty(f) and, for CLOCK, its reference bit ref(f)ref(f). Let disk(p)disk(p) be the bytes of page pp on disk and mem(f)mem(f) the bytes in frame ff. The current value of page pp is mem(table[p])mem(table[p]) if pp is in the table, and disk(p)disk(p) otherwise.

Callers follow the protocol of the page: they change the bytes of a frame only while they hold a pin on it, and they report each change by unpin(p, true) before their last unpin of that page.

Invariant.

  1. table[p]=ftable[p] = f if and only if page(f)=ppage(f) = p, and no page is in two frames.
  2. pin(f)≥0pin(f) \ge 0 for every frame, and pin(f)pin(f) is the number of fetches of page(f)page(f) that have not been unpinned yet.
  3. If page(f)=ppage(f) = p, pin(f)=0pin(f) = 0 and dirty(f)dirty(f) is false, then mem(f)=disk(p)mem(f) = disk(p).

Part 3 states that a clean unpinned frame holds the same bytes as the disk. A pinned frame may hold changes that are not reported yet; they are reported before the pin count can return to zero.

Lemma 1. VICTIM returns only a frame ff with pin(f)=0pin(f) = 0, and FETCH fails at line L7 only if every frame is pinned.

Proof. For LRU, VICTIM picks among the frames with pin count zero by definition. For CLOCK, line L19 is reached only after the test at line L17. VICTIM is called only when no frame is free; if no frame has pin count zero, the implementation reports this before the search, which is the failure at line L7. □\square

Lemma 2 (termination of CLOCK). If some frame has pin count zero, VICTIM for CLOCK returns after at most 2B2B steps.

Proof. Pin counts do not change during the search. Let UU be the nonempty set of frames with pin count zero. In the first BB steps the hand visits every frame once. Each frame of UU visited with a clear bit is returned at once. Otherwise every frame of UU had its bit set and is cleared on its visit, so in the next BB steps the hand reaches a frame of UU with a clear bit and returns it. □\square

Lemma 3. FETCH, UNPIN, new_page and flush keep the invariant.

Proof. FETCH on a hit (lines L1 to L3) adds one pin and one outstanding fetch, which keeps part 2, and changes no bytes. FETCH on a miss uses a free frame or a victim ff with pin(f)=0pin(f) = 0 (Lemma 1). If ff held a page qq and was dirty, line L8 writes mem(f)mem(f) to disk, so disk(q)disk(q) becomes the current value of qq; if it was clean, part 3 already gives mem(f)=disk(q)mem(f) = disk(q). In both cases, removing qq from the table at line L9 does not change the current value of qq, which is now disk(q)disk(q). Lines L10 and L11 read pp (which was not in the table) into ff and set the table entry, so part 1 holds; the pin count is 1 for the one outstanding fetch; and mem(f)=disk(p)mem(f) = disk(p) with a clear dirty bit, so part 3 holds once the pin is gone if no change is reported. UNPIN lowers the pin count by one for one outstanding fetch, and sets the dirty bit if the caller reports a change. If the pin count reaches zero with a clear dirty bit, no caller reported a change since the frame was last clean, so by the protocol no caller changed it, and part 3 holds. new_page allocates a page and fetches it with the dirty bit set, so part 3 does not apply to it. flush writes a dirty frame and clears its bit, so then mem(f)=disk(p)mem(f) = disk(p). □\square

Theorem. Under the protocol, starting with all frames free:

(a) a page with a positive pin count stays in the same frame until its pin count returns to zero;

(b) for every page pp, at every moment when no caller holds a pin on pp, the current value of pp is the value after the last reported change to pp, or disk(p)disk(p) at the start if there was none; and after flush_all, disk(p)disk(p) is that value;

(c) the number of disk reads equals the number of misses, and the number of disk writes equals the number of dirty victims plus the number of flushes of dirty frames.

Proof. (a) A frame changes its page only at lines L9 to L11 on a miss, and the frame is a victim, which has pin count zero by Lemma 1.

(b) A reported change is a change to mem(f)mem(f) while ff is pinned, followed by setting dirty(f)dirty(f). The frame stays with pp while it is pinned, by (a). After that, the bytes of pp in memory can leave the pool only at line L8, which writes them to disk because the bit is set. So the current value of pp is always the last reported value. flush_all writes every dirty frame, and by part 3 every clean frame already agrees with the disk, so afterwards the disk holds the current value of every page.

(c) Line L10 is the only read and runs once per miss (new_page does not read). Line L8 and flush are the only writes, and each runs only for a dirty frame. □\square

The CLOCK step count. Suppose no frame is pinned during any victim search, as in a sequence where each request is fetched and unpinned at once. Each step of the hand either clears a reference bit or returns a victim. A reference bit is set once per request (a hit or a miss records a use), and a bit can be cleared only after it was set, so over nn requests the steps that clear a bit number at most nn, and the steps that return a victim number at most mm, the number of misses. So the total work of all victim searches is at most n+m≤2nn + m \le 2n steps, which is O(1)O(1) amortized per request.

LRU and the sequential loop. With BB frames and a loop over B+1B + 1 pages 0,1,…,B0, 1, \ldots, B, repeated, every request of LRU misses. Proof. After the first B+1B + 1 requests, and at each later request of page jj, the pool holds the BB pages used most recently, which are the BB pages other than jj, since jj was used B+1B + 1 requests ago and every other page more recently. So jj is not in the pool. □\square

Complexity

The page I/O is counted in the external memory model with pages as blocks. In the external memory model, the memory holds M/B blocks; this is the number of buffer pages B of this page. A request that hits costs no I/O. A miss costs one read, plus one write when the victim is dirty, so nn requests cost at most 2n2n I/Os, and the number of reads is the number of misses. The cost does not separate sequential and random I/O; a pool that reads ahead for scans turns many random reads into a few large sequential ones.

The CPU work per request is a hash lookup in the page table, O(1)O(1) expected, plus the work of the policy on a miss.

  • LRU with a doubly linked list of the unpinned frames: O(1)O(1) per request. The sample code finds the oldest frame by a scan, O(B)O(B) per miss.
  • CLOCK: at most 2B2B steps of the hand per victim, since one turn clears every bit of an unpinned frame. If no frame is ever pinned during a victim search, the total number of steps over nn requests is at most n+mn + m for mm misses: each step either clears a bit that an earlier request set, or ends at a victim. Pinned frames add steps that the hand passes over.

The number of misses depends on the policy and the workload, and there is no best policy for all workloads. For the paging problem with BB frames, the optimal offline policy, Belady's algorithm, drops the page whose next use is farthest away, and LRU makes at most BB times as many misses as it on any sequence, up to an additive constant (Sleator and Tarjan 1985). Database policies are judged by measurement on workloads, not by such bounds.

Variants

  • LRU-K. O'Neil, O'Neil and Weikum (1993) drop the page whose KK-th most recent use is the oldest. With K=2K = 2, a page used once by a scan has no second use and goes first, so scans do not flush the pages that are used often. See LRU-K.
  • 2Q. Johnson and Shasha (1994) get much of the effect of LRU-2 at the cost of LRU: new pages enter a FIFO queue and move to the main LRU queue only on a second use. See 2Q.
  • CLOCK with counts. PostgreSQL uses a clock sweep in which each buffer has a usage count up to 5 instead of one bit. The hand decreases the count and takes a buffer only when its count is zero.
  • Rings for scans. A large sequential scan, a bulk write or a vacuum in PostgreSQL uses a small ring of buffers of its own, so that it does not push the rest of the pool out.
  • Per query allocation. DBMIN gives each file that a query opens a locality set of frames and a policy that fits its access pattern, and admits a query only if its sets fit in the pool. See DBMIN.
  • Hints and priorities. Some systems let the query layer mark pages as likely to be reused, such as the root and the inner nodes of a B+ tree, or as used once.
  • Adaptive policies. CLOCK-Pro and CAR adapt between recency and frequency.

When to use it

Every disk-based database system has a buffer pool. The choices are the policy and the size. Use CLOCK or one of its variants when the cost per request must be small and there are many concurrent threads, since a hit only sets a bit and takes no lock on a shared list. Use LRU-K or 2Q when scans and point lookups mix, so that scans do not flush the hot pages. Give scans a ring or an MRU set of their own. The five-minute rule is a guide for the size: a page that is used more often than once per break-even interval should stay in memory.

Pitfalls

  • A missing unpin. A caller that forgets an unpin leaves the page pinned forever, and the pool loses one frame. With enough of them, every fetch fails. Tie each pin to a scope that ends it.
  • Pins and latches. A pin keeps the page in its frame. It does not stop another thread from reading a page that is being changed. Changes need a latch on the page as well, and the pin count must not be used as a lock.
  • Write-ahead logging. With write-ahead logging, a dirty page must not reach the disk before the log records that describe its changes. Before line L8 writes a dirty page, the pool must force the log up to the log sequence number of the page. Whether dirty pages of uncommitted transactions may be written at all is the steal policy; see steal and force policies.
  • Double buffering. If the operating system also caches the file, each page can be in memory twice. Database systems often open their files with direct I/O, which also gives them control over the order of writes. Stonebraker (1981) described these problems with the file systems of that time.
  • Sequential flooding. Plain LRU with a scan larger than the pool misses on every request of the scan, and pushes out all other pages. Use a ring for scans, MRU for loops, or LRU-K.
  • The page table under concurrency. One lock on the whole page table is a bottleneck. Systems split the table into partitions, each with its own lock.

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.

buffer_pool.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/buffer-pool/. The authors are listed in prov/GQQFSE.jsonl.

"""A buffer pool: B frames, a page table, pin counts, dirty bits and a policy.

The disk is a dict from page id to bytes that counts reads and writes. A caller
fetches a page (which pins it), reads or changes the frame's bytes, and unpins
it, saying whether it changed the page. A pinned frame is never chosen as a
victim. Two replacement policies are given, LRU and CLOCK.
"""

from typing import Dict, List, Optional


class AllFramesPinned(Exception):
    """Every frame is pinned, so no page can be brought in."""


class Disk:
    def __init__(self, pages: Optional[Dict[int, bytes]] = None) -> None:
        self.pages: Dict[int, bytes] = dict(pages or {})
        self.reads = 0
        self.writes = 0

    def read(self, pid: int) -> bytes:
        self.reads += 1
        return self.pages[pid]

    def write(self, pid: int, data: bytes) -> None:
        self.writes += 1
        self.pages[pid] = bytes(data)

    def allocate(self, size: int) -> int:
        pid = max(self.pages, default=-1) + 1
        self.pages[pid] = bytes(size)
        return pid


class Frame:
    __slots__ = ("pid", "data", "pin", "dirty", "ref", "stamp")

    def __init__(self) -> None:
        self.pid: Optional[int] = None
        self.data = bytearray()
        self.pin = 0
        self.dirty = False
        self.ref = False   # CLOCK reference bit
        self.stamp = 0     # LRU time of last access


class BufferPool:
    def __init__(self, disk: Disk, n_frames: int, policy: str = "lru") -> None:
        if n_frames < 1:
            raise ValueError("a pool needs at least one frame")
        if policy not in ("lru", "clock"):
            raise ValueError("policy must be lru or clock")
        self.disk = disk
        self.frames: List[Frame] = [Frame() for _ in range(n_frames)]
        self.table: Dict[int, int] = {}   # page id -> frame number
        self.policy = policy
        self.hand = 0
        self.clock = 0
        self.hits = 0
        self.misses = 0

    # ------------------------------------------------------------ policy

    def _touch(self, f: Frame) -> None:
        self.clock += 1
        f.stamp = self.clock
        f.ref = True

    def _victim(self) -> Optional[int]:
        if all(f.pin > 0 for f in self.frames):
            return None
        if self.policy == "lru":
            cands = [i for i, f in enumerate(self.frames) if f.pin == 0]
            return min(cands, key=lambda i: self.frames[i].stamp)
        while True:                                       # @line L15
            i = self.hand                                 # @line L16
            self.hand = (self.hand + 1) % len(self.frames)  # @line L16
            f = self.frames[i]
            if f.pin == 0:                                # @line L17
                if f.ref:                                 # @line L18
                    f.ref = False                         # @line L18
                else:
                    return i                              # @line L19

    # ------------------------------------------------------------ interface

    def fetch(self, pid: int) -> bytearray:
        """Pin page pid and return its frame's bytes."""
        if pid in self.table:                             # @line L1
            f = self.frames[self.table[pid]]              # @line L2
            f.pin += 1                                    # @line L2
            self._touch(f)                                # @line L2
            self.hits += 1
            return f.data                                 # @line L3
        self.misses += 1
        free = next((i for i, f in enumerate(self.frames) if f.pid is None), None)
        if free is not None:                              # @line L4
            i = free                                      # @line L4
        else:                                             # @line L5
            i = self._victim()                            # @line L6
            if i is None:                                 # @line L7
                self.misses -= 1
                raise AllFramesPinned(pid)                # @line L7
            v = self.frames[i]
            if v.dirty:                                   # @line L8
                self.disk.write(v.pid, v.data)            # @line L8
            del self.table[v.pid]                         # @line L9
        f = self.frames[i]
        f.data = bytearray(self.disk.read(pid))           # @line L10
        f.pid, f.pin, f.dirty = pid, 1, False             # @line L11
        self.table[pid] = i                               # @line L11
        self._touch(f)                                    # @line L12
        return f.data                                     # @line L12

    def unpin(self, pid: int, dirty: bool = False) -> None:
        f = self.frames[self.table[pid]]                  # @line L13
        if f.pin == 0:
            raise ValueError(f"page {pid} is not pinned")
        f.pin -= 1                                        # @line L13
        f.dirty = f.dirty or dirty                        # @line L14

    def new_page(self, size: int) -> int:
        """Allocate a page on disk and fetch it pinned. Its frame starts dirty."""
        pid = self.disk.allocate(size)
        reads = self.disk.reads
        self.fetch(pid)
        self.disk.reads = reads   # the new page has nothing to read
        self.frames[self.table[pid]].dirty = True
        return pid

    def flush(self, pid: int) -> None:
        f = self.frames[self.table[pid]]
        if f.dirty:
            self.disk.write(pid, f.data)
            f.dirty = False

    def flush_all(self) -> None:
        for pid in list(self.table):
            self.flush(pid)

    def pin_count(self, pid: int) -> int:
        return self.frames[self.table[pid]].pin if pid in self.table else 0

    def resident(self) -> List[int]:
        return sorted(self.table)

    def check(self) -> None:
        for pid, i in self.table.items():
            assert self.frames[i].pid == pid
        assert sum(f.pid is not None for f in self.frames) == len(self.table)
        assert all(f.pin >= 0 for f in self.frames)
test_buffer_pool.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/buffer-pool/. The authors are listed in prov/GQQFSE.jsonl.

import random
import unittest

from buffer_pool import AllFramesPinned, BufferPool, Disk


def make_disk(n, size=8):
    return Disk({p: bytes([p % 256]) * size for p in range(n)})


def lru_misses(trace, b):
    """A plain LRU cache of b pages, as a list from least to most recent."""
    cache, misses = [], 0
    for p in trace:
        if p in cache:
            cache.remove(p)
        else:
            misses += 1
            if len(cache) == b:
                cache.pop(0)
        cache.append(p)
    return misses


def clock_misses(trace, b):
    """A plain CLOCK of b frames: free frames fill in order, then the hand sweeps."""
    pages, refs, hand, misses = [None] * b, [False] * b, 0, 0
    for p in trace:
        if p in pages:
            refs[pages.index(p)] = True
            continue
        misses += 1
        if None in pages:
            i = pages.index(None)
        else:
            while refs[hand]:
                refs[hand] = False
                hand = (hand + 1) % b
            i = hand
            hand = (hand + 1) % b
        pages[i], refs[i] = p, True
    return misses


def run(pool, trace):
    for p in trace:
        pool.fetch(p)
        pool.unpin(p)


class TestBufferPool(unittest.TestCase):
    def test_worked_example(self):
        trace = [1, 2, 3, 1, 4, 1, 2, 5, 1, 2]
        lru = BufferPool(make_disk(6), 3, "lru")
        run(lru, trace)
        self.assertEqual((lru.misses, lru.hits), (6, 4))
        self.assertEqual(lru.resident(), [1, 2, 5])
        clock = BufferPool(make_disk(6), 3, "clock")
        run(clock, trace)
        self.assertEqual((clock.misses, clock.hits), (7, 3))
        self.assertEqual(clock.resident(), [1, 2, 5])
        self.assertEqual(clock.disk.reads, 7)
        self.assertEqual(clock.disk.writes, 0)

    def test_policies_match_plain_simulations(self):
        for seed in range(20):
            rng = random.Random(seed)
            n = rng.randrange(2, 30)
            b = rng.randrange(1, 10)
            hot = max(1, n // 5)
            trace = [rng.randrange(hot) if rng.random() < 0.7 else rng.randrange(n)
                     for _ in range(400)]
            lru = BufferPool(make_disk(n), b, "lru")
            run(lru, trace)
            self.assertEqual(lru.misses, lru_misses(trace, b))
            self.assertEqual(lru.disk.reads, lru.misses)
            clock = BufferPool(make_disk(n), b, "clock")
            run(clock, trace)
            self.assertEqual(clock.misses, clock_misses(trace, b))

    def test_looping_scan_defeats_lru(self):
        # A loop over b + 1 pages misses on every access with LRU.
        trace = list(range(5)) * 10
        pool = BufferPool(make_disk(5), 4, "lru")
        run(pool, trace)
        self.assertEqual(pool.misses, len(trace))

    def test_all_pinned(self):
        pool = BufferPool(make_disk(4), 2)
        pool.fetch(0)
        pool.fetch(1)
        with self.assertRaises(AllFramesPinned):
            pool.fetch(2)
        self.assertEqual(pool.resident(), [0, 1])
        pool.unpin(1)
        pool.fetch(2)
        self.assertEqual(pool.resident(), [0, 2])
        pool.unpin(2)
        with self.assertRaises(ValueError):
            pool.unpin(2)

    def test_pinned_pages_stay_and_data_is_consistent(self):
        for seed in range(15):
            rng = random.Random(1000 + seed)
            n, b = rng.randrange(3, 20), rng.randrange(2, 6)
            policy = rng.choice(["lru", "clock"])
            disk = make_disk(n, 4)
            pool = BufferPool(disk, b, policy)
            truth = dict(disk.pages)
            pinned = {}
            dirty_evictions = 0
            for _ in range(300):
                p = rng.randrange(n)
                if pinned and rng.random() < 0.3:
                    q = rng.choice(sorted(pinned))
                    pool.unpin(q)
                    pinned[q] -= 1
                    if pinned[q] == 0:
                        del pinned[q]
                    continue
                before = set(pool.resident())
                dirty_before = {f.pid for f in pool.frames if f.dirty}
                try:
                    data = pool.fetch(p)
                except AllFramesPinned:
                    self.assertTrue(all(f.pin > 0 for f in pool.frames))
                    self.assertNotIn(p, pool.table)
                    continue
                gone = before - set(pool.resident())
                self.assertFalse(gone & set(pinned), "a pinned page was evicted")
                dirty_evictions += len(gone & dirty_before)
                self.assertEqual(bytes(data), truth[p])
                change = rng.random() < 0.5
                if change:
                    data[rng.randrange(4)] = rng.randrange(256)
                    truth[p] = bytes(data)
                if rng.random() < 0.4:
                    pinned[p] = pinned.get(p, 0) + 1
                    if change:
                        pool.frames[pool.table[p]].dirty = True
                else:
                    pool.unpin(p, dirty=change)
                for q, c in pinned.items():
                    self.assertEqual(pool.pin_count(q), c)
                pool.check()
            self.assertEqual(disk.writes, dirty_evictions)
            for q in list(pinned):
                for _ in range(pinned[q]):
                    pool.unpin(q)
            pool.flush_all()
            self.assertEqual(disk.pages, truth)
            writes = disk.writes
            pool.flush_all()
            self.assertEqual(disk.writes, writes)

    def test_new_page(self):
        disk = make_disk(2)
        pool = BufferPool(disk, 2)
        pid = pool.new_page(8)
        self.assertEqual(pid, 2)
        self.assertEqual(disk.reads, 0)
        pool.fetch(pid)[0] = 7
        pool.unpin(pid)
        pool.unpin(pid)
        pool.fetch(0)
        pool.unpin(0)
        pool.fetch(1)
        pool.unpin(1)
        self.assertEqual(disk.pages[2][0], 7)
        self.assertEqual(disk.writes, 1)


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

History

Effelsberg and Haerder (1984) gave the first full account of database buffer management: how to find a page in the pool, how to share frames among transactions, and how replacement policies compare. Stonebraker (1981) argued that the buffer caches of operating systems do not serve databases well, because their LRU ignores the known access patterns of queries. Sacco and Schkolnick (1982) proposed the hot set model, and Chou and DeWitt (1985) the query locality set model with the DBMIN algorithm, both based on those access patterns. O'Neil, O'Neil and Weikum (1993) gave LRU-K, and Johnson and Shasha (1994) gave 2Q. Hellerstein, Stonebraker and Hamilton (2007) describe the buffer pool as it exists in current systems.

References

  1. Principles of database buffer management, buffer search, the allocation of frames to transactions, and the replacement algorithms
  2. Architecture of a database system, the section on storage management and its part on buffer management
  3. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, third edition, McGraw-Hill (2003), Chapter 9 (storing data: disks and files), the section on the buffer manager: pin counts, dirty bits and replacement policies
  4. Operating system support for database management, the section on buffer pool management
  5. The LRU-K page replacement algorithm for database disk buffering, the definition of LRU-K and the argument against plain LRU for mixed workloads
  6. An evaluation of buffer management strategies for relational database systems, the reference patterns of relational queries and the simulation of replacement algorithms

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.worst
  • a full proof of space.extra
  • 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/GQQFSE/text.yaml