Algorithm Search⌘K

Algorithmcore

Fuzzy checkpoint

Also called fuzzy checkpointing.

A checkpoint that records the dirty pages and active transactions without stopping new updates or forcing pages to disk.

Time
O(n + m + d) worst
Space
O(m + d) extra
Where
d = the entries of the dirty page table; m = the entries of the transaction table; n = the log records from the begin_checkpoint record to the end of the log
Properties
deterministic
Origin
C. Mohan, Don Haderle, Bruce Lindsay, Hamid Pirahesh, Peter Schwarz, 1992

A fuzzy checkpoint is a checkpoint that writes the transaction table and the dirty page table to the log without writing any data page and without stopping transactions. Restart then starts its scan at the checkpoint, and starts redo at the oldest recLSN in the dirty page table, which can be older than the checkpoint. The checkpointing page gives the general technique and compares the kinds of checkpoint, and ARIES recovery gives the full restart, with tables copied in one step; this page is about the checkpoint itself when the two tables are copied at different moments while transactions keep running, and about the merge rule that the analysis pass needs then. The nonquiescent checkpoint of undo/redo logging is a different scheme: it does not stop transactions either, but it writes every dirty item.

In plain words

A database keeps a journal of changes and a list of the pages in memory that are newer than their disk copies. For each such page it remembers the place in the journal of its oldest change not yet on disk. A checkpoint is a bookmark in the journal that saves this list and the list of running transactions, so that after a crash the system can skip the old part of the journal.

The fuzzy kind writes no pages and does not wait. It writes a "begin" mark, copies the two lists while work goes on, perhaps one now and one a little later, and then writes an "end" mark with the copies. Because the copies were made at different moments, restart reads the journal from the "begin" mark and uses what it reads there to fix the copies.

The problem

The model is the one of ARIES. Each page has a pageLSN, the log sequence number of its last change. The buffer manager uses steal and no-force and obeys the WAL rule: before it writes a page, it flushes the log up to the page's pageLSN. A commit is forced. A rollback writes compensation log records. Normal processing keeps two tables in memory:

  • the transaction table (ATT): for each transaction that has begun and not ended, its status, its lastLSN and its undoNext, the next update to undo;
  • the dirty page table (DPT): for each page whose buffer copy differs from the disk, its recLSN, the LSN of the first change since the page was last written.

A checkpoint must let restart rebuild both tables as they were at the crash, after reading only the log from the checkpoint on. It may not write data pages, and it may not stop other transactions. Copying a large table takes time, so the system may copy the ATT and the DPT at different moments, and transactions may begin, change pages, commit and end between the copies.

The algorithm

  1. FUZZY-CHECKPOINT() ▷ other steps may run between the lines
  2. 1b ← APPEND(⟨BEGIN_CHECKPOINT⟩)
  3. 2att ← a copy of the ATT (status, lastLSN, undoNext of each transaction)
  4. 3dpt ← a copy of the DPT (recLSN of each dirty page) ▷ before or after L2, but after L1
  5. 4e ← APPEND(⟨END_CHECKPOINT, att, dpt⟩)
  6. 5flush the log up to e
  7. 6master ← b ▷ one atomic write of a block
  8. ANALYSIS()
  9. 7start ← master, or 1 if there is none; ATT ← ∅; DPT ← ∅; ended ← ∅
  10. 8for each record r of the stable log with r.lsn ≥ start, in LSN order do
  11. 9if r belongs to a transaction T and is not END then ATT[T].lastLSN ← r.lsn; set undoNext and status from r
  12. 10if r is UPDATE or CLR and r.page ∉ DPT then DPT[r.page] ← r.lsn
  13. 11if r is END then remove T from the ATT; add T to ended
  14. 12if r is END_CHECKPOINT then
  15. 13for each (T, entry) in r.att with T ∉ ATT and T ∉ ended do ATT[T] ← entry
  16. 14for each (P, recLSN) in r.dpt do DPT[P] ← min(DPT[P], recLSN) ▷ recLSN if P ∉ DPT
  17. 15for each committed T in the ATT do append ⟨END, T⟩ and remove T
  18. 16redoLSN ← the smallest recLSN in the DPT (the end of the log if it is empty)
  19. RECOVER()
  20. 17ANALYSIS(); redo from redoLSN with the pageLSN test, as in ARIES
  21. 18undo the transactions left in the ATT, largest undoNext first, writing CLRs
  22. 19flush the log

The checkpoint (lines L1 to L6). It costs two log records, one log flush and one write of the master record, plus the time to copy the tables. Both copies come after the begin record. The master record is written only after the end record is on disk, so it never names a checkpoint whose tables were lost.

The scan (lines L8 to L11). Analysis reads every record from the begin record on. Each record of a transaction sets the transaction's entry: an update makes itself the head of the chain, a CLR moves the head to its undoNextLSN, an abort leaves the head at its prevLSN, and a commit marks the transaction committed. The first update or CLR of a page puts the page in the DPT with that LSN.

The merge (lines L12 to L14). The copies describe the state at two moments between the begin and end records. The scan has already seen every record after the begin record, so it knows more than the copies about every transaction and page that it has met. Line L13 adds from the copy only the transactions that the scan has not met and that have not ended since the begin record. Line L14 adds the copied pages and keeps the smaller recLSN for a page that is in both. A transaction whose records are all before the begin record, and a page whose oldest missing change is before it, come only from the copies.

Redo and undo (lines L15 to L19). These are the passes of ARIES. Redo can start before the checkpoint, at the oldest recLSN. Undo can go back past the checkpoint, along the chain of a transaction that began before it. The flush at the end puts the END records of recovery on disk before new work begins.

Example

Pages P=10P = 10, Q=20Q = 20, R=30R = 30, all with pageLSN 0. Locks are held until END.

