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.
- Solves
- Crash recovery problem
- 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
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- 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 is a page with one value. The schedule is strict: a transaction that wrote 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:
- START : transaction begins;
- : changed item from old value to new value (undo logging writes only , redo logging only );
- COMMIT and ABORT ;
- START CKPT , where are the active transactions, and END CKPT, 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 |
|---|---|---|
| START | BEGIN | ARIES needs none: a prevLSN of 0 marks the first record of |
| UPDATE | ARIES adds the record's LSN, the prevLSN of and a location in the page; and are the before and after images | |
| COMMIT , ABORT | COMMIT, ABORT | ARIES logs each undo step as a CLR and closes with END |
| START CKPT | BEGIN_CHECKPOINT | the list is the set of keys of the ARIES transaction table |
| END CKPT | 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.
WRITE(T, X, w)- 1
v ← the current value of X (the buffer copy if X is dirty, else the disk copy) - 2
append ⟨T, X, v, w⟩ to the log tail; X ← w in the buffer; pageLSN(X) ← the LSN of the record OUTPUT(X) ▷ the buffer manager calls it at any time- 3
flush the log up to pageLSN(X) ▷ the write-ahead rule (UR1) - 4
write X with its pageLSN to disk; X is clean COMMIT(T)- 5
append ⟨COMMIT T⟩; flush the log up to it; report the commit ABORT(T)- 6
for each update ⟨T, X, v, w⟩ of T, newest first, do X ← v in the buffer - 7
append ⟨ABORT T⟩ ▷ not forced CHECKPOINT() ▷ other steps may run between L8, L9 and L10- 8
append ⟨START CKPT (T_1, ..., T_k)⟩ for the active T_i; flush the log - 9
OUTPUT every dirty item - 10
append ⟨END CKPT⟩; flush the log RECOVER()- 11
s, L ← the LSN and the list of the START CKPT that matches the last END CKPT (s ← 0, L ← ∅ if none) - 12
U ← L ∪ {T : ⟨START T⟩ is after s}; C ← ∅; open ← L - 13
for each record r of the stable log, from the end backwards do ▷ undo pass - 14
if r.lsn < s and open = ∅ then stop - 15
if r = ⟨COMMIT T⟩ then add T to C - 16
else if r = ⟨START T⟩ then remove T from open - 17
else if r = ⟨T, X, v, w⟩ with T ∈ U and T ∉ C then X ← v; pageLSN(X) ← r.lsn - 18
for each record r after s, forwards do ▷ redo pass - 19
if r = ⟨T, X, v, w⟩ with T ∈ C then X ← w; pageLSN(X) ← r.lsn - 20
OUTPUT every item that lines L17 and L19 changed - 21
append ⟨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 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 , , on disk, all with pageLSN 0. The run before the crash:
| LSN | record | note |
|---|---|---|
| 1 | START | |
| 2 | ||
| 3 | START | |
| 4 | ||
| 5 | COMMIT | log flushed to 5 |
| 6 | START CKPT | log flushed to 6 |
| 7 | ||
| 8 | START | |
| 9 | then line L9 flushes the log to 9 and writes , , | |
| 10 | END CKPT | log flushed to 10 |
| 11 | COMMIT | log flushed to 11 |
| 12 | the buffer writes : log flushed to 12, on disk |
Then the system crashes. The disk holds and , both written by , which never committed. Recovery finds the checkpoint at with list , so .
| pass | records read | action |
|---|---|---|
| undo | 12 | has no commit seen: |
| undo | 11, 10 | |
| undo | 9, 8 | : |
| undo | 7, 6, 5 | committed: skip LSN 7; LSN 5 adds to , which does no harm |
| undo | 4, 3 | committed: skip; LSN 3 closes , so open is empty; the pass stops before LSN 2 |
| redo | 7 to 12 | LSN 7: |
| end | write , , ; append ABORT as LSN 13 |
Recovery reads 10 records backwards and 6 forwards and writes 3 items. The result is , , , the values of the committed and . The undo of is needed because the checkpoint itself wrote the uncommitted value 12 to disk. The redo of 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 and splits into three cases. If a committed transaction updated after the checkpoint start, the redo pass runs last and leaves the newest such value. Otherwise, if an unfinished candidate updated , 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 , 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 . writes 2 and aborts, which puts back 1 in the buffer without a log record. writes 3 and commits. After a crash, undo then redo gives 3. Redo then undo gives 1: the undo of , 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 is a page with one value and a pageLSN. The schedule is strict: after a transaction writes , no other transaction writes until 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 and loses the buffer, the log tail and the lists of updates. The log only grows at its end, so is always a prefix of the log that the run appended.
For an item , the target is the after image of the newest update on in by a transaction with a commit record in , or the initial value of if there is no such update. Write for the set of transactions with a commit record in .
Lemma 1 (order). Among the transactions that write and commit, the order of their updates on in the log is the order of their commits.
Proof. If writes before does, strictness puts the end of between the two writes, and commits after its own write.
So is the value of 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 (the buffer copy if is dirty, else the disk copy) is the newest after image of the active transaction that has written , if there is one; otherwise it is the after image of the newest update on 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 . 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 , which by the induction and strictness was the last committed value, and no commit on happened in between. Lines L3 and L4 copy the value from the buffer to the disk and do not change it.
Lemma 3 (UR1). At every time, if the disk copy of holds an effect of an update record , then is in .
Proof. Every change to the buffer copy of 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.
Lemma 4 (passes). Let and come from line L11 and from line L12. The undo pass reads every record with LSN at least and every update of a transaction in . When the redo pass starts, , and every update with LSN larger than is by a transaction in .
Proof. Line L14 stops only below and only when the pass has read the start record of each transaction in . Those start records are in , 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 was active at the checkpoint start or started after it, so its commit record, if any, has LSN larger than , and line L15 has read it. A transaction that writes after the checkpoint start is active then, so it is in or its start record is after . When there is no checkpoint, , the pass reads all of , and holds every transaction.
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 , newest first, and line L19 redoes exactly the updates after by transactions in , oldest first.
Theorem. When RECOVER ends, after any number of crashes in normal processing or in earlier runs of RECOVER, every item holds 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 . Each run computes the value it gives to from 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 , from the disk that the crash left. Fix . There are three cases.
Case A: some update on after is by a transaction in . Line L19 runs after all of line L17, and its last change to is the newest such update. By Lemma 4 every update of a transaction in after is redone, and an update on by before is older. So gets .
Case B: no update on after is by , but some update on in the undo pass is by a transaction in . Line L19 does not touch . Line L17 undoes these updates newest first, so ends with the before image of the oldest one, , by transaction . No earlier update of on exists (it would be older than and also undone), so is the first write of to , and by Lemma 2 and strictness, is the after image of the newest committed update on before , or the initial value. This is unless some update on by has LSN larger than . Suppose there is one. In case B, is before . By strictness ended before , and it did not commit (its commit would be in after , by Lemma 4). So ended before by a rollback, or by a crash and a recovery that undid it, and in both cases before the checkpoint start. Then is not in and did not start after , so , a contradiction.
Case C: neither. Recovery does not touch , so keeps its disk copy. If , holds every transaction, so no update on is in , by Lemma 3 the disk copy is the initial value, and is the initial value. If , by Lemma 4 every update on after is by , and in case C there is none, by or by . Let be the time of line L9. At the disk copy of equals its current value. If an active transaction had written at , then was active at the checkpoint start, so , and is not in , so committed later with no further write to ; its last write is the newest update on in and is , and by Lemma 2 it is the current value at . If no active transaction had written , Lemma 2 gives the last committed value at , and no later update on exists, so this is . After the disk copy changes only by line L4 on a dirty copy, and a copy becomes dirty only by an update on , which does not exist after .
In all cases line L20 writes the touched items, so at the end every item is clean and holds .
Corollary (cost). One run of RECOVER reads each record from the end of back to the oldest start record of a transaction in (or to the checkpoint start, if that is older) once, then the records after once more. Each touched item is written at least once and at most once per OUTPUT. Without a checkpoint, both passes read all of .
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 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: records. The redo pass reads the records after the checkpoint start once more, at most . Each record costs with hash sets, so the time is .
- Items written. Each item that recovery changes is written at least once, writes. In a system with many items per page, recovery reads and writes each touched page once, with enough buffer space.
- Space. The sets , and open take , the changed items .
The checkpoint is what bounds . 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 before COMMIT and recovers with one backward pass. Redo logging writes COMMIT before any item of 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 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 reached the disk before 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 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.
# 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
- 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
- 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag E549PJ Edit this page History Report an error Markdown