Algorithm Search⌘K

Algorithmresearch

Instant restart

Also called instant recovery, on-demand restart.

Admit new transactions right after log analysis and redo or undo each page or transaction on demand when it is first touched.

Time
O(n + u + m) worst
Space
O(n) extra
Where
m = the number of losers; n = the records in the stable log after the last checkpoint; u = the updates of the losers that are not yet compensated
Properties
deterministic
Origin
Goetz Graefe, Wey Guy, Caetano Sauer, Theo Härder, 2015

Instant restart, also called on-demand restart, recovers a database after a system crash with the same log and the same log records as ARIES, but in a different order of work. Restart runs only log analysis, then reacquires the locks of the transactions that were active at the crash, and then opens the system to new transactions. A page is redone when a transaction first needs it, and an unfinished transaction is rolled back when a new transaction needs one of its locks. A background task does the rest. Graefe, Guy and Sauer describe it as one part of instant recovery, together with single-page repair and instant restore after a media failure.

In plain words

A shop closes suddenly. Next morning, the full method is to check every shelf against the order book, and to cancel every half-done order, before the doors open. With a large shop, customers wait for hours.

The quick method first reads the order book once. It writes down which shelves need fixing and puts a "reserved" tag on each item of a half-done order. Then the doors open.

When a customer goes to a shelf that is on the list, a clerk fixes that shelf first, and the customer waits only for that shelf. When a customer wants a reserved item, the clerk first cancels the half-done order and puts its items back. In quiet moments, clerks fix the other shelves and cancel the other orders.

The customer sees the same shop as with the full method. The work is the same. Only the wait at the door is short.

The problem

The model is the one of the crash recovery problem and of ARIES: pages with a pageLSN, a buffer with the steal and no-force policies and the write-ahead rule, a forced commit record, and strict two-phase locking of records. A crash loses the buffer, the lock table and the tail of the log.

After a crash, restart must give every later transaction the same view as a full restart would: the effect of the committed transactions, and none of the effect of the losers. It must stay correct when it crashes during its own run. The goal is to make the time until the first new transaction runs short, and independent of the redo and undo work.

The algorithm

Analysis is the analysis pass of ARIES. It also builds, for each page, the list of the LSNs of its log records, the per-page chain. A real system links these records backward in the log itself, each record with the LSN of the previous record on the same page, as single-page repair does; the code keeps a list in memory.

  1. RESTART()
  2. 1for each record r of the stable log, from the last checkpoint, in LSN order: find the winners, the losers and undoNext[T] for each loser T
  3. 2if r is an update or a CLR then append r.lsn to chain[r.page]; add r.page to needRedo
  4. 3for each loser T, for each update u on the chain of T from undoNext[T]: give T the lock on u.key
  5. 4write ⟨end, T⟩ for each winner; admit new transactions ▷ no redo and no undo has run yet
  6. FIX(P) ▷ every access to page P goes through FIX
  7. 5if P is in needRedo then
  8. 6for each lsn in chain[P], in LSN order do
  9. 7if pageLSN(P) < lsn then apply the record lsn to P; pageLSN(P) ← lsn
  10. 8remove P from needRedo
  11. LOCK(T, x)
  12. 9if a loser L holds the lock on x then ROLLBACK(L)
  13. 10take the lock on x for T, or wait if a live transaction holds it
  14. UNDO-STEP(L)
  15. 11if undoNext[L] ≠ 0 then r ← the record undoNext[L]; undoNext[L] ← r.undoNextLSN if r is a CLR, else r.prevLSN
  16. 12if r is an update then FIX(r.page); append ⟨CLR, L, r.key, value = r.before, undoNextLSN = r.prevLSN⟩ and apply it
  17. 13else append ⟨end, L⟩; release the locks of L; L is no longer a loser
  18. BACKGROUND-STEP()
  19. 14if needRedo is not empty then FIX(a page of needRedo)
  20. 15else if a loser is left then UNDO-STEP(the loser with the largest undoNext)
  21. ROLLBACK(L)
  22. 16repeat UNDO-STEP(L) until L has ended

