Algorithm Search⌘K

Algorithmadvanced

DBMIN buffer management

Also called query locality set model, DBMIN.

Chou and DeWitt's buffer policy: each file a query opens gets its own locality set of frames, sized and replaced by its reference pattern, and a query starts only if all sets fit.

Time
O(n + f) worst · average
Space
O(B + f) extra
Counts
io n worst
Where
B = the number of frames in the pool; f = the number of open file instances; n = the number of page requests
Properties
deterministicnot exactexternalnot in placeonlineiterative
Origin
Hong Tai Chou, David J. DeWitt, 1985

DBMIN is a buffer management algorithm of Chou and DeWitt (1985) for relational database systems. It rests on the query locality set model (QLSM): the query plan already tells how each operator will read each file, for example a sequential scan, a scan that loops over the inner relation of a join, or random lookups through an index. DBMIN gives each file instance, one file opened by one query, its own locality set of frames, with a size and a local replacement policy chosen for its reference pattern. A load controller starts a query only if the locality sets of all running queries fit in the pool. A general buffer pool with one global policy such as LRU or CLOCK treats all pages alike; DBMIN uses the plan to give each access the few frames it needs and to keep one query from taking the frames of another.

In plain words

A database knows its future page requests better than an operating system does. When a query scans a table once, one frame is enough. When a join reads the inner table again and again in a loop, it pays to keep as much of that table as possible, and the best page to give up is the one just read, because it will be needed last. For repeated index lookups, keep the top of the index.

DBMIN gives each opened file its own small set of frames, sized for its pattern, with a rule that fits the pattern. Pages that belong to no set go to a common free list, and any query that needs one of those pages can take it back without a disk read. A new query waits until there are enough free frames for all of its sets.

The problem

A pool of BB frames serves several queries at once. Each query opens files; the same file opened by two queries is two file instances. Each request names a file instance and a page. The goal is high throughput: few disk reads per query, and no thrashing, in which concurrent queries keep taking each other's frames so that all of them run slowly. Chou and DeWitt write NN for the number of frames; this page writes BB, as in the rest of the area.

The reference patterns of the QLSM. Each pattern comes with the size of a locality set and a local policy.

pattern example locality set size local policy
straight sequential (SS) a selection that scans an unordered relation once 1 any
clustered sequential (CS) the inner input of a merge join, which backs up over the records with the same key records of the largest cluster divided by records per page FIFO or LRU
looping sequential (LS) the inner relation of a nested loops join the whole file if it fits MRU if it does not fit
independent random (IR) data pages read through a non-clustered index 1 or bb (below) any
clustered random (CR) an inner relation read through a non-clustered, non-unique index, for an outer relation clustered on non-unique keys about the number of records in the largest cluster as for CS
straight hierarchical (SH), and H/SS one traversal of an index, alone or followed by a scan of the leaves 1 any
hierarchical with clustered sequential (H/CS) a traversal followed by a clustered scan of the leaves as for CS, counting key and pointer pairs as for CS
looping hierarchical (LH) repeated traversals of an index on the join field of the inner relation the upper levels of the tree (below) LIFO with 3 to 4 buffers keeps the root

For independent random access, bb is the expected number of distinct pages that kk random record accesses touch, from Yao's formula: for nn records on mm pages, b=m(1−∏i=1kn(1−1/m)−i+1n−i+1)b = m \left(1 - \prod_{i=1}^{k} \frac{n(1 - 1/m) - i + 1}{n - i + 1}\right). The paper calls (k−b)/b(k - b)/b the residual value of a page, and the set has size 1 if it is at most a threshold β\beta and size bb otherwise. For looping hierarchical access, let bib_i be the number of pages of level ii of the tree (the root is level 0) that kk traversals touch, again by Yao's formula; the size is about (1+b1+⋯+bj)+1(1 + b_1 + \cdots + b_j) + 1, where jj is the deepest level whose residual value (k−bi)/bi(k - b_i)/b_i is above β\beta. Since the fan-out of an index is large, the root is often the only page worth keeping. For independent random access, the paper notes that all replacement algorithms do about equally well.

The algorithm

