Algorithm Search⌘K

Algorithmcore

Undo/redo logging

Also called undo-redo logging, undo logging and redo logging.

Log before and after images of each update so that recovery redoes committed work and undoes uncommitted work under any buffer policy.

Time
O(n) worst
Space
O(m + k) extra
Where
k = the items that recovery changes; m = the transactions in the candidate set; n = the log records from the oldest start record of a transaction in the checkpoint list to the end
Properties
deterministic
Origin
Jim Gray, 1978

Undo/redo logging is the recovery algorithm that writes, for each update, a log record with both the old value and the new value of the item, so that after a crash it can undo the changes of transactions that did not commit and redo the changes of transactions that did. It sits between two simpler schemes: undo logging keeps only old values, so every changed item must reach the disk before the commit record does (the force policy), and redo logging keeps only new values, so no changed item may reach the disk before the commit record does (the no-steal policy). Undo/redo logging needs only the write-ahead rule, that the update record reaches the disk before the item does, so the buffer manager is free to use steal and no-force. ARIES is a refined form of the same algorithm, with a log sequence number on each page and compensation log records; this page gives the plain form, as taught with the record notation of Garcia-Molina, Ullman and Widom.

In plain words

Each time a transaction changes an item, the system first notes in a journal the item, the old value and the new value. Memory can hold the change for as long as it likes. The one rule is that a changed item goes to disk only after its note is on disk. When a transaction commits, the system writes a "done" note and waits until it is on disk.

After a crash, the disk can hold changes of unfinished transactions, and it can lack changes of finished ones. Recovery reads the journal backwards and puts back the old value of every change by an unfinished transaction. Then it reads the journal forwards and puts in the new value of every change by a finished one. Now and then the system writes all changed items to disk and marks this in the journal, so recovery can skip the older part.

The problem

The model is the one of the crash recovery problem. Each item XX is a page with one value. The schedule is strict: a transaction that wrote XX holds its write lock until it ends. The buffer manager may write a dirty item to disk at any time, and commit does not write items. A crash keeps the disk and the stable part of the log and loses the buffer and the log tail.

The log holds these records, in the forms of Garcia-Molina, Ullman and Widom:

  • ⟨\langleSTART T⟩T\rangle: transaction TT begins;
  • ⟨T,X,v,w⟩\langle T, X, v, w\rangle: TT changed item XX from old value vv to new value ww (undo logging writes only ⟨T,X,v⟩\langle T, X, v\rangle, redo logging only ⟨T,X,w⟩\langle T, X, w\rangle);
  • ⟨\langleCOMMIT T⟩T\rangle and ⟨\langleABORT T⟩T\rangle;
  • ⟨\langleSTART CKPT (T1,…,Tk)⟩(T_1, \dots, T_k)\rangle, where T1,…,TkT_1, \dots, T_k are the active transactions, and ⟨\langleEND CKPT⟩\rangle, for a nonquiescent checkpoint that does not stop transactions.

Each record has an LSN, its position in the log, starting at 1; real systems often use the byte offset of the record instead. Each item on disk carries the LSN of the last record applied to it, its pageLSN, which the write-ahead rule uses. After recovery, every item must hold the value written by the last committed transaction that wrote it, or its initial value.

The records map to the fields of ARIES as follows.

record here ARIES record difference
⟨\langleSTART T⟩T\rangle BEGIN ARIES needs none: a prevLSN of 0 marks the first record of TT
⟨T,X,v,w⟩\langle T, X, v, w\rangle UPDATE ARIES adds the record's LSN, the prevLSN of TT and a location in the page; vv and ww are the before and after images
⟨\langleCOMMIT T⟩T\rangle, ⟨\langleABORT T⟩T\rangle COMMIT, ABORT ARIES logs each undo step as a CLR and closes TT with END
⟨\langleSTART CKPT (T1,…,Tk)⟩(T_1, \dots, T_k)\rangle BEGIN_CHECKPOINT the list is the set of keys of the ARIES transaction table
⟨\langleEND CKPT⟩\rangle END_CHECKPOINT ARIES writes no pages and stores the transaction table and the dirty page table instead

The algorithm

