Algorithmadvanced
Multi-level transaction recovery
Also called multilevel transactions.
Recover transactions whose operations release low-level locks early by undoing completed subtransactions with logical inverse operations.
- Solves
- Crash recovery problem
- Time
- O(n + u (c + log m) + c m) worst
- Space
- O(m) extra
- Where
- c = the level 0 updates of one operation; m = the number of losers; n = the records in the stable log; u = the completed operations of the losers that are not yet compensated
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gerhard Weikum, David Lomet, 1991
Multi-level transaction recovery restores a database after a crash when transactions are built from operations at two or more levels, and each high-level operation releases its low-level locks as soon as it ends, long before its transaction commits. Physical undo by before images is then wrong: another transaction may already have changed the same page or record. The method undoes an operation that is still running at the low level, with before images, and undoes an operation that has completed at the high level, by running its logical inverse as a new operation. It extends ARIES, which has the same pageLSN redo and compensation log records, and it is the recovery side of the transaction model whose concurrency side is open nesting.
In plain words
A bank keeps a counter for each branch and one for the grand total. Adding money to a branch is one small job: change the branch counter, then change the total. While the job runs, it holds those two counters. When the job ends, it lets them go, even though the customer has not yet confirmed.
So two customers can add money to the same branch, one after the other, before either confirms. If the first one now cancels, you cannot put back the old number that the counter had before his deposit. That would also wipe out the second deposit. You must subtract his amount instead.
After a crash, recovery does two repairs. A small job that was cut in half is put back exactly, with the old numbers, because nobody else touched what it held. A small job that ended is taken back with its opposite job.
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, and a commit that forces the log. On top of it, a transaction is a sequence of level 1 operations, and each level 1 operation is a short subtransaction of level 0 page writes.
- Level 0 locks are on the records that one operation writes. The operation holds them until it ends, so at level 0 each operation is strict.
- Level 1 locks are on the abstract objects that the operations change. Two operations conflict at level 1 only if they do not commute. A transaction holds its level 1 locks to its end.
- Each completed operation has an inverse: an operation that removes its effect from any state that later commuting operations may have reached.
The running example is the one of the code: counters, an operation ADD(x, d) that writes x and then the total t, and the inverse ADD(x, -d). Two ADDs always commute, so there are no level 1 locks at all, and two transactions can increase the same counter before either commits.
Recovery must leave every counter with its initial value plus the changes of the committed transactions. It must stay correct when it crashes during its own run.
The algorithm
The log holds ARIES records plus two record types at level 1. An op_commit record ends an operation: it holds the inverse operation and opPrev, the lastLSN of the transaction before the operation began. A comp_commit record ends a compensation, the run of an inverse: it holds the LSN of the op_commit that it compensates and an undoNextLSN equal to that op_commit's opPrev. Level 0 updates and level 0 CLRs are the ARIES records.
RESTART()- 1
for each record r of the stable log, in LSN order do ▷ analysis - 2
if r is commit then mark r.T a winner; if r is end then forget r.T - 3
otherwise lastLSN[r.T] ← r.lsn; undoNext[r.T] ← r.undoNextLSN if r is a CLR or a comp_commit, else r.lsn - 4
write ⟨end, T⟩ for each winner T; the transactions that are left are the losers - 5
for each update or CLR r of the log, in LSN order do ▷ redo: repeat history at level 0 - 6
if pageLSN(r.page) < r.lsn then write r.after into the page; pageLSN(r.page) ← r.lsn - 7
for each loser T do ▷ level 0 pass - 8
while the record u named by undoNext[T] is an update or a CLR do - 9
if u is a CLR then undoNext[T] ← u.undoNextLSN - 10
else append ⟨CLR, T, u.page, u.key, value = u.before, undoNextLSN = u.prevLSN⟩; write u.before; undoNext[T] ← u.prevLSN - 11
while a loser is left do ▷ level 1 pass - 12
T ← the loser with the largest undoNext[T]; r ← the record undoNext[T] - 13
if r is op_commit then run the inverse r.inverse as a new level 0 operation of T - 14
append ⟨comp_commit, T, undone = r.lsn, undoNextLSN = r.opPrev⟩; undoNext[T] ← r.opPrev - 15
else if r is comp_commit then undoNext[T] ← r.undoNextLSN - 16
else if r is abort then undoNext[T] ← r.prevLSN - 17
else append ⟨end, T⟩ and remove T ▷ r is the begin record of T - 18
force the log ADD(T, x, d) ▷ one level 1 operation in normal work- 19
p ← lastLSN[T]; take the level 0 lock on x, then on t, when each write needs it - 20
append ⟨update, T, x, before, before + d⟩ and apply it; then the same for t - 21
append ⟨op_commit, T, inverse = ADD(x, -d), opPrev = p⟩; release the level 0 locks
Analysis and redo (lines L1 to L6) are those of ARIES without a checkpoint: they find the losers, each with the head of its chain, and repeat history at level 0, losers included. After redo every page holds the effect of the whole stable log.
The level 0 pass (lines L7 to L10) finishes level 0. A loser can have at most one operation that did not reach its op_commit: an operation of normal work, or a compensation that a crash cut off. Its level 0 updates sit at the head of the chain. The pass undoes them with before images and CLRs, as ARIES does. This is safe because the operation still held its level 0 locks at the crash, so no other transaction wrote those records after it. The pass stops at the first record that is not a level 0 record: an op_commit, a comp_commit, an abort or a begin. Now every page is operation consistent: it holds the effect of completed operations only.
The level 1 pass (lines L11 to L17) undoes the completed operations of the losers, newest first. For an op_commit it runs the inverse as a new operation with its own level 0 updates (line L13), and then writes a comp_commit whose undoNextLSN skips the compensated operation (line L14). A comp_commit at the head means that the compensation is already done, so line L15 jumps over it. A later crash during a compensation leaves level 0 updates without a comp_commit: the next restart undoes them in the level 0 pass, finds the op_commit at the head again, and runs the compensation again from the start.
Normal rollback of an aborted transaction writes an abort record and runs lines L12 to L17 for that transaction alone, with the same level 0 locks as any operation.
Example
Pages: P0 holds t = 100, P1 holds a = 10 and b = 20, P2 holds c = 30 and d = 40. T1 runs ADD(a, 5). The buffer writes P1 to disk (a steal), and the write-ahead rule forces the log first. T2 then runs ADD(a, 7) on the same counter and commits. T3 starts ADD(c, 4), writes c, and P2 goes to disk. Then the system crashes.
| LSN | record | note |
|---|---|---|
| 1 | begin T1 | |
| 2 | update T1, P1, a: 10 to 15 | P1 on disk with pageLSN 2 |
| 3 | update T1, P0, t: 100 to 105 | |
| 4 | op_commit T1, inverse ADD(a, -5), opPrev 1 | T1 releases its locks on a and t |
| 5 to 8 | begin T2, a: 15 to 22, t: 105 to 112, op_commit T2 | T2 works on a before T1 ends |
| 9, 10 | commit T2, end T2 | the log is forced to 9 |
| 11 | begin T3 | |
| 12 | update T3, P2, c: 30 to 34 | P2 on disk with pageLSN 12 |
Analysis finds the losers T1 (undoNext 4) and T3 (undoNext 12). Redo applies LSNs 3 and 7 to P0 (pageLSN 0) and LSN 6 to P1 (pageLSN 2), and skips LSNs 2 and 12, which the disk pages already hold. Now a = 22, t = 112 and c = 34.
The level 0 pass meets the update 12 of T3 and writes CLR 13 (c := 30, undoNextLSN 11). The chain of T3 is now at its begin record, and the chain of T1 is at the op_commit 4, so the pass stops. The level 1 pass takes T3 first (undoNext 11 is larger than 4) and writes end 14. For T1 it runs ADD(a, -5): update 15 (a: 22 to 17), update 16 (t: 112 to 107), and comp_commit 17 with undoNextLSN 1. Then end 18.
The result is a = 17, b = 20, c = 30, d = 40 and t = 107: the initial values plus the committed +7 of T2, and t is again the sum of the four counters. Physical undo of T1 would write the before images of LSNs 3 and 2, t = 100 and a = 10, and lose the committed work of T2.
Correctness
Theorem. Assume the write-ahead rule, a forced commit record, level 0 locks held to the end of each operation, level 1 operations of concurrent transactions that commute (or level 1 locks held to commit for those that do not), and inverses that undo an operation from any state that commuting operations reach. Then after any number of crashes, also crashes during restart, a restart that runs to the end leaves each counter at its initial value plus the changes of the transactions whose commit record is in the stable log. No completed operation is compensated twice.
The proof has four steps. Redo repeats history, by the pageLSN argument of ARIES, so the state after redo is the effect of every level 0 record in the stable log. The stable log is a prefix of the log, so each CLR of the level 0 pass comes before any later write of the same record, and its before image is the right value; after the pass, the state is the effect of the completed operations and completed compensations only. The chain of a transaction, read through opPrev and the undoNextLSN of each comp_commit, visits exactly its completed operations that have no comp_commit, newest first. Each compensation then removes the effect of one such operation, because the inverse undoes it in the presence of commuting operations of other transactions. The full proof gives the lemmas for the model of the code.
Proof: Two-level restart leaves exactly the changes of committed transactionsfull
Model. This is the model of the implementation. Items are counters on pages, and is the total. A level 1 operation of transaction appends, in this order, an update of from to , an update of from to , and an op_commit record with the inverse and , the lastLSN of before . holds a level 0 lock on each item from its update to its op_commit. A compensation of is an operation of the same form with delta , closed by a comp_commit record with and . A transaction runs one operation or compensation at a time. It commits only between operations, and its commit record is forced. The buffer obeys the write-ahead rule. A crash keeps the disk and the stable log, which is a prefix of the log, and loses the rest. The delta of an update or CLR record is , where for a CLR the before value is the value of the item just before the CLR was applied.
Every record of except its begin record has prevLSN equal to the previous record of .
Lemma 1 (repeating history). After line L6, every page holds the effect of all update and CLR records of the stable log on that page, applied in LSN order.
Proof. Each page version on disk with pageLSN holds the effect of the records on it with LSN at most , in LSN order: normal work and restart set the pageLSN to the LSN of each record they apply, and by the write-ahead rule every such record is in the stable log. Lines L5 and L6 apply, in LSN order, exactly the records with LSN above . There is no checkpoint, so no record is skipped.
Lemma 2 (level 0 isolation). Let be an update of on item in the stable log, and let belong to an operation or compensation of . If the stable log has no op_commit or comp_commit that closes , then the stable log holds no update or CLR on by another transaction after .
Proof. In normal work holds the lock on from to its closing record. Since the closing record is not in the stable log and the stable log is a prefix, every record after that is in the stable log was appended while still held the lock, or after a crash. After a crash, the lock is gone, but the restart that follows writes on only in its level 0 pass for itself (line L10), or in a compensation of its level 1 pass. Every compensation starts after the level 0 pass has ended. When the level 0 pass ends, is compensated by a CLR of that is earlier in the log than any compensation of that restart, so if a later compensation's update on is in the stable log, then so is that CLR, and ends at level 0 before it.
Lemma 3 (chain). For a transaction and a prefix of the log, follow the chain from 's head: an update or abort record leads to its prevLSN, a CLR or a comp_commit to its undoNextLSN, an op_commit to its prevLSN at level 0 and to its opPrev at level 1. Then (a) at level 0 the chain visits exactly the updates of that are not compensated by a CLR and that belong to an operation or compensation without a closing record; (b) after these, at level 1, the chain visits exactly the completed operations of that have no comp_commit, newest first.
Proof. By induction over the records of , as Lemma 1 of the proof of ARIES. An update is put at the head. An op_commit closes the current operation: its opPrev skips the operation's level 0 updates, which are now part of a completed operation. A CLR for the head update has undoNextLSN equal to , which removes and nothing else. A comp_commit for has undoNextLSN equal to , which removes and the level 0 updates of the compensation itself. Line L3 sets the head to this pointer for a CLR or a comp_commit, and to the record itself otherwise, so analysis finds the head of each loser.
Lemma 4 (operation consistency). After the level 0 pass, the value of every item equals its initial value plus over the updates of completed operations and completed compensations in the log.
Proof. By Lemma 1, after redo the value of is its initial value plus the deltas of all updates and CLRs on . A CLR for an update of writes the before image of . By Lemma 2, no other transaction changed between and the CLR, and by Lemma 3(a) the CLRs of undo the updates of the open operation newest first, so the CLR's delta is . The level 0 pass compensates every update of Lemma 3(a). So the updates of open operations and their CLRs cancel in pairs, and what is left is the deltas of closed operations and compensations.
Lemma 5 (no double compensation). For each op_commit , the log holds at most one comp_commit with .
Proof. A comp_commit for is written only when the chain of the level 1 pass, or of a normal rollback, is at . Once it is in the log, by Lemma 3(b) no chain of any later prefix visits again. If it is in the volatile tail at a crash, it is lost together with every later record, and the stable log has none.
Theorem. After any number of crashes, also during restarts, a restart that runs to the end leaves every item at its initial value plus over the operations of the transactions whose commit record is in the stable log.
Proof. By Lemma 4, after the level 0 pass the value of is its initial value plus the deltas of all closed operations and compensations. A winner committed between operations, so all its operations are closed. For a loser, by Lemma 3(b), the level 1 pass compensates every completed operation that has no comp_commit, one at a time, and each compensation of adds to and to from whatever state it meets. This is correct because additions commute: the effect of a set of additions on a counter is their sum in any order. A compensation that a crash cuts off is open at the next restart, so it is undone at level 0 and run again; Lemma 5 rules out a second comp_commit. When the loser's chain reaches its begin record, each of its operations is paired with exactly one compensation, and its net delta is 0. Transactions that rolled back before the crash and wrote end records are in the same state. So the value is the initial value plus the deltas of the winners. The same holds for .
With operations that do not commute, the argument needs one more hypothesis: a transaction holds a level 1 lock on each object until it ends, so that no operation of another transaction that does not commute with comes between and its compensation. Under that hypothesis, the step "each compensation removes from any state it meets" holds for any inverse that is correct on the states that commuting operations reach.
Complexity
The cost is counted in log records and page operations for one restart. In the implementation the log has no checkpoint, so analysis and redo read the whole stable log, records, and redo reads each page at most once. With the fuzzy checkpoint of ARIES, analysis starts at the last checkpoint and redo at the smallest recLSN, so only the log after those points is read.
- Level 0 pass. Each loser has at most one cut-off operation, so the pass writes at most CLRs per loser, in total.
- Level 1 pass. Each of the completed operations costs one compensation: level 0 updates and one comp_commit, so the pass writes records and end records. Choosing the largest undoNext with a heap costs per step.
- Log volume per update. In normal work each level 0 write logs a before and an after image, and each operation adds one op_commit that holds its inverse. The inverse is small: a key and a delta.
- Repeated crashes. A compensation that a crash cuts off is undone and run again, so each crash during the level 1 pass can add up to records. ARIES has a bound on the total growth over all crashes; this method has a bound per crash.
The space is for the transaction table.
Properties
- Early release of low-level locks. A transaction holds a page or record lock only for the length of one operation, which is the point of the method for hot items such as counters and index pages.
- Logical undo, physical redo. Redo stays page-oriented and exact with the pageLSN test; only undo of completed operations is logical.
- Restartable. A comp_commit in the stable log removes its operation from the chain, so a crash never makes a completed compensation run again. A compensation without its comp_commit is undone at level 0 and run again.
- One code path. Normal rollback and restart use the same level 1 step, as ARIES uses one UNDO-STEP.
Variants and improvements
- More levels. With levels of records, pages and files, each level runs one pass, from the lowest level up, and each pass leaves the state consistent at the next level.
- Nested top actions of ARIES. ARIES gets the same effect for structure changes such as B-tree page splits: the split is logged, then closed by a dummy CLR whose undoNextLSN jumps over it, so rollback never undoes the split physically. The undo of the inserted key is a logical inverse.
- Escrow and counters. The escrow transactional method uses the same commutativity of increments, with checks on bounds.
- Long-running transactions. Sagas push the idea to whole transactions: each step commits, and a failure runs compensating steps. Sagas give up isolation between steps; level 1 locks keep it here.
When to use it
Use it when short low-level locks matter, for example on index pages, free-space maps and counters that many transactions update, and when each high-level operation has a cheap inverse. Plain ARIES with record locks held to commit is simpler when operations do not need to release their locks early. The method needs a correct inverse for every operation, which is easy for increments and for inserts and deletes of keys, and harder for operations whose inverse depends on data that the operation destroyed.
Pitfalls
- Physical undo of a completed operation. Line L13 must run the inverse. Before images of a completed operation can overwrite later changes of other transactions, as the example shows.
- Logical undo of a cut-off operation. The inverse of a whole ADD applied to an operation that wrote x but not yet t would also subtract from t. Cut-off operations must be undone at level 0, in lines L7 to L10, before any level 1 step.
- The order of the passes. The level 1 pass must start only after the level 0 pass has ended for every loser. An inverse that runs on a state that still holds half an operation acts on a state that no serial execution reaches.
- The undoNextLSN of a comp_commit. It must be the opPrev of the compensated operation, not the prevLSN of the comp_commit. Otherwise the next restart finds the op_commit again and compensates it twice.
- Inverses that do not commute. If two operations on the same object do not commute, the transaction must keep its level 1 lock to commit. Without it, the inverse is not correct.
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/multi-level-recovery/. The authors are listed in prov/7Q7BG3.jsonl.
"""Two-level transaction recovery on a simulated disk and log.
Level 1 operations are ADD(x, d) on counters. Each one is a subtransaction of
level 0 page writes: x := x + d, then t := t + d (t holds the total), then an
op_commit record that holds the inverse ADD(x, -d). Level 0 locks on x and t
are held only while the operation runs. ADDs commute, so level 1 needs no
locks, and two transactions may change the same counter before either commits.
Stable storage is the disk (page -> (values, page_lsn)) and the stable log.
The buffer pool, the log tail, the locks and the transaction tables are
volatile. The buffer policy is steal and no-force with the WAL rule. Each
public method is one atomic step, and restart() yields after each step, so a
test can crash anywhere, also inside recovery.
"""
from dataclasses import dataclass
from typing import Iterator
PAGE_OF = {"t": "P0", "a": "P1", "b": "P1", "c": "P2", "d": "P2"}
INIT = {"t": 100, "a": 10, "b": 20, "c": 30, "d": 40}
@dataclass(frozen=True)
class Rec:
lsn: int
kind: str # begin, update, op_commit, clr, comp_commit, abort, commit, end
txn: int
prev: int = 0 # prevLSN of the same transaction, 0 for none
page: str = ""
key: str = ""
before: int = 0
after: int = 0 # update and clr: the value written
undo_next: int = 0 # clr and comp_commit: the next record to undo
inv: tuple = () # op_commit: (key, delta) of the inverse ADD
op_prev: int = 0 # op_commit: lastLSN of the transaction before the operation
undone: int = 0 # clr: the update it undoes; comp_commit: the op_commit
def fresh_disk() -> dict:
disk: dict = {}
for k, p in sorted(PAGE_OF.items()):
disk.setdefault(p, ({}, 0))[0][k] = INIT[k]
return disk
def state(disk: dict) -> dict:
return {k: v for p in sorted(disk) for k, v in disk[p][0].items()}
class MLR:
def __init__(self, disk: dict, log: list | None = None, physical_undo: bool = False):
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] = {} # txn -> next record to undo (rollback and restart)
self.plan: dict[int, list] = {} # txn -> level 0 actions still to run
self.locks: dict[str, int] = {} # level 0 locks: key -> txn
self.physical_undo = physical_undo # the wrong method, for the tests
# ------------------------------------------------------------ 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.txn and r.kind != "end":
self.last[r.txn] = r.lsn
return r
def _page(self, p: str) -> list:
if p not in self.buf:
vals, lsn = self.disk[p]
self.buf[p] = [dict(vals), lsn]
return self.buf[p]
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) -> "MLR":
return MLR(self.disk, self.log, self.physical_undo)
def value(self, key: str) -> int:
return self._page(PAGE_OF[key])[0][key]
# ------------------------------------------------------------ level 0 actions
def _write(self, txn: int, key: str, new: int) -> None:
pg = self._page(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=new) # @line L20
pg[0][key], pg[1] = new, r.lsn
def can_act(self, txn: int) -> bool:
a = self.plan[txn][0]
return a[0] != "w" or self.locks.get(a[1], txn) == txn
def _act(self, txn: int) -> None:
"""Run the next level 0 action of the operation or compensation of txn."""
a = self.plan[txn].pop(0)
if a[0] == "w":
self.locks[a[1]] = txn # @line L19
self._write(txn, a[1], self.value(a[1]) + a[2]) # @line L20
return
for k in [k for k, t in self.locks.items() if t == txn]:
del self.locks[k] # release the level 0 locks at the end of the operation
if a[0] == "oc":
self._append(kind="op_commit", txn=txn, prev=self.last[txn],
inv=(a[1], -a[2]), op_prev=a[3]) # @line L21
else:
self._append(kind="comp_commit", txn=txn, prev=self.last[txn],
undone=a[1], undo_next=a[2]) # @line L14
self.undo_next[txn] = a[2] # @line L14
@staticmethod
def _compensation(r: Rec) -> list:
key, d = r.inv
return [("w", key, d), ("w", "t", d), ("cc", r.lsn, r.op_prev)] # @line L13
# ------------------------------------------------------------ normal processing
def begin(self, txn: int) -> None:
self._append(kind="begin", txn=txn)
self.plan[txn] = []
def add(self, txn: int, key: str, d: int) -> None:
"""Start the level 1 operation ADD(key, d); step() runs its level 0 actions."""
p = self.last[txn] # @line L19
self.plan[txn] = [("w", key, d), ("w", "t", d), ("oc", key, d, p)] # @line L19
def busy(self, txn: int) -> bool:
return bool(self.plan.get(txn))
def step(self, txn: int) -> None:
"""One level 0 action of txn, or one rollback step if txn is rolling back."""
if self.plan[txn]:
self._act(txn)
else:
self._l1_step(txn)
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])
del self.plan[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.lsn
def rolling_back(self, txn: int) -> bool:
return txn in self.undo_next
def _l1_step(self, txn: int) -> None:
"""Lines L12 to L17 for one transaction. A compensation is planned here and
its level 0 actions run in the next steps."""
r = self.rec(self.undo_next[txn]) # @line L12
if r.kind == "op_commit":
self.plan[txn] = self._compensation(r) # @line L13
elif r.kind == "comp_commit":
self.undo_next[txn] = r.undo_next # @line L15
elif r.kind == "abort":
self.undo_next[txn] = r.prev # @line L16
else: # begin
self._append(kind="end", txn=txn, prev=self.last[txn]) # @line L17
del self.undo_next[txn] # @line L17
self.plan.pop(txn, None)
self.last.pop(txn, None)
# ------------------------------------------------------------ restart
def restart(self) -> Iterator[None]:
"""Analysis, redo, the level 0 pass and the level 1 pass. Yields after each step."""
winners: set[int] = set()
self.last, self.undo_next, self.plan, self.locks = {}, {}, {}, {}
for r in self.log: # @line L1
if r.kind == "commit":
winners.add(r.txn) # @line L2
elif r.kind == "end":
winners.discard(r.txn) # @line L2
self.last.pop(r.txn, None)
self.undo_next.pop(r.txn, None)
else:
self.last[r.txn] = r.lsn # @line L3
jump = r.kind in ("clr", "comp_commit")
self.undo_next[r.txn] = r.undo_next if jump else r.lsn # @line L3
for t in sorted(winners):
self._append(kind="end", txn=t, prev=self.last[t]) # @line L4
del self.undo_next[t]
del self.last[t]
yield
for r in list(self.log): # @line L5
if r.kind in ("update", "clr"):
pg = self._page(r.page)
if pg[1] < r.lsn: # @line L6
pg[0][r.key], pg[1] = r.after, r.lsn # @line L6
yield
for t in sorted(self.undo_next, key=lambda t: -self.undo_next[t]): # @line L7
while True:
r = self.rec(self.undo_next[t])
if self.physical_undo and r.kind in ("op_commit", "abort", "comp_commit"):
# the wrong method: undo completed operations page by page
self.undo_next[t] = r.undo_next if r.kind == "comp_commit" else r.prev
continue
if r.kind not in ("update", "clr"): # @line L8
break
if r.kind == "clr":
self.undo_next[t] = r.undo_next # @line L9
continue
c = self._append(kind="clr", txn=t, prev=self.last[t], page=r.page, key=r.key,
after=r.before, undo_next=r.prev, undone=r.lsn) # @line L10
pg = self._page(r.page)
pg[0][r.key], pg[1] = r.before, c.lsn # @line L10
self.undo_next[t] = r.prev # @line L10
yield
while self.undo_next: # @line L11
t = max(self.undo_next, key=lambda t: self.undo_next[t]) # @line L12
self._l1_step(t)
yield
while self.plan.get(t): # the level 0 actions of a compensation
self._act(t) # @line L13
yield
self.flush_log() # @line L18
def recover(self) -> None:
for _ in self.restart():
pass
test_multi_level_recovery.py 233 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multi-level-recovery/. The authors are listed in prov/7Q7BG3.jsonl.
"""Crash-injection tests for two-level recovery.
A seeded generator builds a workload against a live database: transactions
run ADD operations whose level 0 actions interleave with those of other
transactions, level 0 locks are released at the end of each operation, aborts
roll back one step at a time with compensations, and page writes (steal) and
log flushes come at random places. Each test replays a prefix, crashes,
recovers and compares the counters with the oracle: the initial values plus
the deltas of the transactions whose commit record is in the stable log.
"""
import copy
import random
from collections import Counter
from multi_level_recovery import INIT, MLR, fresh_disk
KEYS = ["a", "b", "c", "d"]
PAGES = ["P0", "P1", "P2"]
def apply(db: MLR, op: tuple) -> None:
kind = op[0]
if kind == "begin":
db.begin(op[1])
elif kind == "add":
db.add(op[1], op[2], op[3])
elif kind == "step":
db.step(op[1])
elif kind == "commit":
db.commit(op[1])
elif kind == "abort":
db.abort(op[1])
elif kind == "flush":
db.flush_page(op[1])
else:
db.flush_log()
def make_workload(rng: random.Random, n_steps: int, db: MLR, first_txn: int = 1, n_txns: int = 6) -> list:
ops: list = []
status: dict[int, str] = {}
nxt = first_txn
while len(ops) < n_steps:
work: list = []
if len(status) < 3 and nxt < first_txn + n_txns:
work.append(("begin", nxt))
for t in sorted(status):
if db.busy(t):
if db.can_act(t):
work += [("step", t)] * 3
elif status[t] == "aborting":
work += [("step", t)] * 3
else:
work += [("add", t, rng.choice(KEYS), rng.randint(1, 9))] * 4
work += [("commit", t), ("abort", t)] if rng.random() < 0.5 else [("commit", t)]
if not work:
break
if rng.random() < 0.2:
op = rng.choice([("flush", p) for p in PAGES] + [("flush_log",)])
else:
op = rng.choice(work)
apply(db, op)
ops.append(op)
if op[0] == "begin":
status[op[1]] = "active"
nxt += 1
elif op[0] == "commit":
del status[op[1]]
elif op[0] == "abort":
status[op[1]] = "aborting"
elif op[0] == "step" and status[op[1]] == "aborting" and not db.rolling_back(op[1]):
del status[op[1]]
return ops
def oracle(base: dict, ops: list, log: list) -> dict:
won = {r.txn for r in log if r.kind == "commit"}
exp = dict(base)
for op in ops:
if op[0] == "add" and op[1] in won:
exp[op[2]] += op[3]
exp["t"] += op[3]
return exp
def values(db: MLR) -> dict:
return {k: db.value(k) for k in sorted(INIT)}
def check_done(db: MLR, ops: list, base: dict) -> None:
assert values(db) == oracle(base, ops, db.log)
assert not db.tail and not db.undo_next and not db.plan
ended = {r.txn for r in db.log if r.kind == "end"}
assert ended == {r.txn for r in db.log if r.txn}
twice = Counter(r.undone for r in db.log if r.kind == "comp_commit")
assert not twice or max(twice.values()) == 1
def run_prefix(ops: list, k: int, disk=None, log=None) -> MLR:
db = MLR(copy.deepcopy(disk) if disk else fresh_disk(), log)
for op in ops[:k]:
apply(db, op)
return db.crash()
def workload(seed: int, n: int = 70) -> list:
return make_workload(random.Random(seed), n, MLR(fresh_disk()))
def test_crash_at_every_step() -> None:
for seed in range(6):
ops = workload(seed)
for k in range(len(ops) + 1):
db = run_prefix(ops, k)
db.recover()
check_done(db, ops[:k], INIT)
def test_crashes_inside_recovery() -> None:
for seed in (11, 12):
ops = workload(seed, 60)
rng = random.Random(seed)
for k in range(0, len(ops) + 1, 2):
n_steps = sum(1 for _ in run_prefix(ops, k).restart())
for j in range(n_steps + 1):
db = run_prefix(ops, k)
gen = db.restart()
for _ in range(j):
next(gen)
for p in PAGES:
if rng.random() < 0.5:
db.flush_page(p)
if rng.random() < 0.5:
db.flush_log()
db = db.crash()
db.recover()
check_done(db, ops[:k], INIT)
def test_two_crashes_inside_recovery() -> None:
rng = random.Random(21)
ops = workload(21, 60)
for k in range(0, len(ops) + 1, 3):
for _ in range(4):
db = run_prefix(ops, k)
for _ in range(2):
gen = db.restart()
for _ in range(rng.randint(0, 25)):
if next(gen, "done") == "done":
break
for p in PAGES:
if rng.random() < 0.6:
db.flush_page(p)
db = db.crash()
db.recover()
check_done(db, ops[:k], INIT)
def test_second_epoch_after_recovery() -> None:
ops1 = workload(31, 50)
db = run_prefix(ops1, len(ops1))
db.recover()
for p in PAGES:
db.flush_page(p)
base = values(db)
disk, log = copy.deepcopy(db.disk), list(db.log)
ops2 = make_workload(random.Random(32), 50, MLR(copy.deepcopy(disk), log), first_txn=100)
for k in range(len(ops2) + 1):
db2 = run_prefix(ops2, k, disk, log)
db2.recover()
assert values(db2) == oracle(base, ops2[:k], db2.log)
def example_db() -> MLR:
db = MLR(fresh_disk())
db.begin(1)
db.add(1, "a", 5)
for _ in range(3):
db.step(1)
db.flush_page("P1") # steal: a = 15 reaches the disk
db.begin(2)
db.add(2, "a", 7)
for _ in range(3):
db.step(2)
db.commit(2)
db.begin(3)
db.add(3, "c", 4)
db.step(3)
db.flush_page("P2") # the WAL rule forces the log to LSN 11
return db.crash()
def test_hand_example() -> None:
db = example_db()
assert [r.kind for r in db.log] == ["begin", "update", "update", "op_commit", "begin", "update",
"update", "op_commit", "commit", "end", "begin", "update"]
db.recover()
assert values(db) == {"a": 17, "b": 20, "c": 30, "d": 40, "t": 107}
new = [(r.lsn, r.kind, r.txn, r.key, r.before, r.after) for r in db.log[12:]]
assert new == [
(13, "clr", 3, "c", 0, 30),
(14, "end", 3, "", 0, 0),
(15, "update", 1, "a", 22, 17),
(16, "update", 1, "t", 112, 107),
(17, "comp_commit", 1, "", 0, 0),
(18, "end", 1, "", 0, 0),
]
assert db.log[16].undo_next == 1 and db.log[16].undone == 4
def test_physical_undo_of_completed_operations_is_wrong() -> None:
db = example_db()
db.physical_undo = True
db.recover()
# T2 committed +7 on a, but the before images of T1 put a back to 10.
assert values(db)["a"] == 10 and values(db)["t"] == 100
def test_level0_locks_are_released_at_operation_end() -> None:
db = MLR(fresh_disk())
db.begin(1)
db.add(1, "a", 1)
db.step(1)
db.begin(2)
db.add(2, "a", 2)
assert not db.can_act(2) # T1 still runs its ADD on a
db.step(1)
db.step(1) # op_commit
assert db.can_act(2) # T1 has not committed, but its level 0 locks are gone
History
Weikum (ACM TODS 1991) described transactions as levels of operations, with locks per level and recovery by inverse operations of completed subtransactions, and measured an implementation on the Codasyl database system UDS. Lomet (SIGMOD 1992) gave MLR, a method that pairs the commit of each subtransaction with a log record for its parent, logs each compensation as a transaction with its own commit, and recovers with a level 0 pass after ARIES-style redo, then a pass at the next level. The nested top actions of ARIES (Mohan et al. 1992) give the same early release for structure changes inside one system.
References
- Gerhard Weikum, Principles and realization strategies of multilevel transaction management, ACM Transactions on Database Systems 16(1), 1991, pages 132 to 180, the model of transactions as levels of operations, the recovery by inverse operations of completed subtransactions, and the measurements on the UDS system, paper level
- David B. Lomet, MLR, a recovery method for multi-level systems, Proceedings of ACM SIGMOD 1992, ACM SIGMOD Record 21(2), pages 185 to 194, Section 2.1 (high level compensation), Section 4.3 (undoing completed subtransactions) and Section 5 (MLR rollback), with the level 0 pass and the level 1 pass of restart
- 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 sections on logical undo and nested top actions, paper level
- Gerhard Weikum and Gottfried Vossen, Transactional Information Systems, Morgan Kaufmann, 2001, the chapters on transactions with object operations and their crash recovery, chapter level only
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 7Q7BG3 Edit this page History Report an error Markdown