The state is a global table of all pages in memory, a global free list, and one locality set per file instance. Each locality set LL has a bound l(L)l(L) and a size r(L)≤l(L)r(L) \le l(L). A page is owned by at most one locality set; a page that no set owns is on the free list, which also holds the empty frames.

  1. REQUEST(L, p) ▷ file instance with locality set L asks for page p
  2. 1if p is in the global table then
  3. 2if owner(p) = L then
  4. 3update the statistics of the policy of L for p; return
  5. 4if owner(p) is another locality set then
  6. 5return p ▷ shared: p stays in the other set
  7. 6remove p from the free list ▷ p is in memory with no owner
  8. 7else
  9. 8f ← the frame at the head of the free list; drop its page from the global table
  10. 9read p into f
  11. 10if r(L) = l(L) then
  12. 11q ← the victim of the policy of L; owner(q) ← none; append q to the free list
  13. 12r(L) ← r(L) - 1
  14. 13owner(p) ← L; add p to L; r(L) ← r(L) + 1
  15. START(Q) ▷ Q opens file instances with bounds l_1, ..., l_k
  16. 14if the bounds of all active sets plus l_1 + ... + l_k < B then
  17. 15activate Q with an empty locality set (r = 0) for each file instance
  18. 16else put Q at the end of the waiting queue
  19. FINISH(Q)
  20. 17for each locality set of Q, put its pages on the free list with no owner
  21. 18while the first waiting query passes the test of line L14 do
  22. 19activate it, as at line L15

Lines L1 to L3 are the first case of the paper, a page found in its own locality set. Lines L4 to L6 and L10 to L13 are the second case, a page in memory but not in the set: if another set owns it, the requester just uses it; otherwise it joins the set, and if the set is then over its bound, the local policy gives a page back to the free list. Lines L7 to L9 are the third case, a page not in memory, which is read into a frame from the free list and then treated as in the second case. In the paper the usage statistics of the new page are updated after the release, so the local policy chooses among the pages that were in the set before; the implementation picks the victim before it adds the new page, which is the same choice, and MRU gives up the page used just before, not the new one. The paper notes that the local policies cause no swapping of their own; disk reads and writes come only from the global table and the free list, here line L9.

The load controller runs when a file is opened or closed. The paper places a suspended query at the front of the waiting queue and, on a close, activates the first waiting query if the condition still holds. The sample code admits a whole query at a time, appends a suspended query at the end of the queue, and also queues a new query when others are already waiting, so that small queries cannot pass a large one forever.

Example

A looping scan. One query loops three times over a file of 6 pages, 0 to 5, with a locality set of l=3l = 3 and B=4B = 4 frames. There are 18 requests.

pass MRU: misses MRU: hits LRU: misses
1 0 1 2 3 4 5 none 0 1 2 3 4 5
2 2 3 4 0 1 5 all 6
3 1 2 3 0 4 5 all 6
total 12 6 18

With MRU, the first pass ends with pages 0, 1 and 5 in the set: each miss on pages 3, 4 and 5 gave up the page read just before it. In pass 2, pages 0 and 1 hit. The miss on page 2 gives up page 1, the miss on 3 gives up 2, the miss on 4 gives up 3, and page 5 hits. With LRU, the page that is needed next is always the one that left the set, so every request misses, and the free list holds only one frame, which does not help.

Load control. Take B=10B = 10. Query Q1Q_1 scans RR once (SS, size 1) and loops over SS (LS, size 6), so it needs 7 frames, and 7<107 < 10 admits it. Query Q2Q_2 needs one set of 3 frames; 7+3=107 + 3 = 10 is not less than 10, so it waits. Query Q3Q_3 needs 1 frame; it waits behind Q2Q_2. When Q1Q_1 finishes, its 7 pages go to the free list with no owner, and Q2Q_2 (needs 3) and then Q3Q_3 (total 4) start. If Q2Q_2 asks for a page of SS that Q1Q_1 had read, it finds it on the free list without a disk read.

Correctness

DBMIN is a heuristic, and its claims are of two kinds. The first are invariants. A page is in at most one locality set, each set has at most ll pages, and the load controller keeps the sum of the bounds below BB. So the sets hold fewer than BB frames together, and the free list is never empty when line L8 needs a frame. A set changes only on requests of its own file instance, so one query cannot take frames from another: the sets of running queries are isolated, which is how DBMIN avoids thrashing. Without sharing, each set holds exactly what a separate cache of ll pages with the same policy would hold, and the free list can only save reads.