Normal processing keeps, for each active transaction, the list of its update records, which it needs for an abort. In this version an abort puts back the old values in the buffer and writes no undo records, so recovery treats an aborted transaction like an unfinished one.

  1. WRITE(T, X, w)
  2. 1v ← the current value of X (the buffer copy if X is dirty, else the disk copy)
  3. 2append ⟨T, X, v, w⟩ to the log tail; X ← w in the buffer; pageLSN(X) ← the LSN of the record
  4. OUTPUT(X) ▷ the buffer manager calls it at any time
  5. 3flush the log up to pageLSN(X) ▷ the write-ahead rule (UR1)
  6. 4write X with its pageLSN to disk; X is clean
  7. COMMIT(T)
  8. 5append ⟨COMMIT T⟩; flush the log up to it; report the commit
  9. ABORT(T)
  10. 6for each update ⟨T, X, v, w⟩ of T, newest first, do X ← v in the buffer
  11. 7append ⟨ABORT T⟩ ▷ not forced
  12. CHECKPOINT() ▷ other steps may run between L8, L9 and L10
  13. 8append ⟨START CKPT (T_1, ..., T_k)⟩ for the active T_i; flush the log
  14. 9OUTPUT every dirty item
  15. 10append ⟨END CKPT⟩; flush the log
  16. RECOVER()
  17. 11s, L ← the LSN and the list of the START CKPT that matches the last END CKPT (s ← 0, L ← ∅ if none)
  18. 12U ← L ∪ {T : ⟨START T⟩ is after s}; C ← ∅; open ← L
  19. 13for each record r of the stable log, from the end backwards do ▷ undo pass
  20. 14if r.lsn < s and open = ∅ then stop
  21. 15if r = ⟨COMMIT T⟩ then add T to C
  22. 16else if r = ⟨START T⟩ then remove T from open
  23. 17else if r = ⟨T, X, v, w⟩ with T ∈ U and T ∉ C then X ← v; pageLSN(X) ← r.lsn
  24. 18for each record r after s, forwards do ▷ redo pass
  25. 19if r = ⟨T, X, v, w⟩ with T ∈ C then X ← w; pageLSN(X) ← r.lsn
  26. 20OUTPUT every item that lines L17 and L19 changed
  27. 21append ⟨ABORT T⟩ for each T ∈ U ∖ C; flush the log

Normal processing (lines L1 to L10). Line L3 is the only ordering rule on the data: the record of a change is on disk before the change is. The commit record is forced so that a reported commit survives a crash; the algorithm stays consistent without the force, but then it can lose a reported commit. The checkpoint writes every item that is dirty at line L9, so every change made before the START CKPT record is on disk once the END CKPT record is.

Undo pass (lines L11 to L17). The candidates UU are the transactions that were active at the last complete checkpoint and those that started after it. Transactions that ended before the checkpoint need nothing: the checkpoint wrote their final values. The pass goes backwards from the end of the log, so it meets the commit record of a transaction before its updates, and it undoes every update of a candidate without a commit record, newest first. It reads past the checkpoint start until it has seen the start record of each transaction in the list, because those transactions can have updates before the checkpoint. An END CKPT without its START CKPT does not count: line L11 uses the last complete checkpoint.

Redo pass (lines L18 and L19). The pass goes forwards from the checkpoint start and redoes each update of a committed transaction, oldest first. Updates before the checkpoint are on disk already.

End (lines L20 and L21). Recovery writes the items it changed and then records the abort of each unfinished candidate. Recovery appends nothing before line L21, so a crash during recovery leaves the same stable log, and the next run computes the same values.

Example

Items A=10A = 10, B=20B = 20, C=30C = 30 on disk, all with pageLSN 0. The run before the crash:

LSN record note
1 ⟨\langleSTART T1⟩T_1\rangle
2 ⟨T1,A,10,11⟩\langle T_1, A, 10, 11\rangle
3 ⟨\langleSTART T2⟩T_2\rangle
4 ⟨T2,B,20,21⟩\langle T_2, B, 20, 21\rangle
5 ⟨\langleCOMMIT T1⟩T_1\rangle log flushed to 5
6 ⟨\langleSTART CKPT (T2)⟩(T_2)\rangle log flushed to 6
7 ⟨T2,C,30,31⟩\langle T_2, C, 30, 31\rangle
8 ⟨\langleSTART T3⟩T_3\rangle
9 ⟨T3,A,11,12⟩\langle T_3, A, 11, 12\rangle then line L9 flushes the log to 9 and writes A=12A = 12, B=21B = 21, C=31C = 31
10 ⟨\langleEND CKPT⟩\rangle log flushed to 10
11 ⟨\langleCOMMIT T2⟩T_2\rangle log flushed to 11
12 ⟨T3,B,21,22⟩\langle T_3, B, 21, 22\rangle the buffer writes BB: log flushed to 12, B=22B = 22 on disk

Then the system crashes. The disk holds A=12A = 12 and B=22B = 22, both written by T3T_3, which never committed. Recovery finds the checkpoint at s=6s = 6 with list (T2)(T_2), so U={T2,T3}U = \{T_2, T_3\}.

pass records read action
undo 12 T3T_3 has no commit seen: B←21B \leftarrow 21
undo 11, 10 C={T2}C = \{T_2\}
undo 9, 8 T3T_3: A←11A \leftarrow 11
undo 7, 6, 5 T2T_2 committed: skip LSN 7; LSN 5 adds T1T_1 to CC, which does no harm
undo 4, 3 T2T_2 committed: skip; LSN 3 closes T2T_2, so open is empty; the pass stops before LSN 2
redo 7 to 12 LSN 7: C←31C \leftarrow 31
end write AA, BB, CC; append ⟨\langleABORT T3⟩T_3\rangle as LSN 13

Recovery reads 10 records backwards and 6 forwards and writes 3 items. The result is A=11A = 11, B=21B = 21, C=31C = 31, the values of the committed T1T_1 and T2T_2. The undo of AA is needed because the checkpoint itself wrote the uncommitted value 12 to disk. The redo of CC is not needed, since the checkpoint wrote 31, but this version has no test that would skip it. The test file builds this run and checks each number.