Analysis (lines L1 to L4). One pass over the log after the last checkpoint finds the losers and the pages that may need redo. Line L3 restores the locks that the losers held at the crash, from their log records. With record locks held to the end of a transaction, a loser held a lock on every record that it changed and did not yet undo. After line L4 the system runs new transactions.

Redo on demand (lines L5 to L8). The first fix of a page after the restart applies the records of its chain with the pageLSN test of ARIES. This is single-page redo: it reads one page and the log records of that page, and no other page.

Undo on demand (lines L9 to L13 and L16). A new transaction that asks for a lock of a loser rolls the loser back first, with the CLRs of ARIES. A loser that holds no lock that anyone wants waits for the background.

Background (lines L14 and L15). Between the actions of new transactions, the system redoes the remaining pages and rolls back the remaining losers. When nothing is left, recovery is complete. A checkpoint can then be taken as usual.

The code that goes with this page is a toy: six records on three pages, physical log records, no checkpoints, no concurrency, and a lock conflict between two live transactions simply fails. It shows the order of the work and the crash cases, not the engineering of a real system.

Example

Pages: P1 holds a = 10 and b = 20, P2 holds c = 30 and d = 40, P3 holds e = 50 and f = 60. T1 writes a, T2 writes c and e, and T1 commits, which forces the log up to LSN 6. The buffer then writes P2 to disk (a steal: c = 31 with pageLSN 4). Then the system crashes.

LSN record
1 begin T1
2 update T1, P1, a: 10 to 11
3 begin T2
4 update T2, P2, c: 30 to 31
5 update T2, P3, e: 50 to 51
6 commit T1

Analysis finds the winner T1 and the loser T2 with undoNext 5. The chains are P1: [2], P2: [4], P3: [5], so all three pages are in needRedo. Line L3 gives T2 the locks on c and e. Line L4 writes end 7 for T1, and the system opens. No data page has been read yet.

  • T3 begins (8) and reads a. FIX(P1) applies LSN 2, so a = 11, the committed value. T3 writes b = 21 (9), commits (10) and ends (11). Only P1 has been redone, and T2 is still a loser.
  • T4 begins (12) and wants to write c. T2 holds the lock, so line L9 rolls T2 back. UNDO-STEP finds LSN 5 and fixes P3, which applies LSN 5 (e = 51), then writes CLR 13 with e = 50 and undoNextLSN 4. The next step fixes P2. Its pageLSN is 4, so redo skips LSN 4, and CLR 14 writes c = 30 with undoNextLSN 3. The next step reaches the begin record, and end 15 releases the locks of T2.
  • T4 now gets the lock on c and writes c = 32 (16).

The background has nothing left to do. The final values are a = 11, b = 21, c = 32, d = 40, e = 50 and f = 60: the same as after a full ARIES restart followed by T3 and T4.

Correctness

Theorem. Assume the write-ahead rule, a forced commit record, record locks held to the end of each transaction, and that every access to a page goes through FIX and every access to a record through LOCK. Then after any number of crashes, also crashes during the instant phase or the background phase, every read of a new transaction returns the committed value of the record. When the background is done, the database holds exactly the effect of the committed transactions.

The proof has three parts. FIX gives a page that holds the whole history of the stable log on that page, by the pageLSN argument of ARIES applied to one page: before its first fix, nothing has written the page since the restart. The locks of line L3 keep new transactions away from every record that a loser still has to undo, and line L9 releases such a lock only after the loser has ended. Undo of a loser writes before images on records that no one else has changed since, so it restores the values before the loser. The full proof gives the lemmas for the model of the code.

Proof: New transactions after an instant restart read only committed valuesfull