The second kind is the analysis of a pattern. For a loop over L>l≥2L > l \ge 2 pages with MRU, every pass after the first has at least l−1l - 1 hits, while LRU with the same ll frames has none. The full proof is below. That the sizes and policies of the table are good choices is shown by measurement, not proved.

Proof: DBMIN keeps its locality sets within their bounds and isolated, always finds a free frame, and MRU gains at least l - 1 hits per pass of a loopfull

We use the notation of the page: BB frames; for each locality set LL of an active query, its bound l(L)l(L), its pages P(L)P(L) and its size r(L)=∣P(L)∣r(L) = |P(L)|; the global table GG of the pages in memory, with owner(p)owner(p) either a set or none; and the free list FF, a list of frames that hold either a page with no owner or nothing. Let Λ=∑Ll(L)\Lambda = \sum_L l(L) over the sets of active queries.

Invariant.

  1. Every page of GG is in exactly one frame. A page with an owner LL is in P(L)P(L) and not on FF; a page with no owner is on FF. So the sets P(L)P(L) are disjoint, and the frames are split between the sets and FF: ∑Lr(L)+∣F∣=B\sum_L r(L) + |F| = B.
  2. r(L)≤l(L)r(L) \le l(L) for every active set.
  3. Λ<B\Lambda < B, or there is no active query.

Lemma 1. If the invariant holds when line L8 runs, the free list is not empty.

Proof. By parts 1 to 3, ∣F∣=B−∑Lr(L)≥B−Λ≥1|F| = B - \sum_L r(L) \ge B - \Lambda \ge 1. □\square

Lemma 2. REQUEST keeps the invariant.

Proof. In the first case (lines L1 to L3) only usage statistics change. In the shared case (lines L4 and L5) nothing changes. Otherwise pp becomes a page of LL: either it was on FF with no owner and line L6 removes it, or line L8 takes a frame from FF (possible by Lemma 1) and drops the page it held from GG, so that page leaves memory, and line L9 reads pp into the frame. At this point the frame of pp is in neither FF nor any set, so ∑Lr(L)+∣F∣=B−1\sum_L r(L) + |F| = B - 1. If r(L)=l(L)r(L) = l(L), lines L11 and L12 move the victim q∈P(L)q \in P(L) to FF with no owner, which keeps the sum at B−1B - 1 and makes r(L)=l(L)−1r(L) = l(L) - 1. Line L13 adds pp to LL, which restores the sum to BB and gives r(L)≤l(L)r(L) \le l(L). Every page still has one frame and one place, so part 1 holds; part 3 does not change. □\square

Lemma 3. START and FINISH keep the invariant.

Proof. START activates a query only if Λ\Lambda plus its bounds is less than BB, and its new sets are empty, so parts 1 to 3 hold after it. FINISH moves the pages of the query's sets to FF with no owner, which keeps part 1, and lowers Λ\Lambda; each activation at line L19 passes the same test as START. □\square

Theorem 1 (isolation). The pages of a locality set LL change only during requests made through LL. In particular, no request of another query removes a page from P(L)P(L), and a running query never waits for frames.

Proof. Pages enter P(L)P(L) only at line L13 and leave only at line L11, both in a request through LL, or when the query of LL finishes. Lines L6 and L8 of other requests take pages only from FF, which by part 1 holds no page of P(L)P(L). By Lemma 1 a request always finds a frame, so it never waits. □\square

Theorem 2 (sets as separate caches). Suppose no page is requested through two different sets while it is in memory (no sharing). Then, after every request, P(L)P(L) is exactly the content of a separate cache of l(L)l(L) pages that runs the policy of LL on the requests made through LL. The number of disk reads is at most the sum, over the sets, of the misses of those separate caches.

Proof. Without sharing, line L4 is never true. So for each request through LL of page pp, if p∈P(L)p \in P(L) the statistics are updated, which is what the separate cache does on a hit; otherwise pp joins P(L)P(L), and if the set was full the policy's victim among the old pages leaves first, which is what the separate cache does on a miss. By induction over the requests through LL, the two contents are equal, and the policy statistics agree too. A disk read happens at line L9 only if pp is not in memory, so in particular p∉P(L)p \notin P(L), which is a miss of the separate cache. □\square