Correctness

Theorem. Assume a strict schedule, line L3 on every write of an item, and a stable log that only grows at its end. After a crash at any point, also during RECOVER, any number of times, a RECOVER that runs to the end leaves every item with the value of the newest update on it by a transaction whose commit record is in the stable log, or with its initial value.

The proof fixes an item XX and splits into three cases. If a committed transaction updated XX after the checkpoint start, the redo pass runs last and leaves the newest such value. Otherwise, if an unfinished candidate updated XX, the undo pass leaves the old value of the oldest such update; by strictness that old value is the last committed one, and no committed update can come later, since its writer would have had to wait for the candidate to end before the checkpoint. Otherwise recovery does not touch XX, and the checkpoint wrote its last committed value, which nothing changed later. Recovery computes every value from the stable log alone and appends nothing before its last line, which makes a crashed recovery harmless. The full proof is in the correctness proof below.

The order of the passes matters in this version. Take X=1X = 1. T1T_1 writes 2 and aborts, which puts back 1 in the buffer without a log record. T2T_2 writes 3 and commits. After a crash, undo then redo gives 3. Redo then undo gives 1: the undo of T1T_1, an unfinished candidate, comes last. The test file checks both.

Proof: Undo/redo recovery leaves every item with its last committed valuefull

Model. Each item XX is a page with one value and a pageLSN. The schedule is strict: after a transaction TT writes XX, no other transaction writes XX until TT ends, by its commit (line L5) or by its rollback (lines L6 and L7, one step). The buffer manager may call OUTPUT (lines L3 and L4) on any dirty item at any time, also during recovery. A commit is reported only after its commit record is stable (line L5). Lines L8, L9 and L10 are three separate steps, and other steps can run between them; line L9 is one step. A crash keeps the disk and the stable log RR and loses the buffer, the log tail and the lists of updates. The log only grows at its end, so RR is always a prefix of the log that the run appended.

For an item XX, the target τ(X)\tau(X) is the after image of the newest update on XX in RR by a transaction with a commit record in RR, or the initial value of XX if there is no such update. Write C∗C^* for the set of transactions with a commit record in RR.

Lemma 1 (order). Among the transactions that write XX and commit, the order of their updates on XX in the log is the order of their commits.

Proof. If T1T_1 writes XX before T2T_2 does, strictness puts the end of T1T_1 between the two writes, and T2T_2 commits after its own write. □\square

So τ(X)\tau(X) is the value of XX after the committed transactions run one after the other in commit order, which is what the crash recovery problem asks for.

Lemma 2 (current value). In normal processing, the current value of XX (the buffer copy if XX is dirty, else the disk copy) is the newest after image of the active transaction that has written XX, if there is one; otherwise it is the after image of the newest update on XX by a transaction that has committed, or the initial value.

Proof. By induction on the steps, starting from a state where every item holds its last committed value (the initial state, or the end of a recovery by the Theorem below). Line L2 sets the value to the new after image, and by strictness the writer is the only active writer of XX. A commit makes the active writer's last after image the newest committed one. Line L6 puts back, newest first, the before images of the aborting transaction; the oldest of them was the current value just before that transaction first wrote XX, which by the induction and strictness was the last committed value, and no commit on XX happened in between. Lines L3 and L4 copy the value from the buffer to the disk and do not change it. □\square

Lemma 3 (UR1). At every time, if the disk copy of XX holds an effect of an update record uu, then uu is in RR.

Proof. Every change to the buffer copy of XX sets its pageLSN to the LSN of the record it applies (lines L2 and L17, L19), or keeps a pageLSN at least as large (line L6). So the pageLSN is at least the LSN of every record whose effect the copy holds. Line L3 makes the log stable up to that pageLSN before line L4 writes the copy. □\square

Lemma 4 (passes). Let ss and LL come from line L11 and UU from line L12. The undo pass reads every record with LSN at least ss and every update of a transaction in LL. When the redo pass starts, C∩U=C∗∩UC \cap U = C^* \cap U, and every update with LSN larger than ss is by a transaction in UU.

Proof. Line L14 stops only below ss and only when the pass has read the start record of each transaction in LL. Those start records are in RR, since line L8 made the log stable up to the checkpoint start, and each one comes before all updates of its transaction. A transaction in UU was active at the checkpoint start or started after it, so its commit record, if any, has LSN larger than ss, and line L15 has read it. A transaction that writes after the checkpoint start is active then, so it is in LL or its start record is after ss. When there is no checkpoint, s=0s = 0, the pass reads all of RR, and UU holds every transaction. □\square

Lines L15 to L17 meet the commit record of a transaction before its updates, because the pass goes backwards. So line L17 undoes exactly the updates in the pass by transactions in U∖C∗U \setminus C^*, newest first, and line L19 redoes exactly the updates after ss by transactions in C∗C^*, oldest first.

Theorem. When RECOVER ends, after any number of crashes in normal processing or in earlier runs of RECOVER, every item XX holds τ(X)\tau(X) on disk and is clean.