Model. This is the model of the implementation. Records are items xx on pages, each page with a pageLSN. A transaction writes an item with a physical update record that holds the before and the after value, and it holds a lock on each item that it reads or writes until its end record. The buffer obeys the write-ahead rule, a commit record is forced, and the policies are steal and no-force. Rollback of a transaction uses CLRs as in ARIES: the CLR for an update uu writes u.beforeu.\mathrm{before} and has undoNextLSN equal to u.prevLSNu.\mathrm{prevLSN}. A crash keeps the disk and the stable log, which is a prefix of the log, and loses the rest. There are no checkpoints.

Restart runs lines L1 to L4: analysis builds, for each page PP, the list chain[P]\mathrm{chain}[P] of the LSNs of all update and CLR records on PP in the stable log, in LSN order, and the set needRedo of these pages; it finds the losers with the head undoNext of each chain; and it gives each loser the lock on every item that its chain still has to undo. Then new transactions run. Every access to a page goes through FIX (lines L5 to L8), and every access to an item takes its lock through LOCK (lines L9 and L10).

The committed value of an item xx is the after value of the last update on xx by a committed transaction, or the initial value if there is none. A transaction is committed when its commit record is in the stable log. Under strict locking this is the value that xx has after a full ARIES restart.

Lemma 1 (redo on demand). After FIX(P)(P) returns, the buffered page PP holds the effect of all update and CLR records on PP in the stable log, in LSN order, and, after that, the effect of the records on PP written since the restart.

Proof. Before the first FIX(P)(P) after the restart, no record on PP has been written since the restart, because every write of a page (by a new transaction in WRITE, or by UNDO-STEP in line L12) calls FIX first. The disk version of PP with pageLSN pp holds the effect of the records on PP with LSN at most pp, by the write-ahead rule and the pageLSN rule of normal work. Lines L6 and L7 apply the records of chain[P]\mathrm{chain}[P] with LSN above pp in LSN order, and chain[P]\mathrm{chain}[P] holds all records on PP of the stable log. Line L8 removes PP from needRedo, so later calls do not redo it again, and later records are applied by the action that writes them. □\square

Lemma 2 (loser locks). From the end of line L3 until a loser LL ends, every item xx that an update on the chain of LL changed is locked by LL. No other transaction writes or reads xx before LL ends.

Proof. Line L3 locks every such item. Under strict locking in normal work, two transactions never hold uncommitted updates on the same item, so line L3 never gives one item to two losers. LOCK, line L9, gives a lock held by a loser to another transaction only after ROLLBACK(L)(L) has run, that is, after the end record of LL. Locks are released only in line L13 and at commit. □\square

Lemma 3 (undo). When a loser LL ends, every update of LL in the log is compensated by a CLR, and each item that LL changed holds the value it had before the first update of LL on it.

Proof. The chain from undoNext[L][L] through prevLSN for updates and undoNextLSN for CLRs visits exactly the updates of LL that are not yet compensated, newest first, as in ARIES. Line L11 and line L12 walk this chain and write one CLR per update. Line L12 calls FIX first, so by Lemma 1 the CLR is applied to a page that holds the whole history. By Lemma 2 no other transaction changed the item between the update and its CLR, so writing the before image undoes exactly this update. Applied newest first, the CLRs leave each item at the before value of the oldest update of LL on it. □\square

Theorem. In the model, after a crash at any point, and after any number of later crashes, also during the instant phase or the background phase, (a) every read by a new transaction returns the committed value of the item, as it would after a full ARIES restart, and (b) when the background steps are done, every item holds the initial value plus the effect of the committed transactions, old and new.

Proof. (a) A new transaction TT reads xx only after LOCK(T,x)(T, x) succeeds. If a loser held the lock, line L9 has rolled it back, and by Lemma 3 xx holds the value before the loser's updates. If no loser held the lock, then by Lemma 2 no loser changed xx, or its changes on xx are already compensated. Then FIX gives the page with the whole history by Lemma 1, and the last change of xx in it is by a committed transaction, by a compensated loser, or by a new transaction that committed before TT took the lock. This is the committed value.