Theorem 3 (MRU on a loop). Consider a separate cache of l≥2l \ge 2 pages with the MRU policy, and the requests 0,1,…,L−10, 1, \ldots, L - 1, repeated, with L>lL > l. Every pass after the first has at least l−1l - 1 hits. LRU with ll pages on the same requests has no hits at all.

Proof. After each request, the page just requested is in the cache and is the most recently used one. Let KK be the cache without the page of the last request. After the first ll requests the cache is full and ∣K∣=l−1|K| = l - 1, and ∣K∣|K| stays l−1l - 1:

  • On a miss for pp, the victim is the most recently used page, the page p′p' of the previous request, and pp takes its place. So KK does not change.
  • On a hit for pp, pp was in KK (it is not p′p', since consecutive requests differ when L≥2L \ge 2). Now pp is the last page and p′p' joins KK. So KK loses pp and gains p′p'.

So a page leaves KK only when it is requested, and then the request is a hit. At the start of any pass after the first, KK holds l−1l - 1 pages. Each of them is requested once during the pass, and until it is requested it stays in KK, so that request is a hit. This gives at least l−1l - 1 hits in the pass.

For LRU, at a request of page pp after the first ll requests, the cache holds the ll pages requested most recently. They are the ll requests just before, which are ll distinct pages other than pp, because pp was last requested L>lL > l requests earlier. So every request misses. □\square

By Theorem 2, a looping file instance in DBMIN with an MRU set of size ll has at most L−l+1L - l + 1 disk reads per pass after the first, and the free list can only save more.

What is not proved. The sizes and policies of the table on the page are rules from the paper, justified by the reference patterns and by simulation. Whether DBMIN gives more throughput than another policy depends on the workload; Chou and DeWitt measured it, and this note proves only the invariants and the loop bound above.

Complexity

The 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. Each request causes at most one disk read, at line L9, so nn requests cost at most nn reads; this page and the paper treat only reads. The number of reads is at most the sum, over the locality sets, of the misses of a separate cache of ll pages with the same policy.

The CPU work per request is O(1)O(1) expected with a hash table for the global table, a doubly linked list for the free list, and a doubly linked list per locality set for LRU, MRU and FIFO. START and FINISH cost O(f)O(f) for ff file instances, if the sum of the bounds is kept as a running total, plus the pages that FINISH gives back. The sample code removes a page from the free list by a linear search, O(B)O(B).

Properties

  • Isolation. A query's locality sets change only through its own requests. A new query cannot slow down a running one by taking its frames, since it only starts if its sets fit.
  • Sharing without ownership. Two queries that read the same page share one frame. The page counts against the set that owns it, and the other query just uses it.
  • Cheap reuse. Pages given back by a set or by a finished query stay in memory on the free list until their frame is needed, so a later request finds them without a read.
  • Admission, not preemption. The load controller delays queries and never takes frames away from a running one. A query whose sets are too big for the pool never starts, so the bounds must be at most B−1B - 1 in total.

Variants and improvements

  • Hot set model. Sacco and Schkolnick (1982) estimate for each query a hot set, the number of frames below which its page faults rise sharply, and run a query only if its hot set fits. The hot set is one number per query, and the replacement inside it is LRU. DBMIN makes the estimate per file instance and picks the policy per pattern.
  • Marginal gains. Later work on flexible buffer allocation gives each additional frame to the query where one more frame saves the most reads, instead of a fixed set size per pattern.
  • General purpose policies. LRU-K and 2Q get part of the benefit of DBMIN without hints from the plan: a page read once by a scan does not push out the hot pages.
  • Rings for scans. Systems such as PostgreSQL give a large sequential scan a small ring of frames, which is the SS rule of DBMIN.

When to use it

Use the ideas of DBMIN when the access pattern of each operator is known from the plan, as in a Volcano style iterator engine, and many queries share one pool: give scans one frame or a small ring, give looped inner relations MRU or the whole file, keep the upper levels of indexes, and control the admission of queries by their memory needs. Most systems do not implement DBMIN as a whole. They use a global policy such as CLOCK or LRU-K, and add the rules for scans and indexes as hints.

Pitfalls

  • Wrong patterns. The sizes come from the plan. If the optimizer misestimates a cluster size or the number of random lookups, the set is too small or too big. A set that is too small for a loop turns the loop into a stream of misses.
  • MRU outside loops. MRU is right for a loop that does not fit. For any other pattern it gives up exactly the page with the most recent use, which is often the next one needed.
  • Admission deadlock. A query whose total bound is at least BB waits forever. Cap each bound, or reduce the set of a looping scan to fit.
  • Shared pages. The page used by a second query stays in the set of its owner. If the owner gives it up, it goes to the free list and can be dropped while the second query still uses it often; that query's next request then takes it into its own set.
  • Writes. The paper studies a read-only setting. With updates, a victim must be written before its frame is reused, and the write-ahead rule of the buffer pool applies.

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.

dbmin.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dbmin/. The authors are listed in prov/DPJZ9M.jsonl.

"""DBMIN buffer management (Chou and DeWitt 1985), for read-only page requests.

The pool has N frames. Every page in memory is in the global table. A page is
owned by at most one locality set; a page with no owner is on the global free
list, which also holds the empty frames. Each file instance of an active query
has a locality set with a bound l, a current size r <= l, and a local policy
(lru, mru or fifo). A query is admitted only if the bounds of all active sets
plus its own add up to less than N.
"""

from collections import OrderedDict, deque
from typing import Deque, Dict, List, Optional, Tuple

POLICIES = ("lru", "mru", "fifo")
SetId = Tuple[object, object]   # (query, file instance)


class LocalitySet:
    def __init__(self, bound: int, policy: str) -> None:
        if bound < 1:
            raise ValueError("a locality set needs at least one buffer")
        if policy not in POLICIES:
            raise ValueError(f"unknown policy {policy}")
        self.bound = bound
        self.policy = policy
        # pages in policy order: by last use (lru, mru) or by arrival (fifo)
        self.pages: "OrderedDict[int, None]" = OrderedDict()

    @property
    def size(self) -> int:
        return len(self.pages)

    def use(self, p: int) -> None:
        if self.policy in ("lru", "mru"):
            self.pages.move_to_end(p)

    def victim(self) -> int:
        if self.policy == "mru":
            return next(reversed(self.pages))
        return next(iter(self.pages))


class DBMIN:
    def __init__(self, n_frames: int) -> None:
        self.N = n_frames
        self.owner: Dict[int, Optional[SetId]] = {}          # the global table
        self.free: Deque[Optional[int]] = deque([None] * n_frames)  # None is an empty frame
        self.sets: Dict[SetId, LocalitySet] = {}
        self.active: Dict[object, List[object]] = {}
        self.waiting: Deque[Tuple[object, Dict[object, Tuple[int, str]]]] = deque()
        self.reads = 0
        self.hits = 0

    # ------------------------------------------------------------ load control

    def demand(self) -> int:
        return sum(s.bound for s in self.sets.values())

    def start(self, q: object, files: Dict[object, Tuple[int, str]]) -> bool:
        """Admit query q with its file instances {name: (l, policy)}, or queue it."""
        if q in self.active or any(q == w for w, _ in self.waiting):
            raise ValueError(f"query {q} is already known")
        if not self.waiting and self._fits(files):           # @line L14
            self._activate(q, files)                          # @line L15
            return True
        self.waiting.append((q, files))                       # @line L16
        return False

    def _fits(self, files: Dict[object, Tuple[int, str]]) -> bool:
        return self.demand() + sum(l for l, _ in files.values()) < self.N

    def _activate(self, q: object, files: Dict[object, Tuple[int, str]]) -> None:
        self.active[q] = list(files)
        for name, (l, policy) in files.items():
            self.sets[(q, name)] = LocalitySet(l, policy)

    def finish(self, q: object) -> List[object]:
        """End query q, free its locality sets, and admit waiting queries that fit."""
        for name in self.active.pop(q):
            ls = self.sets.pop((q, name))
            for p in ls.pages:                                # @line L17
                self.owner[p] = None                          # @line L17
                self.free.append(p)                           # @line L17
        started = []
        while self.waiting and self._fits(self.waiting[0][1]):  # @line L18
            w, files = self.waiting.popleft()                 # @line L19
            self._activate(w, files)                          # @line L19
            started.append(w)
        return started

    # ------------------------------------------------------------ requests

    def request(self, q: object, name: object, p: int) -> bool:
        """Serve a request of query q on file instance name for page p. True on a hit."""
        sid = (q, name)
        ls = self.sets[sid]
        if p in self.owner:                                   # @line L1
            self.hits += 1
            if self.owner[p] == sid:                          # @line L2
                ls.use(p)                                     # @line L3
                return True                                   # @line L3
            if self.owner[p] is not None:                     # @line L4
                return True                                   # @line L5
            self.free.remove(p)                               # @line L6
            hit = True
        else:                                                 # @line L7
            old = self.free.popleft()                         # @line L8
            if old is not None:                               # @line L8
                del self.owner[old]                           # @line L8
            self.reads += 1                                   # @line L9
            hit = False
        if ls.size == ls.bound:                               # @line L10
            v = ls.victim()                                   # @line L11
            del ls.pages[v]                                   # @line L11 L12
            self.owner[v] = None                              # @line L11
            self.free.append(v)                               # @line L11
        self.owner[p] = sid                                   # @line L13
        ls.pages[p] = None                                    # @line L13
        return hit

    # ------------------------------------------------------------ checks

    def check(self) -> None:
        owned = [p for ls in self.sets.values() for p in ls.pages]
        assert len(owned) == len(set(owned)), "a page is in two locality sets"
        for sid, ls in self.sets.items():
            assert ls.size <= ls.bound
            assert all(self.owner[p] == sid for p in ls.pages)
        on_free = [p for p in self.free if p is not None]
        assert sorted(on_free + owned) == sorted(self.owner)
        assert all(self.owner[p] is None for p in on_free)
        assert len(self.free) + len(owned) == self.N
        assert self.demand() < self.N or not self.sets
test_dbmin.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dbmin/. The authors are listed in prov/DPJZ9M.jsonl.

import random
import unittest

from dbmin import DBMIN


def plain_cache(trace, l, policy):
    """A stand-alone cache of l pages; returns its contents after each request."""
    cache, states = [], []
    for p in trace:
        if p in cache:
            if policy != "fifo":
                cache.remove(p)
                cache.append(p)
        else:
            if len(cache) == l:
                cache.pop(-1 if policy == "mru" else 0)
            cache.append(p)
        states.append(sorted(cache))
    return states


def reference_model(n_frames, sets, trace):
    """A direct model of the three cases, with lists; returns the number of reads."""
    owner, free, members, reads = {}, [None] * n_frames, {s: [] for s in sets}, 0
    for sid, p in trace:
        l, policy = sets[sid]
        if p in owner and owner[p] == sid:
            if policy != "fifo":
                members[sid].remove(p)
                members[sid].append(p)
            continue
        if p in owner and owner[p] is not None:
            continue
        if p in owner:
            free.remove(p)
        else:
            old = free.pop(0)
            if old is not None:
                del owner[old]
            reads += 1
        if len(members[sid]) == l:
            v = members[sid].pop(-1 if policy == "mru" else 0)
            owner[v] = None
            free.append(v)
        members[sid].append(p)
        owner[p] = sid
    return reads


class TestDBMIN(unittest.TestCase):
    def test_worked_example_looping_scan(self):
        trace = list(range(6)) * 3
        reads = {}
        for policy in ("mru", "lru"):
            db = DBMIN(4)
            self.assertTrue(db.start("Q", {"R": (3, policy)}))
            for p in trace:
                db.request("Q", "R", p)
                db.check()
            reads[policy] = db.reads
        self.assertEqual(reads, {"mru": 12, "lru": 18})

    def test_worked_example_admission(self):
        db = DBMIN(10)
        self.assertTrue(db.start("Q1", {"R": (1, "fifo"), "S": (6, "mru")}))
        self.assertFalse(db.start("Q2", {"T": (3, "lru")}))   # 7 + 3 = 10 is not below 10
        self.assertFalse(db.start("Q3", {"U": (1, "fifo")}))  # it waits behind Q2
        self.assertEqual(db.finish("Q1"), ["Q2", "Q3"])
        self.assertEqual(db.demand(), 4)

    def test_sharing_keeps_the_owner(self):
        db = DBMIN(8)
        db.start("Q1", {"A": (2, "lru")})
        db.start("Q2", {"B": (2, "lru")})
        self.assertFalse(db.request("Q1", "A", 5))
        self.assertTrue(db.request("Q2", "B", 5))
        self.assertEqual(db.owner[5], ("Q1", "A"))
        self.assertEqual(db.sets[("Q2", "B")].size, 0)
        self.assertEqual(db.reads, 1)
        db.finish("Q1")
        self.assertIsNone(db.owner[5])
        self.assertTrue(db.request("Q2", "B", 5))   # found on the free list, no read
        self.assertEqual(db.owner[5], ("Q2", "B"))
        self.assertEqual(db.reads, 1)
        db.check()

    def test_sets_behave_as_standalone_caches(self):
        # Without sharing, each locality set holds what a cache of its own size would hold,
        # and the free list can only save reads.
        for seed in range(25):
            rng = random.Random(seed)
            k = rng.randrange(1, 4)
            sets = {}
            for j in range(k):
                sets[j] = (rng.randrange(1, 5), rng.choice(["lru", "mru", "fifo"]))
            n_frames = sum(l for l, _ in sets.values()) + rng.randrange(1, 4)
            db = DBMIN(n_frames)
            self.assertTrue(db.start("Q", sets))
            traces = {j: [] for j in sets}
            trace = []
            for _ in range(300):
                j = rng.randrange(k)
                p = 100 * j + (rng.randrange(8) if rng.random() < 0.5 else rng.randrange(3))
                trace.append(((("Q", j)), p))
                traces[j].append(p)
                db.request("Q", j, p)
                db.check()
            plain_misses = 0
            for j, (l, policy) in sets.items():
                states = plain_cache(traces[j], l, policy)
                self.assertEqual(sorted(db.sets[("Q", j)].pages), states[-1])
                before = [[]] + states[:-1]
                plain_misses += sum(1 for p, s in zip(traces[j], before) if p not in s)
            self.assertLessEqual(db.reads, plain_misses)
            self.assertEqual(db.reads, reference_model(
                n_frames, {("Q", j): v for j, v in sets.items()}, trace))

    def test_random_with_sharing_and_admission(self):
        for seed in range(25):
            rng = random.Random(500 + seed)
            n_frames = rng.randrange(4, 12)
            db = DBMIN(n_frames)
            running = []
            for step in range(400):
                if rng.random() < 0.05 or not running:
                    q = f"Q{step}"
                    files = {f: (rng.randrange(1, max(2, n_frames // 2)), rng.choice(["lru", "mru", "fifo"]))
                             for f in range(rng.randrange(1, 3))}
                    if db.start(q, files):
                        running.append(q)
                elif rng.random() < 0.05:
                    q = running.pop(rng.randrange(len(running)))
                    running.extend(db.finish(q))
                else:
                    q = rng.choice(running)
                    f = rng.choice(db.active[q])
                    reads = db.reads
                    p = rng.randrange(20)
                    p_resident = p in db.owner
                    hit = db.request(q, f, p)
                    self.assertEqual(hit, p_resident)
                    self.assertEqual(db.reads - reads, 0 if hit else 1)
                    self.assertIn(p, db.owner)
                db.check()
                self.assertEqual(sorted(running), sorted(db.active))


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

History

Effelsberg and Haerder (1984) surveyed database buffer management and the use of access patterns. Sacco and Schkolnick (1982) proposed the hot set model. Chou and DeWitt (1985) defined the query locality set model and DBMIN, and evaluated it with a simulation that combined real traces and distributions, with a CPU model of a VAX-11/750 and the WiSS storage system, on six query types over relations of Wisconsin benchmark style with 182-byte tuples. With 1 to 32 concurrent queries, the simple policies (RAND, FIFO, CLOCK) thrashed as the load grew, and DBMIN had 7 to 13% more throughput than the hot set algorithm.

References

  1. An evaluation of buffer management strategies for relational database systems, the query locality set model and its reference patterns, the DBMIN algorithm with its three cases and its load controller (pp. 130 to 132), and the simulation results
  2. A mechanism for managing the buffer pool in a relational database system using the hot set model, the hot set model, the predecessor that DBMIN refines
  3. Principles of database buffer management, the survey of buffer allocation and replacement that the DBMIN paper builds on
  4. Approximating block accesses in database organizations, the formula for the expected number of pages touched by k random record accesses

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.average
  • 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)
WritingW2 basic
  • a scene preset for the example