Proof. A run of RECOVER appends nothing before line L21, so all runs that crash before line L21 ends see the same RR. Each run computes the value it gives to XX from RR alone, and only for the items that lines L17 and L19 touch; it writes the others never. So a crashed run changes only touched items, and the last run writes all touched items again (line L20, or an OUTPUT after the last change). The records that line L21 adds are abort records, which no line of RECOVER reads. So it is enough to show that one full run gives τ(X)\tau(X), from the disk that the crash left. Fix XX. There are three cases.

Case A: some update on XX after ss is by a transaction in C∗C^*. Line L19 runs after all of line L17, and its last change to XX is the newest such update. By Lemma 4 every update of a transaction in C∗C^* after ss is redone, and an update on XX by C∗C^* before ss is older. So XX gets τ(X)\tau(X).

Case B: no update on XX after ss is by C∗C^*, but some update on XX in the undo pass is by a transaction in U∖C∗U \setminus C^*. Line L19 does not touch XX. Line L17 undoes these updates newest first, so XX ends with the before image vv of the oldest one, ee, by transaction TeT_e. No earlier update of TeT_e on XX exists (it would be older than ee and also undone), so ee is the first write of TeT_e to XX, and by Lemma 2 and strictness, vv is the after image of the newest committed update on XX before ee, or the initial value. This is τ(X)\tau(X) unless some update cc on XX by C∗C^* has LSN larger than ee. Suppose there is one. In case B, cc is before ss. By strictness TeT_e ended before cc, and it did not commit (its commit would be in RR after ss, by Lemma 4). So TeT_e ended before cc by a rollback, or by a crash and a recovery that undid it, and in both cases before the checkpoint start. Then TeT_e is not in LL and did not start after ss, so Te∉UT_e \notin U, a contradiction.

Case C: neither. Recovery does not touch XX, so XX keeps its disk copy. If s=0s = 0, UU holds every transaction, so no update on XX is in RR, by Lemma 3 the disk copy is the initial value, and τ(X)\tau(X) is the initial value. If s>0s > 0, by Lemma 4 every update on XX after ss is by UU, and in case C there is none, by C∗C^* or by U∖C∗U \setminus C^*. Let tt be the time of line L9. At tt the disk copy of XX equals its current value. If an active transaction TT had written XX at tt, then TT was active at the checkpoint start, so T∈L⊆UT \in L \subseteq U, and TT is not in U∖C∗U \setminus C^*, so TT committed later with no further write to XX; its last write is the newest update on XX in RR and is τ(X)\tau(X), and by Lemma 2 it is the current value at tt. If no active transaction had written XX, Lemma 2 gives the last committed value at tt, and no later update on XX exists, so this is τ(X)\tau(X). After tt the disk copy changes only by line L4 on a dirty copy, and a copy becomes dirty only by an update on XX, which does not exist after tt.

In all cases line L20 writes the touched items, so at the end every item is clean and holds τ(X)\tau(X). □\square

Corollary (cost). One run of RECOVER reads each record from the end of RR back to the oldest start record of a transaction in LL (or to the checkpoint start, if that is older) once, then the records after ss once more. Each touched item is written at least once and at most once per OUTPUT. Without a checkpoint, both passes read all of RR.

Remark (order of the passes). The proof of case A uses that line L19 runs after line L17. If redo ran first, case A would fail when a transaction that aborted in normal processing wrote XX before a committed transaction did: its undo would come last and put back its old before image. The test file builds this case. A system that logs each rollback step and redoes it, as ARIES does with compensation log records, avoids the problem in a different way; this proof does not cover that variant. This model does not log rollbacks, which is why it undoes aborted transactions in recovery.

Complexity

The cost of one recovery, counted in log records and items, in the worst case:

  • Log records read. The undo pass reads from the end of the log back to the oldest start record of a transaction in the checkpoint list, or to the checkpoint start if that is older: nn records. The redo pass reads the records after the checkpoint start once more, at most nn. Each record costs O(1)O(1) with hash sets, so the time is O(n)O(n).
  • Items written. Each item that recovery changes is written at least once, kk writes. In a system with many items per page, recovery reads and writes each touched page once, with enough buffer space.
  • Space. The sets UU, CC and open take O(m)O(m), the changed items O(k)O(k).

The checkpoint is what bounds nn. Without one, both passes read the whole log. With one, the work depends only on the log since the checkpoint start and on the active transactions at the checkpoint, not on the age of the database. In the test with 40 committed transactions of 3 updates each and a checkpoint before the last two transactions, recovery reads 13 records instead of 410 (a measurement of the implementation). A long-running transaction in the list pulls the undo pass back to its start record; this is the main reason to keep transactions short.

Properties

  • Any buffer policy. Steal and no-force are both allowed. Undo logging needs force and redo logging needs no-steal.
  • Idempotent. The records hold values, not operations, so applying a record twice gives the same result, and recovery can run again after a crash without extra bookkeeping.
  • Restartable. A crash during recovery is followed by a normal recovery.
  • Nonquiescent checkpoints. Transactions keep running during a checkpoint, but the checkpoint writes every dirty item.
  • Bounded log growth. Recovery appends one abort record per unfinished candidate, so repeated crashes during recovery add little to the log. ARIES gets the same bound with undo steps that it does log, as compensation log records.