(b) Line L14 fixes every page that is left in needRedo, and line L15 runs UNDO-STEP for every loser that is left until it ends. Each step makes progress, so the background phase ends with needRedo empty and no loser. By Lemma 1 and Lemma 3, the state is then the history of the stable log with every loser undone, plus the committed new transactions.

For a later crash, the new stable log is a prefix of the log, with the CLRs and end records written so far. The next analysis finds the CLRs, and the head of each loser skips the updates they compensate. The new transactions that did not commit are new losers of the same kind. So the same argument applies to the new stable log. □\square

The tests check the theorem by a crash after every prefix of a random workload, by crashes during the instant phase and during background recovery, and by a hand example with the log records of the page.

Complexity

The cost is counted in log records read and pages read and written, for one restart. The log is read from the last fuzzy checkpoint, so a checkpoint bounds nn.

  • Until the system opens. Analysis reads the nn log records once, and line L3 walks the chains of the losers, at most nn records. No data page is read or written. This is the time that ARIES spends in analysis alone; ARIES then reads every dirty page and the log again for redo before undo.
  • First access to a page. One page read and the records of its chain. A chain that is linked through the log costs one log read per record; with the log records of a page close together in a log archive or a cache, this is a few reads.
  • Total work. Over the whole restart, each page in needRedo is read once and each record of the log is applied at most once, O(n)O(n), as in ARIES. Undo writes one CLR per update of a loser and one end per loser, O(u+m)O(u + m). The total is the same as for ARIES; only the order is different.
  • Log volume per update. Normal processing is unchanged: one update record per change, with a before and an after image. The per-page backward link adds one LSN to each record.
  • Space. The table of pages that need redo, the loser table and the lock table. The code also keeps the chains in memory, O(n)O(n); a real system keeps them in the log.

Heuristic. The time to the first transaction is about the time of analysis, which a checkpoint keeps short. The response time of the first transactions is longer than normal, since each one may pay for the redo of its pages and the rollback of losers in its way. This page gives no measurement.

Properties

  • Same log, same records. Normal processing and the log format are those of ARIES, plus the per-page link.
  • Incremental and restartable. Each page and each loser is recovered on its own. A crash during recovery leaves CLRs and pages that the next analysis uses, so work is not lost.
  • No change in the view. A new transaction cannot see a page before its redo, or a record of a loser before its undo.
  • Locks reacquired from the log. The locks of the losers come from their log records alone.

Variants and improvements

  • Order of the background work. Redo of the pages that the workload uses often, or rollback of the losers that hold hot locks, first.
  • Redo first, undo later. ARIES already allows new transactions after the redo pass, while undo runs, when the locks of the losers are reacquired first. The time to open is then that of analysis and redo, which grows with the size of the buffer at the crash.
  • Instant restore. After a media failure, the same idea restores segments of the lost device on demand from the backup and the log archive, as described in the media recovery problem.
  • Single-page repair. The per-page chain also repairs one damaged page during normal processing, from an older copy of the page and its log records, without a restart.

When to use it

Use it when the time until the system accepts work after a crash matters more than the speed of the first transactions, and when the database and the buffer are large, so that a full redo pass takes long. It needs a per-page chain or another fast way to find the records of one page, and locks that can be rebuilt from the log. With a small buffer and a short log after the checkpoint, a plain ARIES restart is simpler and almost as fast.

Pitfalls

  • A page access that bypasses FIX. A scan or a prefetch that reads a page from disk without the redo check returns an old version. Every path into the buffer must check needRedo.
  • Opening before the loser locks are set. If a new transaction can read a record before line L3 locks it, it sees an uncommitted value of a loser.
  • Undo with a page that is not redone. A CLR applied to a page that still needs redo gives the page a high pageLSN, so the later redo skips the older records of the page, and the page never gets them. Line L12 fixes the page first.
  • Locks coarser than records. With page locks the losers lock whole pages, and many new transactions wait for undo. With predicate or key-range locks, the locks to rebuild must also come from the log.
  • Forgetting needRedo at a second crash. The state of the instant phase is not in the log. The next analysis rebuilds it from the log, and pages that were redone and written back pass the pageLSN test at no cost.

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.