LSN record prevLSN note
1 BEGIN T1T_1 0
2 UPDATE T1T_1, PP: 10 to 11 1 DPT: PP 2
3 BEGIN T2T_2 0
4 UPDATE T2T_2, QQ: 20 to 21 3 DPT: QQ 4
5 BEGIN_CHECKPOINT then the ATT is copied: T1T_1 (active, 2, 2), T2T_2 (active, 4, 4)
6 COMMIT T1T_1 2 log flushed to 6
7 END T1T_1 6
8 UPDATE T2T_2, RR: 30 to 31 4 DPT: RR 8; then PP is written to disk (11, pageLSN 2) and the DPT is copied: QQ 4, RR 8
9 END_CHECKPOINT with both copies log flushed to 9; master ←5\leftarrow 5
10 BEGIN T3T_3 0
11 UPDATE T3T_3, PP: 11 to 12 10 DPT: PP 11
12 COMMIT T2T_2 8 log flushed to 12

The END record of T2T_2 is still in the log tail when the system crashes. The disk holds P=11P = 11 (pageLSN 2), Q=20Q = 20 and R=30R = 30 (pageLSN 0). Analysis starts at LSN 5.

LSN read ATT DPT note
5
6 T1T_1 committed
7 ended ={T1}= \{T_1\}
8 T2T_2 (active, 8, 8) RR 8
9 same QQ 4, RR 8 T1T_1 is in the copy but has ended: not added; T2T_2 is known; QQ comes from the copy
10, 11 T2T_2, T3T_3 (active, 11, 11) QQ 4, RR 8, PP 11
12 T2T_2 committed same line L15 then appends END T2T_2 as LSN 13

Redo starts at LSN 4, before the checkpoint. It reads 9 records and the 3 pages, and applies LSN 4 (Q=21Q = 21), LSN 8 (R=31R = 31) and LSN 11 (P=12P = 12). Undo rolls back T3T_3: CLR at LSN 14 sets P=11P = 11 with undoNextLSN 0, and END T3T_3 is LSN 15. The result is P=11P = 11, Q=21Q = 21, R=31R = 31, the writes of the committed T1T_1 and T2T_2.

Three wrong choices give wrong results on this run. Without the ended set, line L13 takes T1T_1 back from the copy as an active loser, and undo puts P=10P = 10, which removes a committed write. If redo started at the begin record, LSN 4 would be skipped and QQ would stay 20. And the DPT copy does not hold PP, because PP was written just before the copy; the scan finds PP again at LSN 11. The test file builds this run and the wrong variants.

Correctness

Theorem. Assume the WAL rule, a forced commit, strict page locks held until END, and lines L2 and L3 run after line L1 and before line L4. After a crash at any point, also during recovery, any number of times, the DPT that analysis builds holds every page with a logged change missing from the disk, with a recLSN at most that change's LSN, and the ATT holds exactly the transactions with a record in the stable log and no END record, each with its exact lastLSN, undoNext and status. So recovery with the redo and undo passes of ARIES gives the result of the crash recovery problem.

The proof has two parts. For the DPT, a missing change at or after the begin record is read by the scan, and the minimum at line L14 never raises a value. A missing change before the begin record was missing at the moment of the DPT copy too, since that copy came after the begin record, so the copy held its page with a recLSN at most that change. For the ATT, a transaction with a record after the begin record gets its entry from its last record, which the scan reads. A transaction with all its records before the begin record and no END was active at the ATT copy, which came after the begin record, so the copy is exact for it. A transaction that ended after the begin record is in the ended set and is not added back. The full proof is in the correctness proof below. It also shows that the ARIES rule, which replaces the recLSN with the copied value instead of taking the minimum, is correct: if a change on the page after the begin record is older than the copied recLSN, the page was written after that change. The tests crash after every step of seeded workloads, and after steps of recovery, and check the final state with both rules.

Proof: Analysis after a fuzzy checkpoint with tables copied at different times rebuilds exact tablesfull

Model. Each page holds one value and a pageLSN. Locking is strict at the level of pages: a transaction that wrote a page holds its lock until its END record. The buffer obeys the WAL rule: a page with pageLSN nn is written to disk only after the log is stable up to nn. A commit is reported only after its commit record is stable. A rollback writes one CLR per undone update, with undoNextLSN equal to the prevLSN of that update. A crash keeps the disk, the stable log RR and the master record, and loses the rest. The log only grows at its end, so RR is a prefix of the log that the run appended.

In normal processing the system keeps two tables exactly. The ATT holds each transaction that has a BEGIN record and no END record, with its status, its lastLSN and its undoNext (the head of its chain: the next update to undo). The DPT holds each page whose buffer copy differs from its disk copy, with its recLSN, the LSN of the first change since the page was last written.

A checkpoint runs lines L1 to L6 at four times: line L1 at tbt_b, which appends record bb; line L2 at tat_a; line L3 at tdt_d; lines L4 to L6 at tet_e, which append record ee, make it stable and set the master record to bb. The only constraints are tb<ta<tet_b < t_a < t_e and tb<td<tet_b < t_d < t_e. Any other step can run between them. A page version with pageLSN nn holds the effects of exactly the updates and CLRs on that page with LSN at most nn (the page invariant of the ARIES proof). Say that a record rr on page PP is missing if rr.lsn is larger than the pageLSN of the disk copy of PP.

Lemma 0 (live DPT). At every time of normal processing, for every update or CLR rr on a page PP that is missing, PP is in the live DPT and its recLSN is at most rr.lsn.