Variants and improvements

  • The two simpler schemes. Each keeps only one value per update and pays for it with a buffer rule. Undo logging writes the items of TT before ⟨\langleCOMMIT T⟩T\rangle and recovers with one backward pass. Redo logging writes ⟨\langleCOMMIT T⟩T\rangle before any item of TT and recovers with one forward pass over committed transactions.
  • Quiescent checkpoint. Stop new transactions, wait for the active ones to end, write all dirty items, and write one CKPT record. Recovery then never reads past it, but the system stalls.
  • pageLSN test. With the pageLSN on disk, redo can skip a record whose LSN is at most the item's pageLSN. This turns the redo of CC in the example into a skip, and it is what allows logical logging, where a record cannot be applied twice.
  • ARIES. ARIES adds a prevLSN chain, logs undo steps as compensation log records, redoes every update before it undoes (repeating history), and replaces the checkpoint's page writes with a copy of the dirty page table (fuzzy checkpoint). This supports record-level locking inside a page and partial rollback.
  • Group commit. Several commit records share one log flush; see group commit.

When to use it

Use undo/redo logging when items are updated in place, the buffer manager must be free to write any item, and commit should cost one sequential log write. It is the right model to learn first: it shows why both kinds of information are needed under steal and no-force, and what each buffer rule buys. A real system with many records per page, record locks and operations that are not idempotent uses ARIES. A main-memory system that never writes uncommitted data needs only redo logging. Shadow paging avoids the undo information by never writing in place.

Pitfalls

  • Treat an abort record as the end. If a stolen value of TT reached the disk before TT aborted, and the rollback was done only in the buffer, the disk still holds it after a crash. Unless rollbacks are logged, undo aborted transactions in recovery. The test file builds this case.
  • Redo before undo, with unlogged rollbacks. See the example under Correctness.
  • Stop the undo pass at the checkpoint start. A transaction in the list can have updates before the checkpoint, and the checkpoint may have written them. Read back to its start record.
  • Use an incomplete checkpoint. A START CKPT without a matching END CKPT does not promise that the earlier changes are on disk. Use the START CKPT of the last END CKPT.
  • Break the write-ahead rule. If an item reaches the disk before its update record, a crash can leave a value of an unfinished transaction with no record to undo it. The test file builds this case too.
  • Undo in the wrong order. Undo newest first. If one transaction wrote XX twice, undo oldest first leaves the middle value.

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.

undo_redo_logging.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/undo-redo-logging/. The authors are listed in prov/E549PJ.jsonl.

"""Undo/redo logging with the record forms of Garcia-Molina, Ullman and Widom.

Model: each database item X is one page that holds one integer. Stable storage
is the disk (item -> (pageLSN, value)) and the stable log. Volatile storage is
the buffer (the dirty items only), the log tail and the list of updates of each
active transaction. The buffer policy is steal and no-force: output may write a
dirty item at any time, and it obeys rule UR1 (the update record first).

The LSN of a record is its index in the log plus 1. Record kinds and the forms
of the book: START is <START T>, UPDATE is <T, X, v, w>, COMMIT is <COMMIT T>,
ABORT is <ABORT T>, START_CKPT is <START CKPT (T_1, ..., T_k)> and END_CKPT is
<END CKPT>. Each public method is one atomic step. recovery() is a generator
that yields after each step, so that a test can crash inside recovery.
"""

from dataclasses import dataclass
from typing import Iterator


@dataclass(frozen=True)
class Rec:
    lsn: int
    kind: str  # START, UPDATE, COMMIT, ABORT, START_CKPT, END_CKPT
    txn: int = 0
    item: str = ""
    old: int = 0  # v, the before image (undo information)
    new: int = 0  # w, the after image (redo information)
    active: tuple = ()  # START_CKPT: the active transactions T_1, ..., T_k