instant_restart.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instant-restart/. The authors are listed in prov/81XW5M.jsonl.

"""A toy version of instant restart (Graefe, Guy and Sauer) on a simulated disk.

Normal processing is write-ahead logging with record locks held to the end of
the transaction, steal and no-force, and physical update records. Restart
runs log analysis only and then opens the system. A page that still needs
redo is redone when it is first fixed in the buffer, from the list of its log
records that analysis built (the per-page chain). A loser is rolled back when
a new transaction asks for one of its locks. A background step does the rest
of the work, one page or one undo at a time.

There are no checkpoints, so analysis reads the whole log. A crash keeps the
disk (page -> (values, page_lsn)) and the stable log and loses the rest.
"""

from dataclasses import dataclass

PAGE_OF = {"a": "P1", "b": "P1", "c": "P2", "d": "P2", "e": "P3", "f": "P3"}
INIT = {"a": 10, "b": 20, "c": 30, "d": 40, "e": 50, "f": 60}


@dataclass(frozen=True)
class Rec:
    lsn: int
    kind: str  # begin, update, clr, commit, abort, end
    txn: int
    prev: int = 0
    page: str = ""
    key: str = ""
    before: int = 0
    after: int = 0
    undo_next: int = 0  # clr only


def fresh_disk() -> dict:
    disk: dict = {}
    for k, p in sorted(PAGE_OF.items()):
        disk.setdefault(p, ({}, 0))[0][k] = INIT[k]
    return disk