Proof. When rr changes the buffer copy, either PP was dirty, and its recLSN is the first change of the current dirty period, which is at most rr.lsn, or PP becomes dirty with recLSN rr.lsn. A write of PP to disk puts all changes made so far on disk, so no record on PP stays missing, and removing PP is safe. After a recovery, which runs before normal processing goes on, redo has applied every missing record of RR (by Lemma 1 for that recovery, which uses this lemma only for earlier times, so the proof is by induction on the number of crashes, and by the pageLSN test), and the first record that redo applies to PP sets the recLSN; every missing record on PP is at or after it. CLRs that recovery writes follow the first case. □\square

Lemma 1 (coverage). After analysis (lines L7 to L16), for every update or CLR rr in RR on page PP that is missing, PP is in the DPT and DPT[P]≤r[P] \le r.lsn. Hence redoLSN ≤r\le r.lsn.

Proof. If there is no master record, analysis reads all of RR, and line L10 puts PP in the table at its first record, at most rr.lsn. Otherwise the master names bb, and by line L5 before line L6 the record ee is in RR. Values in the table only go down after they are set, since line L14 takes a minimum. Two cases.

Case rr.lsn ≥b\ge b. Line L8 reads rr. If PP is not in the table then, line L10 sets DPT[P]=r[P] = r.lsn. If it is, its value came from an earlier scanned record, which is smaller than rr, or from line L14, which only stores LSNs of records appended before td<tet_d < t_e; if rr comes after ee these are smaller than rr.lsn, and if rr comes before ee, line L10 or an earlier record already gave a value at most rr.lsn, and the minimum keeps it.

Case rr.lsn <b< b. Then rr was appended before tb<tdt_b < t_d. The page PP was not written to disk between rr and the crash, since that write would hold rr. So rr was missing at tdt_d, and Lemma 0 gives that the live DPT held PP with recLSN at most rr.lsn at tdt_d. Line L3 copied that entry, and line L14 makes DPT[P][P] at most it. □\square

Lemma 2 (transactions). After line L14 has run for ee and the scan has ended, the ATT holds exactly the transactions with a record in RR and no END record in RR. For each one, lastLSN is the LSN of its last record in RR, undoNext is the head of its chain in RR, and the status is committed if and only if its COMMIT record is in RR.

Proof. Line L9 sets an entry from one record alone: lastLSN is that record's LSN, and undoNext is the LSN of an update, the undoNextLSN of a CLR, the prevLSN of an abort (the chain head then, since no CLR precedes the abort), or 0 after a BEGIN. A COMMIT can only be followed by the END. So once the scan has read the last record of TT in RR, the entry is exact. Take TT with a record in RR and no END in RR.

Case: TT has a record in RR at or after bb. The scan reads its last record, and only an END removes it. Line L13 cannot overwrite the entry, since it adds only missing transactions; if TT first appears after ee, line L13 may add the copy first and the scan then overwrites it.

Case: all records of TT in RR are before bb. TT has no END before tet_e: an END before tbt_b would be in RR, and an END between tbt_b and tet_e would be in RR (line L5 makes everything up to ee stable) at or after bb. So TT was in the live ATT at tat_a. Any record of TT appended between tbt_b and tet_e would be in RR at or after bb, so TT appended no record between tbt_b and tat_a, and the copy holds the exact entry for its last record, which is before bb. At ee, TT is not in the table (no scanned record) and not in the ended set (no END after bb), so line L13 adds it, and no later record changes it.

Now take TT with an END in RR. If the END is at or after bb, line L11 removes TT and puts it in the ended set, so line L13 does not add it back, and if the END is after ee, line L11 removes the entry that line L13 added. If the END is before bb, TT was not in the live ATT at tat_a, so it is not in the copy, and the scan meets none of its records. Finally, every transaction in the copy has its BEGIN before tat_a, so in RR. □\square

Theorem. If the redo and undo passes of ARIES recovery (lines L17 and L18) run after this analysis, and recovery forces the log at its end (line L19), then after a crash at any point, also during recovery, any number of times, a recovery that runs to the end leaves every page with the value of the newest uncompensated update by a transaction whose commit record is in RR, or with its initial value.

Proof. The correctness proof of ARIES recovery uses two properties of analysis: its Lemma 3 (every missing record is covered by the DPT) and its Lemma 4 (the ATT holds exactly the losers, with the heads of their chains). Lemmas 1 and 2 give both for tables copied at different times, and the rest of that proof does not depend on how the tables were built. A crash during recovery leaves the master record unchanged and a stable log that only has more records at its end, so Lemmas 0 to 2 apply to it. Line L19 puts the END records of recovery in RR before normal processing goes on; without it, a loser whose END was lost and whose records are all before a later checkpoint would appear neither in the scan nor in that checkpoint's copy. □\square

Remark (the ARIES merge rule). ARIES, at the end_checkpoint record, sets DPT[P][P] to the copied recLSN instead of the minimum. This is also correct. Let cc be the copied value and rr a missing record on PP. If rr is before bb, Lemma 0 at tdt_d gives c≤rc \le r.lsn. If rr is at or after bb and rr.lsn <c< c, then at tdt_d the dirty period of PP began at cc, after rr, so PP was written between rr and cc and rr is not missing. So cc is at most every missing record on PP. The test file runs the crash tests with both rules.

Remark (why the times matter). The proof of Lemma 1 uses td>tbt_d > t_b: a page dirtied before tbt_b and copied before it was dirtied is in neither the scan nor the copy. The proof of Lemma 2 uses ta>tbt_a > t_b in the same way, and it uses the ended set when ta<tet_a < t_e: a transaction that ends between tat_a and tet_e is in the copy, and without the ended set line L13 would add it back as a loser. The test file builds the first and the last of these cases.

Complexity