class Db:
    """A database with undo/redo logging. Each step costs O(1), except a log
    flush (the records in the tail) and a checkpoint (the dirty items)."""

    def __init__(self, disk: dict, log: list | None = None) -> None:
        # disk maps an item to its value, or to a pair (pageLSN, value)
        self.disk = {x: (v if isinstance(v, tuple) else (0, v)) for x, v in disk.items()}
        self.log: list[Rec] = list(log or [])  # the stable log
        self.tail: list[Rec] = []  # the log records not yet on disk
        self.buf: dict[str, list] = {}  # dirty item -> [pageLSN, value]
        self.updates: dict[int, list[Rec]] = {}  # active T -> its update records
        self.read_count = 0  # log records read by the last recovery

    # ---- log and buffer -------------------------------------------------
    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:
        keep = []
        for r in self.tail:
            (self.log if upto is None or r.lsn <= upto else keep).append(r)
        self.tail = keep

    def flushed_lsn(self) -> int:
        return len(self.log)

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

    def _set(self, x: str, lsn: int, v: int) -> None:
        self.buf[x] = [lsn, v]

    def output(self, x: str) -> None:
        """Write a dirty item to disk (steal or clean)."""
        if x not in self.buf:
            return
        lsn, v = self.buf.pop(x)
        self.flush_log(lsn)  # @line L3: rule UR1, the update record first
        assert lsn <= self.flushed_lsn()
        self.disk[x] = (lsn, v)  # @line L4

    def crash(self) -> "Db":
        """Lose the buffer, the log tail and every volatile table."""
        return Db(dict(self.disk), list(self.log))

    # ---- normal processing ----------------------------------------------
    def start(self, t: int) -> None:
        self._append(kind="START", txn=t)
        self.updates[t] = []

    def write(self, t: int, x: str, w: int) -> None:
        v = self.value(x)  # @line L1
        r = self._append(kind="UPDATE", txn=t, item=x, old=v, new=w)  # @line L2
        self._set(x, r.lsn, w)  # @line L2
        self.updates[t].append(r)

    def commit(self, t: int) -> None:
        r = self._append(kind="COMMIT", txn=t)  # @line L5
        self.flush_log(r.lsn)  # @line L5: the commit returns after this
        del self.updates[t]

    def abort(self, t: int) -> None:
        for r in reversed(self.updates.pop(t)):  # @line L6: newest first
            lsn = self.buf[r.item][0] if r.item in self.buf else self.disk[r.item][0]
            self._set(r.item, lsn, r.old)  # @line L6
        self._append(kind="ABORT", txn=t)  # @line L7

    def ckpt_start(self) -> None:
        r = self._append(kind="START_CKPT", active=tuple(sorted(self.updates)))  # @line L8
        self.flush_log(r.lsn)  # @line L8

    def ckpt_flush(self) -> None:
        for x in sorted(self.buf):  # @line L9
            self.output(x)  # @line L9

    def ckpt_end(self) -> None:
        r = self._append(kind="END_CKPT")  # @line L10
        self.flush_log(r.lsn)  # @line L10

    # ---- recovery ---------------------------------------------------------
    def last_checkpoint(self) -> tuple[int, tuple]:
        """The LSN s and the list of the START CKPT that matches the last
        END CKPT of the stable log, or (0, ()) if there is none."""
        seen_end = False
        for r in reversed(self.log):
            if r.kind == "END_CKPT":
                seen_end = True
            elif r.kind == "START_CKPT" and seen_end:
                return r.lsn, r.active
        return 0, ()

    def recovery(self, write_aborts: bool = True) -> Iterator[str]:
        self.buf, self.tail, self.updates = {}, [], {}
        s, listed = self.last_checkpoint()  # @line L11
        cand = set(listed) | {r.txn for r in self.log[s:] if r.kind == "START"}  # @line L12
        committed: set[int] = set()  # @line L12
        open_ = set(listed)  # @line L12
        self.read_count = 0
        for r in reversed(self.log):  # @line L13: the undo pass
            if r.lsn < s and not open_:  # @line L14
                break
            self.read_count += 1
            if r.kind == "COMMIT":  # @line L15
                committed.add(r.txn)
            elif r.kind == "START":  # @line L16
                open_.discard(r.txn)
            elif r.kind == "UPDATE" and r.txn in cand and r.txn not in committed:  # @line L17
                self._set(r.item, r.lsn, r.old)
                yield "undo"
        for r in self.log[s:]:  # @line L18: the redo pass
            self.read_count += 1
            if r.kind == "UPDATE" and r.txn in committed:  # @line L19
                self._set(r.item, r.lsn, r.new)
                yield "redo"
        for x in sorted(self.buf):  # @line L20
            self.output(x)
            yield "output"
        if write_aborts:
            for t in sorted(cand - committed):  # @line L21
                self._append(kind="ABORT", txn=t)
            self.flush_log()  # @line L21
            yield "abort records"

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

    def state(self) -> dict[str, int]:
        return {x: self.value(x) for x in sorted(self.disk)}
test_undo_redo_logging.py 300 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/undo-redo-logging/. The authors are listed in prov/E549PJ.jsonl.

"""Crash-injection tests for undo/redo logging.

A seeded generator builds a strict workload against a live database: write
locks are held to the end of each transaction, page outputs (steals), log
flushes, aborts and the three steps of a nonquiescent checkpoint come at random
places. Each test replays a prefix of the workload, crashes, recovers and
compares the result with the oracle: the writes of the committed transactions,
applied in commit order.
"""

import random
import unittest

from undo_redo_logging import Db, Rec

ITEMS = "abcde"