class Db:
    def __init__(self, disk: dict, log: list | None = None):
        self.disk = disk
        self.log: list[Rec] = list(log or [])
        self.tail: list[Rec] = []
        self.buf: dict[str, list] = {}
        self.last: dict[int, int] = {}  # txn -> lastLSN
        self.undo_next: dict[int, int] = {}  # txns that roll back -> next record to undo
        self.locks: dict[str, int] = {}  # record lock: key -> txn
        self.chain: dict[str, list[int]] = {}  # page -> LSNs of its records (restart only)
        self.need_redo: set[str] = set()
        self.losers: set[int] = set()
        self.redone: list[str] = []  # pages redone since the restart, in order

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

    def _append(self, **kw) -> Rec:
        r = Rec(lsn=len(self.log) + len(self.tail) + 1, **kw)
        self.tail.append(r)
        if r.kind != "end":
            self.last[r.txn] = r.lsn
        return r

    def flush_log(self) -> None:
        self.log.extend(self.tail)
        self.tail = []

    def flush_page(self, p: str) -> None:
        if p in self.buf:
            if self.buf[p][1] > len(self.log):  # WAL rule
                self.flush_log()
            self.disk[p] = (dict(self.buf[p][0]), self.buf[p][1])

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

    def fix(self, p: str) -> list:
        """Bring page p into the buffer, and redo it first if it needs redo."""
        if p not in self.buf:
            vals, lsn = self.disk[p]
            self.buf[p] = [dict(vals), lsn]
        if p in self.need_redo:  # @line L5
            pg = self.buf[p]
            for lsn in self.chain[p]:  # @line L6
                r = self.rec(lsn)
                if pg[1] < r.lsn:  # @line L7
                    pg[0][r.key], pg[1] = r.after, r.lsn  # @line L7
            self.need_redo.discard(p)  # @line L8
            self.redone.append(p)
        return self.buf[p]

    # ------------------------------------------------------------ transactions
    def begin(self, txn: int) -> None:
        self._append(kind="begin", txn=txn)

    def lock(self, txn: int, key: str) -> bool:
        """Take the lock on key for txn. A loser's lock is freed by rolling the
        loser back at once; a lock of another live transaction is a conflict."""
        holder = self.locks.get(key, txn)
        if holder in self.losers:  # @line L9
            self.rollback(holder)  # @line L9
            holder = txn
        if holder != txn:
            return False
        self.locks[key] = txn  # @line L10
        return True

    def read(self, txn: int, key: str) -> int | None:
        if not self.lock(txn, key):
            return None
        return self.fix(PAGE_OF[key])[0][key]

    def write(self, txn: int, key: str, value: int) -> bool:
        if not self.lock(txn, key):
            return False
        pg = self.fix(PAGE_OF[key])
        r = self._append(kind="update", txn=txn, prev=self.last[txn], page=PAGE_OF[key],
                         key=key, before=pg[0][key], after=value)
        pg[0][key], pg[1] = value, r.lsn
        return True

    def _release(self, txn: int) -> None:
        for k in [k for k, t in self.locks.items() if t == txn]:
            del self.locks[k]

    def commit(self, txn: int) -> None:
        self._append(kind="commit", txn=txn, prev=self.last[txn])
        self.flush_log()
        self._append(kind="end", txn=txn, prev=self.last[txn])
        self._release(txn)
        del self.last[txn]

    def abort(self, txn: int) -> None:
        r = self._append(kind="abort", txn=txn, prev=self.last[txn])
        self.undo_next[txn] = r.prev

    def undo_step(self, txn: int) -> None:
        """Undo one update of txn with a CLR, or end its rollback."""
        nxt = self.undo_next[txn]
        if nxt:
            r = self.rec(nxt)  # @line L11
            if r.kind == "clr":
                self.undo_next[txn] = r.undo_next  # @line L11
                return
            if r.kind == "update":
                pg = self.fix(r.page)  # @line L12
                c = self._append(kind="clr", txn=txn, prev=self.last[txn], page=r.page, key=r.key,
                                 before=pg[0][r.key], after=r.before, undo_next=r.prev)  # @line L12
                pg[0][r.key], pg[1] = r.before, c.lsn  # @line L12
            self.undo_next[txn] = r.prev  # @line L11
            return
        self._append(kind="end", txn=txn, prev=self.last[txn])  # @line L13
        del self.undo_next[txn]
        del self.last[txn]
        self.losers.discard(txn)
        self._release(txn)  # @line L13

    def rollback(self, txn: int) -> None:
        while txn in self.undo_next:  # @line L16
            self.undo_step(txn)  # @line L16

    # ------------------------------------------------------------ restart
    def restart(self) -> None:
        """Log analysis. After it the system accepts new transactions."""
        won: set[int] = set()
        for r in self.log:  # @line L1
            if r.kind == "commit":
                won.add(r.txn)
                self.last[r.txn] = r.lsn
            elif r.kind == "end":
                won.discard(r.txn)
                self.last.pop(r.txn, None)
                self.undo_next.pop(r.txn, None)
            else:
                self.last[r.txn] = r.lsn  # @line L1
                self.undo_next[r.txn] = r.undo_next if r.kind == "clr" else r.lsn  # @line L1
            if r.kind in ("update", "clr"):
                self.chain.setdefault(r.page, []).append(r.lsn)  # @line L2
                self.need_redo.add(r.page)  # @line L2
        for t in sorted(won):
            self._append(kind="end", txn=t, prev=self.last.pop(t))  # @line L4
            del self.undo_next[t]
        self.losers = set(self.undo_next)
        for t in sorted(self.losers):  # @line L3
            nxt = self.undo_next[t]
            while nxt:  # walk the chain of t; lock each record it changed
                r = self.rec(nxt)
                if r.kind == "update":
                    self.locks[r.key] = t  # @line L3
                nxt = r.undo_next if r.kind == "clr" else r.prev
        # from here on new transactions run

    def background_step(self) -> bool:
        """One unit of the remaining restart work. Returns False when none is left."""
        if self.need_redo:
            self.fix(min(self.need_redo))  # @line L14
            return True
        if self.losers:
            t = max(self.losers, key=lambda t: self.undo_next[t])  # @line L15
            self.undo_step(t)  # @line L15
            return True
        return False

    def value(self, key: str) -> int:
        return self.fix(PAGE_OF[key])[0][key]