All bounds are worst case and are proved by counting the steps of the pseudocode.

  • The checkpoint appends two records, flushes the log once and writes the master record once. Copying the tables takes O(m+d)O(m + d) time and the end record has size O(m+d)O(m + d). It writes no data page.
  • Analysis reads the nn records from the begin record to the end, O(1)O(1) each with hash tables, plus O(m+d)O(m + d) for the merge.
  • Redo reads the log from the smallest recLSN, and it reads each page in the DPT once.
  • Undo reads the records of the losers, back to the oldest first record of a loser.

So the checkpoint bounds analysis by the log since the checkpoint, but it bounds redo only through the oldest recLSN, and undo only through the oldest loser. In the test with 50 committed transactions, all pages written every 10 transactions, and one transaction still active at the crash, analysis reads 3 records with the checkpoint and 203 without it, and redo reads 4 records with the checkpoint and 202 without it, since without the copied DPT analysis cannot know that the pages were written (a measurement of the implementation).

Properties

  • No page writes. The checkpoint never writes a data page, so it does not compete with transactions for the disk.
  • No waiting. Transactions run during the whole checkpoint. The only short pauses are those needed to copy each table consistently.
  • Restartable. A crash during the checkpoint leaves the master record at the previous complete checkpoint.
  • Exact tables. After analysis, the tables are those of a full scan of the log, for the transactions, and cover all missing changes, for the pages.
  • Depends on page writing. The redo start moves forward only as pages are written. A page that stays dirty keeps an old recLSN and holds back the redo start.

Variants and improvements

  • Tables copied in one step. The simplest version copies both tables when it builds the end record. Then the merge does not need the ended set, but the copy must be made while no table changes.
  • ARIES. ARIES copies the dirty page table a little at a time, and replaces the recLSN with the copied value at the end_checkpoint record. ARIES also notes that a restart without an analysis pass could start redo at the smaller of the begin record and the smallest recLSN in the end record.
  • Background page writing. Writing the pages with the oldest recLSN, also hot pages, moves the redo start forward. It is separate from the checkpoint but sets the value of each checkpoint.
  • Consistent and two-checkpoint schemes. The checkpointing page describes checkpoints that write dirty pages, which make redo start at the checkpoint or at the one before.
  • Snapshots in distributed systems. A global snapshot also records a state without stopping the processes, but it records process states and messages, not log positions.

When to use it

Use a fuzzy checkpoint in a disk-based system with steal and no-force and a large buffer pool, where writing all dirty pages at once would stall transactions for seconds. It needs pageLSNs and a recovery that can start redo before the checkpoint, as ARIES does. A system without a DPT, such as the plain undo/redo logging on this site, must write the dirty pages instead. A main-memory system that writes snapshots does not need a DPT at all.

Pitfalls

  • Re-adding an ended transaction. If the ATT copy is older than the end record, a transaction can commit and end in between. Without the ended set it comes back as a loser and its committed work is undone.
  • Copying before the begin record. A page dirtied between the copy and the begin record is in neither the copy nor the scan, and its change is lost if the page was not written. The same holds for a transaction that wrote between the copy and the begin record.
  • Redo from the begin record. A page in the DPT copy can hold an old missing change. Start at the smallest recLSN.
  • The master record before the flush. If the end record is lost with the log tail, the master names a checkpoint without tables.
  • Not flushing at the end of recovery. If the END records written by recovery are lost and a later checkpoint is taken, a loser with all its records before that checkpoint is in neither the copy nor the scan.
  • Hot pages. A page that is changed all the time is never clean, so its recLSN stays old and every checkpoint keeps the same redo start. ARIES asks that such pages also be written reasonably often.

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.

fuzzy_checkpoint.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fuzzy-checkpoint/. The authors are listed in prov/EF79FV.jsonl.

"""A fuzzy checkpoint whose two tables are copied at different times, and the
analysis pass that merges them with the log.

Model: each page holds one integer. Stable storage is the disk (page ->
(pageLSN, value)), the stable log and the master record. Volatile storage is
the buffer (dirty pages only), the log tail, the transaction table (ATT) and
the dirty page table (DPT). The buffer policy is steal and no-force with the
WAL rule. Rollback, in normal processing and in recovery, writes compensation
log records (CLRs). The LSN of a record is its index in the log plus 1.

A checkpoint is four separate steps, and any other step can run between them:
ckpt_begin (append BEGIN_CHECKPOINT), copy_att, copy_dpt (in either order) and
ckpt_end (append END_CHECKPOINT with both copies, force it, set the master).
No page is written by a checkpoint.

recovery() is a generator that yields after each step, so that a test can
crash inside recovery. Redo and undo are those of ARIES.
"""

from dataclasses import dataclass
from typing import Iterator


@dataclass(frozen=True)
class Rec:
    lsn: int
    kind: str  # BEGIN, UPDATE, CLR, COMMIT, ABORT, END, BEGIN_CHECKPOINT, END_CHECKPOINT
    txn: int = 0
    prev: int = 0  # prevLSN, 0 for the first record of a transaction
    page: str = ""
    before: int = 0
    after: int = 0
    undo_next: int = 0  # CLR only
    att: tuple = ()  # END_CHECKPOINT: (txn, status, lastLSN, undoNext) for each entry
    dpt: tuple = ()  # END_CHECKPOINT: (page, recLSN) for each entry


TXN_KINDS = ("BEGIN", "UPDATE", "CLR", "COMMIT", "ABORT")