def make_workload(db: Db, rng: random.Random, n_ops: int, first_txn: int = 1) -> list:
    """Run n_ops random steps on db and return them as a list of tuples."""
    ops: list = []
    owner: dict[str, int] = {}  # item -> the transaction that holds its write lock
    active: list[int] = []
    next_txn = first_txn
    next_val = 100 * first_txn
    phase = 0  # 0: no checkpoint, 1: after START CKPT, 2: after the flush
    while len(ops) < n_ops:
        roll = rng.random()
        if roll < 0.12 and len(active) < 4:
            op = ("start", next_txn)
            active.append(next_txn)
            next_txn += 1
        elif roll < 0.55 and active:
            t = rng.choice(active)
            free = [x for x in ITEMS if owner.get(x, t) == t]
            if not free:
                continue
            x = rng.choice(free)
            next_val += 1
            op = ("write", t, x, next_val)
            owner[x] = t
        elif roll < 0.68 and active:
            t = rng.choice(active)
            op = ("commit", t) if rng.random() < 0.7 else ("abort", t)
            active.remove(t)
            owner = {x: u for x, u in owner.items() if u != t}
        elif roll < 0.80 and db.buf:
            op = ("output", rng.choice(sorted(db.buf)))
        elif roll < 0.86:
            op = ("flush",)
        elif roll < 0.95:
            op = ("ckpt_start", "ckpt_flush", "ckpt_end")[phase]
            op = (op,)
            phase = (phase + 1) % 3
        else:
            continue
        apply_op(db, op)
        ops.append(op)
    return ops


def apply_op(db: Db, op: tuple) -> None:
    kind = op[0]
    if kind == "start":
        db.start(op[1])
    elif kind == "write":
        db.write(op[1], op[2], op[3])
    elif kind == "commit":
        db.commit(op[1])
    elif kind == "abort":
        db.abort(op[1])
    elif kind == "output":
        db.output(op[1])
    elif kind == "flush":
        db.flush_log()
    else:
        getattr(db, kind)()


def oracle(base: dict, ops: list) -> dict:
    """The committed writes, applied in commit order, on top of base."""
    state = dict(base)
    pending: dict[int, list] = {}
    for op in ops:
        if op[0] == "start":
            pending[op[1]] = []
        elif op[0] == "write":
            pending[op[1]].append((op[2], op[3]))
        elif op[0] == "commit":
            for x, w in pending.pop(op[1]):
                state[x] = w
        elif op[0] == "abort":
            pending.pop(op[1])
    return state


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


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


def recover_with_crashes(db: Db, rng: random.Random, stop_after: int) -> tuple[Db, bool]:
    """Run recovery for stop_after steps with random outputs between steps,
    then crash. Return the crashed database and whether recovery finished."""
    steps = db.recovery()
    for _ in range(stop_after):
        if next(steps, None) is None:
            return db.crash(), True
        if db.buf and rng.random() < 0.5:
            db.output(rng.choice(sorted(db.buf)))
    return db.crash(), False


def recovered_state(db: Db) -> dict:
    db.recover()
    assert not db.buf and not db.tail
    return {x: v for x, (_, v) in sorted(db.disk.items())}