test_instant_restart.py 192 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instant-restart/. The authors are listed in prov/81XW5M.jsonl.

"""Crash injection for the toy instant restart.

A random workload runs on the database and is cut by a crash after every
prefix. After the restart, new transactions run at once, mixed with
background steps, and every value they read must be the committed value.
"""

import random

from instant_restart import INIT, PAGE_OF, Db, fresh_disk

KEYS = sorted(PAGE_OF)
PAGES = sorted(set(PAGE_OF.values()))


def workload(db: Db, rng: random.Random, steps: int, first_txn: int = 1) -> dict:
    """Run steps random actions. Return the committed state."""
    committed = dict(INIT)
    active: dict[int, dict] = {}  # txn -> its writes
    rolling: list[int] = []
    nxt = first_txn
    for _ in range(steps):
        r = rng.random()
        if r < 0.15 and len(active) < 3:
            db.begin(nxt)
            active[nxt] = {}
            nxt += 1
        elif r < 0.5 and active:
            t = rng.choice(sorted(active))
            k = rng.choice(KEYS)
            v = rng.randint(100, 999)
            if db.write(t, k, v):
                active[t][k] = v
        elif r < 0.6 and active:
            t = rng.choice(sorted(active))
            db.commit(t)
            committed.update(active.pop(t))
        elif r < 0.68 and active:
            t = rng.choice(sorted(active))
            db.abort(t)
            del active[t]
            rolling.append(t)
        elif r < 0.8 and rolling:
            t = rolling[0]
            db.undo_step(t)
            if t not in db.undo_next:
                rolling.pop(0)
        else:
            db.flush_page(rng.choice(PAGES))
    return committed


def instant_phase(db: Db, rng: random.Random, committed: dict, txns: int, first_txn: int,
                  crash_after: int | None = None) -> Db:
    """Run new transactions one after another, with background steps between
    their actions. Check each read. Crash after crash_after actions if given."""
    actions = 0
    for t in range(first_txn, first_txn + txns):
        db.begin(t)
        writes = {}
        for k in rng.sample(KEYS, 2):
            assert db.read(t, k) == committed[k]
            v = rng.randint(1000, 9999)
            assert db.write(t, k, v)
            writes[k] = v
            if rng.random() < 0.5:
                db.background_step()
            if rng.random() < 0.3:
                db.flush_page(rng.choice(PAGES))
            actions += 1
            if crash_after is not None and actions == crash_after:
                return db.crash()
        db.commit(t)
        committed.update(writes)
    return db


def drain_and_check(db: Db, committed: dict) -> None:
    while db.background_step():
        pass
    assert not db.need_redo and not db.losers and not db.undo_next
    assert {k: db.value(k) for k in KEYS} == committed
    assert not db.locks


def test_crash_at_every_prefix() -> None:
    for seed in range(4):
        steps = 60
        for k in range(steps + 1):
            db = Db(fresh_disk())
            committed = workload(db, random.Random(seed), k)
            db = db.crash()
            db.restart()
            rng = random.Random(1000 + 7 * seed + k)
            db = instant_phase(db, rng, committed, txns=4, first_txn=500)
            drain_and_check(db, committed)


def test_crash_during_the_instant_phase() -> None:
    for seed in range(4):
        db = Db(fresh_disk())
        committed = workload(db, random.Random(seed), 50)
        db = db.crash()
        db.restart()
        for cut in range(1, 7):
            probe = Db(dict(db.disk), list(db.log))
            probe.restart()
            rng = random.Random(seed * 31 + cut)
            state = dict(committed)
            crashed = instant_phase(probe, rng, state, txns=4, first_txn=500, crash_after=cut)
            # the new transaction that was cut did not commit; the earlier ones did
            again = Db(dict(crashed.disk), list(crashed.log))
            crashed.restart()
            again.restart()
            drain_and_check(crashed, state)
            # a second restart from the same stable state gives the same values
            drain_and_check(again, state)