class Db:
    def __init__(self, disk: dict, log: list | None = None, master: int = 0) -> None:
        self.disk = {p: (v if isinstance(v, tuple) else (0, v)) for p, v in disk.items()}
        self.log: list[Rec] = list(log or [])
        self.master = master
        self.tail: list[Rec] = []
        self.buf: dict[str, list] = {}  # dirty page -> [pageLSN, value]
        self.att: dict[int, list] = {}  # txn -> [status, lastLSN, undoNext]
        self.dpt: dict[str, int] = {}  # dirty page -> recLSN
        self.ck: dict = {}  # the checkpoint in progress
        self.stats = {"analysis": 0, "redo": 0, "undo": 0, "page_reads": 0}

    # ---- log, buffer, disk ------------------------------------------------
    def rec(self, lsn: int) -> Rec:
        return self.log[lsn - 1] if lsn <= len(self.log) else self.tail[lsn - len(self.log) - 1]

    def _append(self, **fields) -> Rec:
        r = Rec(lsn=len(self.log) + len(self.tail) + 1, **fields)
        self.tail.append(r)
        return r

    def flush_log(self, upto: int | None = None) -> None:
        n = len(self.tail) if upto is None else max(0, upto - len(self.log))
        self.log += self.tail[:n]
        self.tail = self.tail[n:]

    def value(self, p: str) -> int:
        return self.buf[p][1] if p in self.buf else self.disk[p][1]

    def page_lsn(self, p: str) -> int:
        return self.buf[p][0] if p in self.buf else self.disk[p][0]

    def _change(self, p: str, lsn: int, v: int) -> None:
        if p not in self.buf:
            self.dpt[p] = lsn  # the first change since the page was clean
        self.buf[p] = [lsn, v]

    def flush_page(self, p: str) -> None:
        if p not in self.buf:
            return
        lsn, v = self.buf.pop(p)
        self.flush_log(lsn)  # the WAL rule
        self.disk[p] = (lsn, v)
        del self.dpt[p]

    def crash(self) -> "Db":
        return Db(dict(self.disk), list(self.log), self.master)

    def _chain(self, lsn: int) -> int:
        """Normalize a chain pointer: a BEGIN record ends the chain."""
        return 0 if lsn == 0 or self.rec(lsn).kind == "BEGIN" else lsn

    # ---- normal processing ------------------------------------------------
    def begin(self, t: int) -> None:
        r = self._append(kind="BEGIN", txn=t)
        self.att[t] = ["active", r.lsn, 0]

    def update(self, t: int, p: str, w: int) -> None:
        r = self._append(kind="UPDATE", txn=t, prev=self.att[t][1], page=p, before=self.value(p), after=w)
        self._change(p, r.lsn, w)
        self.att[t][1:] = [r.lsn, r.lsn]

    def commit(self, t: int) -> None:
        r = self._append(kind="COMMIT", txn=t, prev=self.att[t][1])
        self.flush_log(r.lsn)
        self.att[t][:2] = ["committed", r.lsn]

    def end(self, t: int) -> None:
        self._append(kind="END", txn=t, prev=self.att[t][1])
        del self.att[t]

    def abort(self, t: int) -> None:
        r = self._append(kind="ABORT", txn=t, prev=self.att[t][1])
        self.att[t][:2] = ["aborting", r.lsn]

    def undo_step(self, t: int) -> bool:
        """Undo the next update of t, or end t. Return True when t has ended."""
        status, last, nxt = self.att[t]
        if nxt == 0:
            self.end(t)
            return True
        r = self.rec(nxt)
        if r.kind == "UPDATE":
            c = self._append(kind="CLR", txn=t, prev=last, page=r.page, after=r.before, undo_next=self._chain(r.prev))
            self._change(r.page, c.lsn, r.before)
            self.att[t][1:] = [c.lsn, c.undo_next]
        elif r.kind == "CLR":
            self.att[t][2] = r.undo_next
        else:  # ABORT
            self.att[t][2] = self._chain(r.prev)
        return False

    # ---- the fuzzy checkpoint ---------------------------------------------
    def ckpt_begin(self) -> None:
        b = self._append(kind="BEGIN_CHECKPOINT")  # @line L1
        self.ck = {"b": b.lsn}

    def copy_att(self) -> None:
        self.ck["att"] = tuple((t, *e) for t, e in sorted(self.att.items()))  # @line L2

    def copy_dpt(self) -> None:
        self.ck["dpt"] = tuple(sorted(self.dpt.items()))  # @line L3

    def ckpt_end(self) -> None:
        e = self._append(kind="END_CHECKPOINT", att=self.ck["att"], dpt=self.ck["dpt"])  # @line L4
        self.flush_log(e.lsn)  # @line L5
        self.master = self.ck["b"]  # @line L6
        self.ck = {}

    # ---- recovery -----------------------------------------------------------
    def merge_checkpoint(self, att: dict, dpt: dict, ended: set, r: Rec) -> None:
        for t, status, last, nxt in r.att:  # @line L13
            if t not in att and t not in ended:  # @line L13
                att[t] = [status, last, nxt]
        for p, rec_lsn in r.dpt:  # @line L14
            dpt[p] = min(dpt.get(p, rec_lsn), rec_lsn)  # @line L14

    def analysis(self, start: int | None = None, use_checkpoints: bool = True) -> tuple[dict, dict, int]:
        """Rebuild the ATT and the DPT from the stable log. Return them and the
        LSN where redo starts. The committed transactions are left in the ATT
        with status committed."""
        if start is None:
            start = self.master or 1  # @line L7
        att: dict[int, list] = {}  # @line L7
        dpt: dict[str, int] = {}  # @line L7
        ended: set[int] = set()  # @line L7
        for r in self.log[start - 1 :]:  # @line L8
            self.stats["analysis"] += 1
            if r.kind in TXN_KINDS:  # @line L9
                e = att.setdefault(r.txn, ["active", 0, 0])
                e[1] = r.lsn
                if r.kind in ("UPDATE",):
                    e[2] = r.lsn
                elif r.kind == "CLR":
                    e[2] = r.undo_next
                elif r.kind == "ABORT":
                    e[0], e[2] = "aborting", self._chain(r.prev)
                elif r.kind == "COMMIT":
                    e[0] = "committed"
            if r.kind in ("UPDATE", "CLR") and r.page not in dpt:  # @line L10
                dpt[r.page] = r.lsn  # @line L10
            if r.kind == "END":  # @line L11
                att.pop(r.txn, None)  # @line L11
                ended.add(r.txn)  # @line L11
            if r.kind == "END_CHECKPOINT" and use_checkpoints:  # @line L12
                self.merge_checkpoint(att, dpt, ended, r)
        redo_lsn = min(dpt.values(), default=len(self.log) + 1)  # @line L16
        return att, dpt, redo_lsn

    def recovery(self) -> Iterator[str]:
        self.buf, self.tail, self.att, self.dpt, self.ck = {}, [], {}, {}, {}
        self.stats = {"analysis": 0, "redo": 0, "undo": 0, "page_reads": 0}
        att, dpt, redo_lsn = self.analysis()
        for t in sorted(att):  # @line L15
            if att[t][0] == "committed":
                self._append(kind="END", txn=t, prev=att[t][1])  # @line L15
                del att[t]
        self.att = att
        yield "analysis"
        fetched: set[str] = set()
        for r in self.log[redo_lsn - 1 :]:  # @line L17: redo, repeating history
            self.stats["redo"] += 1
            if r.kind not in ("UPDATE", "CLR") or r.page not in dpt or r.lsn < dpt[r.page]:
                continue
            if r.page not in fetched:
                fetched.add(r.page)
                self.stats["page_reads"] += 1
            if self.page_lsn(r.page) < r.lsn:
                self._change(r.page, r.lsn, r.after)
                yield "redo"
        while self.att:  # @line L18: undo the losers, largest undoNext first
            t = max(self.att, key=lambda u: self.att[u][2])
            if self.att[t][2]:
                self.stats["undo"] += 1
            self.undo_step(t)
            yield "undo"
        self.flush_log()  # @line L19
        yield "flush"

    def recover(self) -> None:
        for _ in self.recovery():
            pass

    def state(self) -> dict[str, int]:
        return {p: self.value(p) for p in sorted(self.disk)}