INIT = {x: 0 for x in ITEMS}


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, 70)
            for k in range(len(ops) + 1):
                db = replay((INIT, []), ops[:k]).crash()
                self.assertEqual(recovered_state(db), oracle(INIT, ops[:k]), (seed, k))

    def test_crash_during_recovery(self):
        for seed in range(12):
            rng = random.Random(1000 + seed)
            ops = make_workload(Db(INIT), rng, 60)
            for k in range(0, len(ops) + 1, 3):
                want = oracle(INIT, ops[:k])
                for j in range(0, 40, 2):
                    db = replay((INIT, []), ops[:k]).crash()
                    db, done = recover_with_crashes(db, rng, j)
                    # a second crash inside the second recovery
                    db, _ = recover_with_crashes(db, rng, j // 2)
                    self.assertEqual(recovered_state(db), want, (seed, k, j))
                    if done:
                        break

    def test_two_eras(self):
        # Recover, keep working on the recovered database, crash again.
        for seed in range(10):
            rng = random.Random(2000 + seed)
            ops1 = make_workload(Db(INIT), rng, 50)
            cut = rng.randrange(len(ops1) + 1)
            db = replay((INIT, []), ops1[:cut]).crash()
            base = recovered_state(db)
            self.assertEqual(base, oracle(INIT, ops1[:cut]))
            snap = snapshot(db)
            ops2 = make_workload(replay(snap, []), rng, 50, first_txn=1000)
            for k in range(len(ops2) + 1):
                db2 = replay(snap, ops2[:k]).crash()
                self.assertEqual(recovered_state(db2), oracle(base, ops2[:k]), (seed, k))


def page_example() -> Db:
    """The example of the page, built step by step."""
    db = Db({"A": 10, "B": 20, "C": 30})
    db.start(1)
    db.write(1, "A", 11)
    db.start(2)
    db.write(2, "B", 21)
    db.commit(1)
    db.ckpt_start()
    db.write(2, "C", 31)
    db.start(3)
    db.write(3, "A", 12)
    db.ckpt_flush()
    db.ckpt_end()
    db.commit(2)
    db.write(3, "B", 22)
    db.output("B")
    return db


def redo_first_recover(db: Db) -> None:
    """The wrong order: redo the committed transactions, then undo the rest."""
    s, listed = db.last_checkpoint()
    cand = set(listed) | {r.txn for r in db.log[s:] if r.kind == "START"}
    committed = {r.txn for r in db.log if r.kind == "COMMIT"}
    for r in db.log[s:]:
        if r.kind == "UPDATE" and r.txn in committed:
            db.buf[r.item] = [r.lsn, r.new]
    for r in reversed(db.log):
        if r.kind == "UPDATE" and r.txn in cand and r.txn not in committed:
            db.buf[r.item] = [r.lsn, r.old]
    for x in sorted(db.buf):
        db.output(x)


class TestExamplesAndPitfalls(unittest.TestCase):
    def test_page_example(self):
        db = page_example()
        self.assertEqual(len(db.log), 12)
        self.assertEqual(db.disk, {"A": (9, 12), "B": (12, 22), "C": (7, 31)})
        db = db.crash()
        self.assertEqual(db.last_checkpoint(), (6, (2,)))
        steps = list(db.recovery())
        self.assertEqual(steps, ["undo", "undo", "redo", "output", "output", "output", "abort records"])
        self.assertEqual(db.read_count, 16)  # 10 in the undo pass, 6 in the redo pass
        self.assertEqual(db.state(), {"A": 11, "B": 21, "C": 31})
        self.assertEqual(db.log[-1], Rec(13, "ABORT", 3))

    def test_redo_first_is_wrong(self):
        def build() -> Db:
            db = Db({"X": 1})
            db.start(1)
            db.write(1, "X", 2)
            db.abort(1)  # the rollback is done in the buffer and is not logged
            db.start(2)
            db.write(2, "X", 3)
            db.commit(2)
            return db.crash()

        good = build()
        good.recover()
        self.assertEqual(good.state(), {"X": 3})
        bad = build()
        redo_first_recover(bad)
        self.assertEqual(bad.state(), {"X": 1})

    def test_aborted_transaction_must_be_undone(self):
        # A stolen value of an aborted transaction stays on disk if recovery
        # treats <ABORT T> as complete.
        db = Db({"X": 1})
        db.start(1)
        db.write(1, "X", 2)
        db.output("X")
        db.abort(1)
        db.start(2)
        db.commit(2)
        db = db.crash()
        self.assertEqual(db.disk["X"], (2, 2))
        db.recover()
        self.assertEqual(db.state(), {"X": 1})

    def test_ur1_violation_breaks_recovery(self):
        class NoWal(Db):
            def output(self, x):
                if x in self.buf:
                    self.disk[x] = tuple(self.buf.pop(x))

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

        db = NoWal({"X": 1})
        db.start(1)
        db.write(1, "X", 2)
        db.output("X")
        db = db.crash()
        self.assertEqual(db.log, [])
        db.recover()
        self.assertEqual(db.state(), {"X": 2})  # wrong: T1 never committed

    def test_checkpoint_bounds_the_scan(self):
        def run(with_ckpt: bool) -> Db:
            db = Db({x: 0 for x in ITEMS})
            rng = random.Random(7)
            for t in range(1, 41):
                db.start(t)
                for _ in range(3):
                    db.write(t, rng.choice(ITEMS), rng.randrange(1000))
                db.commit(t)
            if with_ckpt:
                db.ckpt_start()
                db.ckpt_flush()
                db.ckpt_end()
            db.start(99)
            db.write(99, "a", -1)
            db.start(98)
            db.write(98, "b", -2)
            db.commit(98)
            return db.crash()

        a, b = run(False), run(True)
        a.recover()
        b.recover()
        self.assertEqual(a.state(), b.state())
        self.assertEqual(b.read_count, 13)  # the numbers given on the page
        self.assertEqual(a.read_count, 410)


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

History

Jim Gray's 1978 notes on data base operating systems describe a log that holds undo and redo information and is written ahead of the data. Haerder and Reuter (1983) classified recovery schemes by their buffer policies (steal or not, force or not) and by the log information each needs, which is where undo/redo logging appears as the scheme for steal and no-force. Bernstein, Hadzilacos and Goodman (1987) gave the undo/redo algorithm with its checkpoints as one of four recovery algorithms. Garcia-Molina, Ullman and Widom present undo logging, redo logging and undo/redo logging in this order, with the record forms used on this page. ARIES (1992) is the refined form that most systems follow.

References

  1. Hector Garcia-Molina, Jeffrey D. Ullman and Jennifer Widom, Database Systems, The Complete Book, second edition, Pearson Prentice Hall, 2009, Chapter 17, Coping with System Failures, Sections 17.2 (Undo Logging), 17.3 (Redo Logging) and 17.4 (Undo/Redo Logging), the rules for each scheme and the recovery with checkpoints
  2. Theo Haerder and Andreas Reuter, Principles of transaction-oriented database recovery, ACM Computing Surveys 15(4), 1983, pages 287 to 317, the classification of logging and buffer schemes (STEAL and FORCE) and the undo and redo actions that each scheme needs
  3. Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 6 (the undo/redo algorithm and its checkpoints), chapter level only
  4. Jim Gray, Notes on data base operating systems, in Operating Systems, An Advanced Course, Lecture Notes in Computer Science 60, Springer, 1978, pages 393 to 481, the section on recovery management (the log with undo and redo information, written ahead of the data)
  5. 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.1, Log Records (the fields of an update record and of a CLR), for the map to the ARIES fields

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