def test_crash_during_background_recovery() -> None:
    for seed in range(4):
        db = Db(fresh_disk())
        committed = workload(db, random.Random(seed), 60)
        db = db.crash()
        db.restart()
        rng = random.Random(seed)
        for _ in range(20):
            if not db.background_step():
                break
            if rng.random() < 0.5:
                db.flush_page(rng.choice(PAGES))
            if rng.random() < 0.3:
                db.flush_log()
                db = db.crash()
                db.restart()
        drain_and_check(db, committed)


def test_hand_example() -> None:
    db = Db(fresh_disk())
    db.begin(1)
    db.write(1, "a", 11)
    db.begin(2)
    db.write(2, "c", 31)
    db.write(2, "e", 51)
    db.commit(1)  # forces records 1 to 6
    db.flush_page("P2")  # steal: c = 31 with pageLSN 4 is on disk
    db = db.crash()
    assert len(db.log) == 6
    db.restart()
    assert db.losers == {2} and db.need_redo == {"P1", "P2", "P3"}
    assert db.chain == {"P1": [2], "P2": [4], "P3": [5]}
    assert db.locks == {"c": 2, "e": 2}
    # T3 touches only P1, and only P1 is redone
    db.begin(3)
    assert db.read(3, "a") == 11
    db.write(3, "b", 21)
    db.commit(3)
    assert db.redone == ["P1"] and db.losers == {2}
    # T4 wants c, which the loser T2 holds: T2 is rolled back first
    db.begin(4)
    assert db.write(4, "c", 32)
    assert db.redone == ["P1", "P3", "P2"]
    kinds = [(r.kind, r.txn, r.key, r.after, r.undo_next) for r in map(db.rec, range(7, 17))]
    assert kinds == [("end", 1, "", 0, 0), ("begin", 3, "", 0, 0), ("update", 3, "b", 21, 0),
                     ("commit", 3, "", 0, 0), ("end", 3, "", 0, 0), ("begin", 4, "", 0, 0),
                     ("clr", 2, "e", 50, 4), ("clr", 2, "c", 30, 3), ("end", 2, "", 0, 0),
                     ("update", 4, "c", 32, 0)]
    db.commit(4)
    assert not db.background_step()
    assert {k: db.value(k) for k in KEYS} == {"a": 11, "b": 21, "c": 32, "d": 40, "e": 50, "f": 60}


def test_first_transaction_redoes_only_its_pages() -> None:
    for seed in range(5):
        db = Db(fresh_disk())
        committed = workload(db, random.Random(seed), 80)
        db = db.crash()
        db.restart()
        pending = set(db.need_redo)
        loser_keys = set(db.locks)
        free = [k for k in KEYS if k not in loser_keys]
        if not free:
            continue
        k = free[0]
        db.begin(900)
        assert db.read(900, k) == committed[k]
        assert set(db.redone) <= {PAGE_OF[k]} and set(db.redone) <= pending
        assert db.need_redo == pending - set(db.redone)

History

ARIES (Mohan et al., 1992) recovers in three passes over the log, analysis, redo and undo, and already lets new transactions run during the undo pass. Graefe, Guy and Sauer built instant recovery on the per-page log chains of single-page repair, in their book on instant recovery with write-ahead logging, with a second edition in 2016. Härder, Sauer, Graefe and Guy summarized single-page repair, instant restart and instant restore in Datenbank-Spektrum in 2015.

References

  1. Goetz Graefe, Wey Guy and Caetano Sauer, Instant Recovery with Write-Ahead Logging, second edition, Morgan and Claypool, 2016, the chapters Single-Page Recovery, Instant Restart after a System Failure, and Applications of Instant Restart, chapter level only
  2. Theo Härder, Caetano Sauer, Goetz Graefe and Wey Guy, Instant recovery with write-ahead logging, Datenbank-Spektrum 15(3), 2015, pages 235 to 239, the overview of single-page repair, instant restart and instant restore, paper level
  3. 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, the analysis, redo and undo passes of restart, and new transaction processing during undo, paper level

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