test_fuzzy_checkpoint.py 362 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fuzzy-checkpoint/. The authors are listed in prov/EF79FV.jsonl.

"""Crash-injection tests for fuzzy checkpoints with tables copied at different
times.

A seeded generator builds a strict workload against a live database: page
locks are held until the END record, commits are forced, aborts roll back one
CLR at a time, page writes (steals) and log flushes come at random places, and
the steps of each checkpoint (begin, the two copies in a random order, end) are
spread among the other steps. Each test replays a prefix, crashes, recovers and
compares the result with the oracle: the writes of the committed transactions,
applied in commit order.
"""

import copy
import random
import unittest

from fuzzy_checkpoint import Db

PAGES = "pqrst"
INIT = {p: 0 for p in PAGES}


def make_workload(db: Db, rng: random.Random, n_ops: int, first_txn: int = 1) -> list:
    ops: list = []
    owner: dict[str, int] = {}
    state: dict[int, str] = {}  # txn -> active, committed or aborting
    next_txn, next_val = first_txn, 100 * first_txn
    ck: list = []  # the checkpoint steps still to do
    while len(ops) < n_ops:
        roll = rng.random()
        active = [t for t, s in state.items() if s == "active"]
        if roll < 0.10 and len(state) < 4:
            op = ("begin", next_txn)
            state[next_txn] = "active"
            next_txn += 1
        elif roll < 0.42 and active:
            t = rng.choice(active)
            free = [p for p in PAGES if owner.get(p, t) == t]
            if not free:
                continue
            next_val += 1
            op = ("update", t, rng.choice(free), next_val)
            owner[op[2]] = t
        elif roll < 0.52 and active:
            t = rng.choice(active)
            if rng.random() < 0.7:
                op = ("commit", t)
                state[t] = "committed"
            else:
                op = ("abort", t)
                state[t] = "aborting"
        elif roll < 0.64 and len(state) > len(active):
            t = rng.choice(sorted(t for t in state if state[t] != "active"))
            op = ("end", t) if state[t] == "committed" else ("undo_step", t)
        elif roll < 0.76 and db.buf:
            op = ("flush_page", rng.choice(sorted(db.buf)))
        elif roll < 0.80:
            op = ("flush_log",)
        elif roll < 0.92:
            if not ck:
                ck = ["copy_att", "copy_dpt"]
                rng.shuffle(ck)
                ck = ["ckpt_begin"] + ck + ["ckpt_end"]
            op = (ck.pop(0),)
        else:
            continue
        done = apply_op(db, op)
        if done or op[0] == "end":
            del state[op[1]]
            owner = {p: u for p, u in owner.items() if u != op[1]}
        ops.append(op)
    return ops


def apply_op(db: Db, op: tuple):
    return getattr(db, op[0])(*op[1:])


def oracle(base: dict, ops: list) -> dict:
    state = dict(base)
    pending: dict[int, list] = {}
    for op in ops:
        if op[0] == "begin":
            pending[op[1]] = []
        elif op[0] == "update":
            pending[op[1]].append((op[2], op[3]))
        elif op[0] == "commit":
            for p, w in pending[op[1]]:
                state[p] = w
    return state


def replay(snap: tuple, ops: list) -> Db:
    db = Db(dict(snap[0]), list(snap[1]), snap[2])
    for op in ops:
        apply_op(db, op)
    return db


def snapshot(db: Db) -> tuple:
    return dict(db.disk), list(db.log), db.master


def disk_state(db: Db) -> dict:
    return {p: v for p, (_, v) in sorted(db.disk.items())}


def recover_and_flush(db: Db) -> dict:
    db.recover()
    for p in sorted(db.buf):
        db.flush_page(p)
    return disk_state(db)


def losers(att: dict) -> dict:
    return {t: (e[1], e[2]) for t, e in att.items() if e[0] != "committed"}


class TestCrashInjection(unittest.TestCase):
    def test_crash_after_every_prefix(self):
        for seed in range(25):
            rng = random.Random(seed)
            ops = make_workload(Db(INIT), rng, 80)
            for k in range(len(ops) + 1):
                db = replay((INIT, [], 0), ops[:k]).crash()
                self.assertEqual(recover_and_flush(db), oracle(INIT, ops[:k]), (seed, k))

    def test_analysis_tables(self):
        # The merged tables cover every logged change missing from the disk,
        # and the losers agree with an analysis of the whole log.
        checked = 0
        for seed in range(25):
            rng = random.Random(500 + seed)
            ops = make_workload(Db(INIT), rng, 80)
            for k in range(len(ops) + 1):
                db = replay((INIT, [], 0), ops[:k]).crash()
                att, dpt, redo_lsn = db.analysis()
                for r in db.log:
                    if r.kind in ("UPDATE", "CLR") and r.lsn > db.disk[r.page][0]:
                        self.assertIn(r.page, dpt, (seed, k, r))
                        self.assertLessEqual(dpt[r.page], r.lsn, (seed, k, r))
                        self.assertLessEqual(redo_lsn, r.lsn)
                        checked += 1
                full_att, _, _ = db.analysis(start=1, use_checkpoints=False)
                self.assertEqual(losers(att), losers(full_att), (seed, k))
                self.assertEqual({t for t, e in att.items() if e[0] == "committed"}, {t for t, e in full_att.items() if e[0] == "committed"})
        self.assertGreater(checked, 1000)

    def test_crash_during_recovery(self):
        for seed in range(10):
            rng = random.Random(1000 + seed)
            ops = make_workload(Db(INIT), rng, 70)
            for k in range(0, len(ops) + 1, 3):
                want = oracle(INIT, ops[:k])
                for j in range(0, 30, 2):
                    db = replay((INIT, [], 0), ops[:k]).crash()
                    finished = False
                    for rounds in (j, j // 2):
                        steps = db.recovery()
                        for _ in range(rounds):
                            if next(steps, None) is None:
                                finished = True
                                break
                            x = rng.random()
                            if x < 0.4 and db.buf:
                                db.flush_page(rng.choice(sorted(db.buf)))
                            elif x < 0.6:
                                db.flush_log()
                        db = db.crash()
                    self.assertEqual(recover_and_flush(db), want, (seed, k, j))
                    if finished:
                        break

    def test_two_eras(self):
        for seed in range(10):
            rng = random.Random(2000 + seed)
            ops1 = make_workload(Db(INIT), rng, 60)
            cut = rng.randrange(len(ops1) + 1)
            db = replay((INIT, [], 0), ops1[:cut]).crash()
            db.recover()
            base = oracle(INIT, ops1[:cut])
            self.assertEqual(db.state(), base)
            # keep the dirty pages of recovery in the buffer, and go on
            ops2 = make_workload(copy.deepcopy(db), rng, 60, first_txn=1000)
            for k in range(len(ops2) + 1):
                live = copy.deepcopy(db)
                for op in ops2[:k]:
                    apply_op(live, op)
                got = recover_and_flush(live.crash())
                self.assertEqual(got, oracle(base, ops2[:k]), (seed, k))

    def test_aries_replace_rule_is_also_correct(self):
        # ARIES sets the recLSN to the copied value instead of the minimum.
        class Replace(Db):
            def merge_checkpoint(self, att, dpt, ended, r):
                for t, status, last, nxt in r.att:
                    if t not in att and t not in ended:
                        att[t] = [status, last, nxt]
                for p, rec_lsn in r.dpt:
                    dpt[p] = rec_lsn

            def crash(self):
                return Replace(dict(self.disk), list(self.log), self.master)

        for seed in range(20):
            rng = random.Random(3000 + seed)
            ops = make_workload(Db(INIT), rng, 80)
            for k in range(len(ops) + 1):
                db = Replace(dict(INIT))
                for op in ops[:k]:
                    apply_op(db, op)
                self.assertEqual(recover_and_flush(db.crash()), oracle(INIT, ops[:k]), (seed, k))


def page_example() -> Db:
    db = Db({"P": 10, "Q": 20, "R": 30})
    db.begin(1)
    db.update(1, "P", 11)
    db.begin(2)
    db.update(2, "Q", 21)
    db.ckpt_begin()
    db.copy_att()
    db.commit(1)
    db.end(1)
    db.update(2, "R", 31)
    db.flush_page("P")
    db.copy_dpt()
    db.ckpt_end()
    db.begin(3)
    db.update(3, "P", 12)
    db.commit(2)
    db.end(2)
    return db


class TestExampleAndPitfalls(unittest.TestCase):
    def test_page_example(self):
        db = page_example()
        self.assertEqual(db.master, 5)
        end = db.log[8]
        self.assertEqual(end.kind, "END_CHECKPOINT")
        self.assertEqual(end.att, ((1, "active", 2, 2), (2, "active", 4, 4)))
        self.assertEqual(end.dpt, (("Q", 4), ("R", 8)))
        db = db.crash()
        self.assertEqual(len(db.log), 12)
        self.assertEqual(db.disk, {"P": (2, 11), "Q": (0, 20), "R": (0, 30)})
        att, dpt, redo_lsn = db.analysis()
        self.assertEqual(att, {2: ["committed", 12, 8], 3: ["active", 11, 11]})
        self.assertEqual(dpt, {"Q": 4, "R": 8, "P": 11})
        self.assertEqual(redo_lsn, 4)
        db.recover()
        self.assertEqual(db.stats, {"analysis": 8, "redo": 9, "undo": 1, "page_reads": 3})
        self.assertEqual(db.state(), {"P": 11, "Q": 21, "R": 31})
        kinds = [(r.lsn, r.kind, r.txn) for r in db.log[12:]]
        self.assertEqual(kinds, [(13, "END", 2), (14, "CLR", 3), (15, "END", 3)])

    def test_readding_an_ended_transaction_is_wrong(self):
        class NoEnded(Db):
            def merge_checkpoint(self, att, dpt, ended, r):
                super().merge_checkpoint(att, dpt, set(), r)

        db = page_example().crash()
        bad = NoEnded(dict(db.disk), list(db.log), db.master)
        bad.recover()
        self.assertEqual(bad.state(), {"P": 10, "Q": 21, "R": 31})  # T1 was committed

    def test_redo_from_the_begin_record_is_wrong(self):
        class FromBegin(Db):
            def analysis(self, start=None, use_checkpoints=True):
                att, dpt, _ = super().analysis(start, use_checkpoints)
                return att, dpt, self.master

        db = page_example().crash()
        bad = FromBegin(dict(db.disk), list(db.log), db.master)
        bad.recover()
        self.assertEqual(bad.state()["Q"], 20)  # the committed write of T2 is lost

    def test_copy_before_the_begin_record_is_wrong(self):
        db = Db({"P": 10})
        db.copy_att()
        db.copy_dpt()
        early = dict(db.ck)
        db.begin(1)
        db.update(1, "P", 11)
        db.commit(1)
        db.end(1)
        db.ckpt_begin()
        db.ck.update(att=early["att"], dpt=early["dpt"])  # tables from before the begin record
        db.ckpt_end()
        db = db.crash()
        db.recover()
        self.assertEqual(db.state(), {"P": 10})  # the committed write is lost
        good = Db({"P": 10})
        good.begin(1)
        good.update(1, "P", 11)
        good.commit(1)
        good.end(1)
        good.ckpt_begin()
        good.copy_att()
        good.copy_dpt()
        good.ckpt_end()
        good = good.crash()
        good.recover()
        self.assertEqual(good.state(), {"P": 11})

    def test_master_before_the_force_is_wrong(self):
        class EarlyMaster(Db):
            def ckpt_end(self):
                self._append(kind="END_CHECKPOINT", att=self.ck["att"], dpt=self.ck["dpt"])
                self.master = self.ck["b"]  # set before the record is stable

        db = EarlyMaster({"P": 10})
        db.begin(1)
        db.update(1, "P", 11)
        db.commit(1)
        db.ckpt_begin()
        db.copy_att()
        db.copy_dpt()
        db.ckpt_end()
        db = db.crash()
        self.assertEqual(len(db.log), 3)
        self.assertEqual(db.master, 4)
        db.recover()
        self.assertEqual(db.state(), {"P": 10})  # the committed write is lost

    def test_checkpoint_bounds_analysis(self):
        def run(with_ckpt: bool) -> Db:
            db = Db(dict(INIT))
            rng = random.Random(9)
            for t in range(1, 51):
                db.begin(t)
                db.update(t, rng.choice(PAGES), t)
                db.commit(t)
                db.end(t)
                if t % 10 == 0:
                    for p in sorted(db.buf):
                        db.flush_page(p)
            db.begin(99)
            db.update(99, "p", -1)
            if with_ckpt:
                db.ckpt_begin()
                db.copy_att()
                db.copy_dpt()
                db.ckpt_end()
            db.update(99, "q", -2)
            db.flush_log()
            return db.crash()

        a, b = run(False), run(True)
        a.recover()
        b.recover()
        self.assertEqual(a.state(), b.state())
        self.assertEqual((a.stats["analysis"], b.stats["analysis"]), (203, 3))
        # without a checkpoint, analysis cannot know that the pages were written
        self.assertEqual((a.stats["redo"], b.stats["redo"]), (202, 4))


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

History

Haerder and Reuter (1983) listed fuzzy checkpoints among the checkpoint schemes of their survey. Mohan, Haderle, Lindsay, Pirahesh and Schwarz (1992) gave the form used in ARIES and in most later systems: begin and end records, the transaction table and the dirty page table with recLSNs in the end record, the master record written after the end record is on disk, and no pages written by the checkpoint. They allow the dirty page table to be gathered a little at a time, which is the case this page studies. Ramakrishnan and Gehrke present this form in their chapter on crash recovery.

References

  1. C. Mohan, Don Haderle, Bruce Lindsay, Hamid Pirahesh and Peter Schwarz, ARIES, a transaction recovery method supporting fine-granularity locking and partial rollbacks using write-ahead logging, ACM Transactions on Database Systems 17(1), 1992, pages 94 to 162, Section 4.4, Dirty_Pages Table (the recLSN), Section 5.4, Checkpoints (begin_chkpt and end_chkpt, the dirty pages table gathered a little at a time, no pages forced, the master record), and Section 6.1, Analysis Pass (the merge at end_chkpt, the redo start)
  2. Theo Haerder and Andreas Reuter, Principles of transaction-oriented database recovery, ACM Computing Surveys 15(4), 1983, pages 287 to 317, the section on checkpoint schemes, among them fuzzy checkpoints
  3. Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, third edition, McGraw-Hill, 2003, Chapter 18, the section on checkpointing (fuzzy checkpoints and the master record) and the analysis phase
  4. Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 6, the discussion of checkpointing for the undo/redo algorithm (fuzzy checkpointing), chapter level only

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
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