Lecture 17 · Atomic transactions II: write-ahead logging, RVM and concurrency control

Distributed Systems · Lecture 17。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-440/640 Spring 2026, learning outcomes “write-ahead logging”, “physical vs operation logging” and “nested transactions”; the reading Satyanarayanan et al., Lightweight Recoverable Virtual Memory. Problem set: PS3 asks for the contents of a no-undo/redo write-ahead log and the outcome of its recovery for a given schedule; PS4 asks you to judge a locking-and-logging transfer routine against ACID. This lecture teaches the concepts with different scenarios, and gives no answers. Project: P4’s nodes must log before they act and recover from their logs; no project code here. Sources:

  • M. Satyanarayanan, H. H. Mashburn, P. Kumar, D. C. Steere and J. J. Kistler, Lightweight Recoverable Virtual Memory (SOSP 1993; ACM TOCS 12(1), 1994) — the reading;
  • T. Haerder and A. Reuter, Principles of Transaction-Oriented Database Recovery (ACM Computing Surveys 1983) — steal/force;
  • C. Mohan, D. Haderle, B. Lindsay, H. Pirahesh and P. Schwarz, ARIES (ACM TODS 1992) — repeating history, compensation records, page LSNs;
  • K. P. Eswaran, J. N. Gray, R. A. Lorie and I. L. Traiger, The Notions of Consistency and Predicate Locks in a Database System (CACM 1976) — two-phase locking;
  • P. A. Bernstein, V. Hadzilacos and N. Goodman, Concurrency Control and Recovery in Database Systems (Addison-Wesley 1987);
  • J. E. B. Moss, Nested Transactions: An Approach to Reliable Distributed Computing (MIT PhD thesis 1981);
  • D. J. Rosenkrantz, R. E. Stearns and P. M. Lewis, System Level Concurrency Control for Distributed Database Systems (ACM TODS 1978) — wait-die and wound-wait;
  • J. Gray and A. Reuter, Transaction Processing: Concepts and Techniques (1993).

The slides are not public; this is not a transcript. Every number not attributed to a paper comes from code/lecture17/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9). All demos are exhaustive or seeded and deterministic, except the labelled real-file measurements in demo 05. Code: code/lecture17/. Reading time: ~110 minutes, plus ~15 to run the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain why a shared, sequential write-ahead log replaces per-transaction intentions lists, and what a buffer pool changes.
  2. Classify buffer policies as steal/no-steal and force/no-force, and say for each which log information (undo, redo, both) recovery needs.
  3. State the WAL rule and the commit rule, and show what breaks without each.
  4. Run a recovery by hand: analysis, redo (repeating history), undo with compensation log records. Explain why the order of passes matters and why recovery must be idempotent.
  5. Explain how checkpoints bound recovery and let the log be truncated, and what pins the log start.
  6. Compare physical (value) and operation (logical) logging, and explain page LSNs and physiological logging.
  7. Describe RVM’s design, and why each of its omissions makes it simpler: what it leaves out, set_range, no-restore and no-flush transactions, value logging, truncation, its two optimizations.
  8. Decide whether a schedule is conflict-serializable, and explain two-phase locking, its strict variants, deadlock handling and nested transactions.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 16: ACID, commit points, intentions lists, the toy disk and crash-point analysis;
    • Lecture 15: durable writes (fsync vs F_FULLFSYNC) and the output-commit rule;
    • Lecture 4: idempotence.
  • Scope: transactions on one machine. Here, “isolation” means concurrency control within that machine. Transactions spanning machines (two-phase commit) are Lecture 18; replication is Lectures 19–21.

0.3 Section → code map

SectionIdeaDemo in code/lecture17/
§1–2the log; buffer policies; WAL and commit rules01_wal_rule.py
§3recovery: analysis, redo, undo, CLRs02_recovery.py
§4checkpoints and truncation03_checkpoints.py
§5physical vs operation logging04_physical_vs_logical.py
§6RVM (the reading)05_rvm.py, rvm.py
§7serializability06_serializability.py
§8two-phase locking, deadlock07_two_phase_locking.py
§9nested transactions08_nested_transactions.py

0.4 Notation and the toy world

  • The store (wal.py): four keys A, B, C, D of 100 units, one per home block, on Lecture 16’s toy disk. Each home block holds a value and a page LSN. A volatile buffer pool holds working copies; a volatile log buffer holds records not yet written.
  • Log records are written [LSN] Tn KIND …:
    • UPD A: 100 -> 70 is an update with its before and after values;
    • CLR A = 100 is a compensation (an undo, logged);
    • COMMIT and ABORT are outcomes;
    • CKPT is a checkpoint.
  • The standard script (wal.SCRIPT): T1 moves 30 from A to B and commits; T2 starts moving 50 from C to D and aborts; T3 moves 20 from A to C and commits; T4 subtracts 10 from B and is still running at the end. At three points the buffer manager writes a page home (C, A, B).
  • Crash-point analysis is exhaustive (Lecture 16 §7): a crash after every write, optionally with writes reordered between flushes, and recovery itself crashed at every one of its writes.

1. From intentions lists to a log

1.1 What Lecture 16 left unsolved

Lecture 16’s intentions list was correct, but it had three costs.

  1. One transaction at a time. The list lived in a fixed place on disk, and a new transaction could start only once the previous one had been applied and marked done.
  2. Two synchronous writes per change. Every change was written once to the list and once to its home block before the transaction finished.
  3. Home blocks updated eagerly. The commit path waited for the database itself to be updated.

A database serving thousands of transactions a second cannot pay that. It wants:

  • many transactions in flight at once;
  • one cheap, sequential disk write on the commit path;
  • home pages written later, in big batches, whenever convenient.

1.2 The idea: one log for everyone

A write-ahead log (WAL) is a single append-only file shared by all transactions. Every change is described by a log record appended at the log’s tail. A buffer pool in memory holds copies of the pages being read and written. Pages are written back to their home locations (“cleaned”) whenever the buffer manager needs the space or has spare disk bandwidth. That is not necessarily at commit.

Three properties make this fast:

  • Appends are sequential. On a spinning disk a sequential write avoids seeks. On an SSD it avoids small random writes, which cause write amplification inside the drive.
  • Commits are batched. Many transactions’ commit records can be forced with one flush (group commit).
  • Hot pages are written rarely. A page updated by a thousand transactions is written home once, not a thousand times.

The price is that, at a crash, the disk holds an arbitrary mixture: some pages with changes from transactions that never committed, others missing changes from transactions that did. The log must contain enough to sort this out. What “enough” means depends on the buffer manager’s freedom.


2. The WAL rule and the four buffer policies

2.1 Two questions the buffer manager asks

Haerder and Reuter named the two decisions:

  • Steal: may a page dirtied by an uncommitted transaction be written home (to free its frame)? If yes, a crash can leave uncommitted data on disk, and recovery must be able to undo it.
  • Force: must all pages a transaction dirtied be written home before it commits? If not (“no-force”), a crash can lose committed data that was only in memory, and recovery must be able to redo it.
no-force (redo needed)force (no redo)
steal (undo needed)undo/redo: log before + after values. Almost all databases (ARIES)undo-only: log before values; write pages before COMMIT
no-steal (no undo)redo-only (“no-undo/redo”): log after values. Intentions lists, RVMno-undo/no-redo: needs an atomic multi-page write, which disks do not provide

2.2 The two rules

Two ordering rules make undo and redo possible.

  1. The WAL rule (protects undo). A page may be written home only after every log record describing its changes is on disk. Otherwise a crash can leave an uncommitted change on disk with no before value anywhere.
  2. The commit rule (protects redo). A transaction is committed, and may be acknowledged, only after all its log records, its COMMIT record included, are on disk. Otherwise an acknowledged transaction can vanish.

Both rules say “log first”, which is where “write-ahead” comes from. Both are flush ordering rules in Lecture 16’s sense: a barrier separates the log write from what depends on it.

2.3 Watching it happen (demo 01, Part A)

Under undo/redo (steal, no-force), the standard script reaches the disk like this (abridged):

T1: A -30, B +30         (log buffer gets [1] UPD A: 100 -> 70, [2] UPD B: 100 -> 130)
T2: C -50                (log buffer gets [3] UPD C: 100 -> 50)
write C home             log [1] [2] [3]; flush; HOME C = 50      <- WAL rule, then a STOLEN page
T1 commits               log [4] T1 COMMIT; flush -> ack           <- commit rule
write A home             HOME A = 70                              <- [1] is already durable
T2 aborts                (log buffer gets [6] CLR D = 100, [7] CLR C = 100, [8] ABORT)
T3: C +20, A -20; commits  log [5]..[11]; flush -> ack
T4: B -10; write B home  log [12]; flush; HOME B = 120            <- another stolen page

Two moments matter:

  • The C write. The buffer manager writes T2’s uncommitted C = 50 home. Before it does, the log is flushed so that [3] UPD C: 100 -> 50, the before value, is on disk.
  • T1’s commit. Only one log block is written and one flush made. A and B stay in memory.

2.4 The four policies, every crash point (demo 01, Part B)

policylog recordspage writescommit path (log blocks / home blocks / flushes)violations, in orderreordered
undo/redo1234.0 / 0 / 1.00 / 870 / 1,345
redo-only613.0 / 0 / 1.00 / 320 / 78
undo-only1082.5 / 2.0 / 2.50 / 530 / 105
no-log (force, in place)060 / 2.0 / 1.02 / 94 / 13

All three logged policies survive every crash state. The difference is cost and freedom:

  • Undo/redo puts only sequential log writes on the commit path, and lets the buffer manager write any page at any time.
  • Undo-only must write every dirtied page home before the COMMIT record: 2 home blocks and 2.5 flushes per commit in this script, and in a real system random writes on the critical path.
  • Redo-only wrote the least. No-steal kept uncommitted pages in memory, and its records go to the log only at commit, one per key: RVM’s design (§6). Its price is memory: every page an active transaction touched must stay in the buffer until it commits. A transaction touching more pages than fit in memory cannot run at all.

2.5 Breaking one rule at a time (demo 01, Part C)

what is wrongin orderreorderedfirst violation
steal, but the log has no before values22 / 3863 / 97A=100 B=100 C=50 D=100: T2’s uncommitted −50 stuck on disk
no-force, but the log has no after values27 / 40194 / 216an acknowledged commit lost
WAL rule broken (page home before its record)8 / 7728 / 1,370C=50 stuck on disk with no before value
commit returns before COMMIT is flushed50 / 8610,200 / 10,279an acknowledged commit lost

The last row is not always a bug. RVM offers exactly this as a no-flush commit (§6.3): faster commits, in exchange for bounded persistence. The bug is to do it without telling the application.

2.6 Why most systems choose steal/no-force

  • No-force keeps random home-page writes off the commit path. One sequential log flush replaces several random page writes, and group commit shares that flush among many transactions.
  • Steal frees the buffer manager. A long transaction can touch more pages than memory holds, and memory can be reclaimed at any time.

Recovery is then the most complex of the four, which is the subject of §3. RVM chose no-steal/no-force deliberately: its regions are meant to fit comfortably in memory, so no-steal costs it little, and recovery becomes redo-only.


3. Recovery

3.1 The analysis pass: winners, aborted, losers

After a crash, recovery reads the log from its start (§4) to its tail and sorts transactions:

  • winners: a COMMIT record is on disk;
  • aborted: an ABORT record is on disk (their undo was already done and logged);
  • losers: neither. They were running at the crash and must be rolled back.

In demo 02 Part A the crash comes at the end of the script. The disk holds:

  • A = 70: T1’s value, already home;
  • B = 120: T4’s uncommitted value, stolen;
  • C = 50: T2’s aborted value, stolen before the abort;
  • D = 100: never written.

The durable log holds records 1–12. Analysis finds winners T1 and T3, aborted T2, and loser T4.

3.2 Redo: repeating history

The redo pass goes forward through the log and re-applies every logged change: winners’, losers’ and aborted transactions’ updates, and the compensations. This is ARIES’s repeating history: after the redo pass the pages are exactly as they were in memory at the crash, whatever the buffer manager had or had not written.

Why redo the losers’ changes too, only to undo them a moment later? It keeps the passes simple and independent of what was on disk:

  • after redo, the state is known exactly (“as at the crash”);
  • undo then rolls back the losers from that known state, in reverse order, exactly as a normal abort would have done.

3.3 Undo and compensation log records

The undo pass walks backwards through the losers’ updates and restores before values. When a transaction aborts during normal operation, it does the same thing, and it logs each undo step as a compensation log record (CLR), here CLR C = 100, before logging ABORT.

A CLR is a redo-only record: it describes a change (the restoration) that recovery may need to redo, and it is never undone. Logging compensations has three benefits:

  • Aborts become ordinary history. An aborted transaction’s updates and their reversal are both in the log, and repeating history replays both.
  • A crash during an abort is easy. The CLRs written so far are redone; recovery then finishes undoing the remaining updates.
  • Undo work is bounded. In ARIES each CLR points to the next record to undo, so recovery never undoes the same update twice. Our toy store re-undoes from before values instead, which is safe because they are absolute.

Demo 02’s recovery of the end-of-script crash takes ten steps. Nine are redo steps (T1’s, T2’s with its two CLRs, T3’s, T4’s); the tenth undoes T4: B := 130. The result is A=50 B=130 C=120 D=100, the state after T1 and T3, as it should be.

3.4 The order of passes matters (demo 02, Part B)

algorithmwhat it doesviolations, in orderreordered
repeat-historyredo every change (CLRs too), then undo losers0 / 870 / 1,345
undo-then-redoundo every non-winner backwards, then redo winners0 / 680 / 1,199
redo-winners-then-undo-restredo winners, then undo every non-winner backwards20 / 6830 / 1,199

The third looks natural: “make the winners’ changes happen, make everyone else’s not happen”. It is wrong. T2 had aborted, so C was restored to 100; later T3 committed C = 120. The buggy algorithm redoes T3 (C := 120) and then undoes T2’s update (C := 100), destroying a committed change.

The underlying rule: undoing a change is correct only if no later committed change to the same item has already been redone. Two orders respect it:

  • repeating history and then undoing only true losers. A loser’s change cannot be followed by another transaction’s change to the same item, because the loser held its lock until the crash (§8);
  • undoing everything first and redoing winners afterwards.

3.5 Idempotence and crashes during recovery

Recovery can crash too, and then it runs again on whatever it left behind. Our store makes this safe in two ways (demo 02 Part C):

  • Absolute values. It computes final page images from the log and writes them. Writing the same image twice is harmless.
  • One atomic step at the end. Only after the pages are flushed does it empty the log, with one atomic write of the MASTER block that starts a new log generation. A crash anywhere before that leaves the old log in place.

Crashing recovery at every one of its writes added 69 in-order crash states, all correct. Running recovery three times in a row left identical balances in all 18 crash states. Real systems also log during recovery (CLRs for the undo pass) so that a second recovery does not repeat work. The principle is the same: recovery must be restartable from any point.

3.6 How much work is recovery?

Averaged over the in-order crash states of the script (demo 02 Part D):

policylog records readredo stepsundo stepshome blocks rewritten
undo/redo6.2 (max 12)4.91.32.9
redo-only3.3 (max 6)1.801.3
undo-only5.3 (max 10)01.50.6

The work tracks the policy. In a real database the dominant cost is the length of log to read, which is what checkpoints control.


4. Checkpoints and log truncation

4.1 Two reasons to checkpoint

Without help, the log grows forever and recovery reads all of it. A checkpoint serves two purposes:

  1. Bound recovery time: recovery starts at a recent point instead of the beginning of time.
  2. Reclaim log space: records older than that point can be discarded (truncation), so a fixed-size, circular log suffices.

4.2 How far may the log start move?

The start may move past a record only when recovery can no longer need it. Recovery needs a record in two cases:

  • it may have to redo it: its change is not yet on the home page;
  • it may have to undo it: its transaction is still active (under steal).

So the earliest LSN that must be kept is the minimum of:

  • the CKPT record itself;
  • the first record of every active transaction, if undo is logged;
  • the oldest unwritten change of every dirty page, its recovery LSN (ARIES’s recLSN).

Demo 03 Part A shows the rule at work on a script that checkpoints while T2 and T4 are active:

policyCKPT at LSNstart may move toheld back by
undo/redo84T2’s first record [4]; T4’s first record [7]
redo-only61A’s oldest unwritten change [1], on a page held by T4
undo-only84T2’s and T4’s first records

Truncating at the CKPT record instead broke 47 (undo/redo), 70 (redo-only) and 29 (undo-only) crash states. The redo-only row is instructive. T4 holds page A, so no-steal forbids writing it, but A also carries the committed changes of T1 and T3. Their redo records must stay.

4.3 Sharp vs fuzzy checkpoints

  • A sharp checkpoint writes every dirty page it is allowed to, then logs CKPT. Recovery after it is short, but the checkpoint itself is a burst of random writes.
  • A fuzzy checkpoint writes no pages. It logs CKPT along with the list of active transactions and dirty pages, and relies on a background cleaner that continually writes old dirty pages so that recovery LSNs advance.

Over 3,000 transactions on a 400-block circular log (demo 03 Part B):

checkpointkindlog to read at a crash (mean / max)page writes (all)page writes in checkpointslog full?
never–197 / 3961,768268 (emergency)22 times
every 200 commitssharp166 / 3961,84135515 times
every 50sharp74 / 1482,193693no
every 50fuzzy141 / 2321,5000no
every 10sharp14 / 284,0522,552no
every 2sharp2 / 45,6074,107no

The trade-off is plain:

  • Frequent sharp checkpoints make recovery nearly instant, but multiply page writes.
  • Fuzzy checkpoints cost almost nothing at checkpoint time and still bound the log, because the cleaner does the work that moves the start.

When the log does fill up, the store must abort a transaction and checkpoint. Aborting writes CLRs, so the store must have reserved log space for them. Our first version did not, and a full log could not even abort (see the code README’s “Plan vs reality”).

4.4 Long transactions pin the log

One transaction left open from commit 500 to 2,500 (demo 03 Part C), with a sharp checkpoint every 50 commits:

policymean log to readmaxlog full?
undo/redo80394at commit 630; the long transaction aborted
redo-only80399at commit 626; the long transaction aborted
redo-only + epoch truncation74148no

Under undo/redo, the long transaction’s first record pins the start: nothing after it can be truncated while it might need undoing.

Under redo-only, we expected immunity, since it logs nothing before commit. It was not immune. No-steal kept its page in memory, and that page carried older committed changes whose redo records could not be discarded until the page went home. This is precisely what the RVM paper describes for its incremental truncation: a page with an uncommitted reference count above zero blocks the log head. RVM’s escape is epoch truncation, which applies the committed records in the log to the data segment instead of writing pages from memory (§6.4). Our store’s equivalent, writing the committed version of the held page, kept the log short.

The general lesson for any logging system: long-running transactions are expensive in log space, not just in locks. Databases bound their lifetime or abort them when the log fills.


5. Physical vs operation logging

5.1 Value (physical) logging

A value record carries bytes: the before image, the after image, or both, of the bytes that changed. Its virtues:

  • Idempotent: applying “these bytes are now X” twice is harmless.
  • Page-agnostic: it can be applied to any version of the page, even a torn or stale one.

Its vice is size. An update that moves data moves a lot of bytes.

5.2 Operation (logical) logging

An operation record carries the operation: “add 1 to counter k”, “insert record r”, “reorganize page p”. It is small, but it is not idempotent. Applying “add 30” twice adds 60. It must be applied exactly once, to a page in the state it expects.

The standard fix is the page LSN. Every page stores the LSN of the last logged change it reflects. Redo applies record n to page p only if p.lsn < n, and stamps p.lsn = n when it does. A page that already reflects the change is skipped.

Demo 04 Part A measured real 4 KB page images (a 64-byte header plus 40-byte records). A record is priced at a 16-byte header plus the bytes it carries:

updatevalue record, undo + redo (bytes)redo-only valueoperation recordratio
increment one record’s counter3634281×
insert a record mid-page (sorted)2,1121,3925638×
delete the first record4,0642,68024169×
rewrite every payload in the page4,0182,65720201×
split a full page (3 pages change)8,1044,10064127×

On the toy store (demo 04 Part B), operation records with a page-LSN check were as safe as value records (0 violations). Without the check, 26 of 35 in-order crash states applied an operation twice.

5.3 Operations that span pages, and physiological logging

The page split in the table is tempting: one 64-byte record instead of 8 KB. But a single logical record whose operation changes several pages cannot be guarded by one page’s LSN. Demo 04 Part C transfers 30 from X (page P) to Y (page Q), logged as one record transfer(X, Y, 30). The page holding Y happens to reach the disk first. Whichever test guards the redo fails:

  • Check P’s LSN only. Q already has the credit, P does not, so the transfer is redone and Y is credited twice (X=70, Y=160): 4 states.
  • Check that both pages are older. Q is newer, so the transfer is skipped and X is never debited (X=100, Y=130): 6 states.
  • Either test, P alone on disk. If P reaches the disk alone (reordered, or recovery crashed between the pages), Y goes unpaid (X=70, Y=100): 7 states each.

The fix is physiological logging: physical to a page, logical within it. Each record names one page and an operation on that page (“in page P: X −= 30”; “in page Q: Y += 30”), and each is guarded by its own page’s LSN. That gave 0 violations. ARIES uses exactly this: records are page-oriented for redo, so each can be checked against its page, but compact, like operations.

5.4 The trade-off, summarized

value (physical)operation (logical)physiological
log volumelarge when updates move datasmallestsmall
idempotent?yesno — needs page LSNswith page LSNs
replay needsnothingthe page in the expected state (action consistency)each page in a consistent state
multi-page operationsfine, one record per rangeunsafe as one recordsplit per page
who uses itRVM, intentions lists, many file system journalslogical undo in ARIES (e.g. B-tree inserts that may have moved)ARIES redo, most databases

6. RVM: Lightweight Recoverable Virtual Memory (the reading)

6.1 Background: Camelot and Coda

Coda (Lecture 22) keeps its server meta-data (directories, replica-control state) in data structures that must survive crashes atomically. The Coda group first used Camelot, CMU’s general-purpose transaction facility on Mach. Camelot offered nested and distributed transactions and many choices of logging and commit protocol. Coda used only one feature: recoverable virtual memory, regions of a process’s address space with transactional guarantees. That one feature turned out to be a convenient abstraction:

  • crash recovery restored the data structures in place;
  • directory operations became plain in-memory manipulations;
  • Coda’s own salvager stayed small.

The costs, per the paper, were three:

  • Scalability. Controlled experiments showed Coda servers less scalable than AFS. Server CPU utilization was the main cause, and Camelot accounted for more than a third of its increase. Each Camelot operation involved several Mach tasks, which meant paging and context switches.
  • Programming constraints. All processes had to descend from Camelot’s Disk Manager task, which made starting and debugging servers awkward. Camelot also required Mach kernel threads, which cost far more than Coda’s user-level threads.
  • Maintenance. Camelot was large and depended on rarely used combinations of Mach features. Coda often hit bugs first, and it was hard to tell whether they lay in Camelot or in Mach.

6.2 Design rationale: value simplicity over generality

The paper’s central principle is to “value simplicity over generality”, following Lampson’s advice on interface design. RVM keeps exactly two properties, atomicity and permanence against process failure. It factors everything else out to layers above or below:

left outwhere it goes instead
nested transactionsa layer above RVM (the paper sketches one; §9)
distributed transactionsa layer above (a coordinator running two-phase commit; Lecture 18)
concurrency control (serializability)the application, at the granularity it wants
media-failure resiliencebelow: a mirrored disk in the device driver

Two structural decisions follow.

  • A library, not a set of processes. RVM is linked into the application; no IPC is involved. On the paper’s hardware a Mach IPC cost about 600 local procedure calls. The price is trust: the application and RVM can damage each other’s data structures. Another price is that applications cannot share one log on a dedicated disk. Each process has its own log, in a file (forced with fsync) or a raw partition.
  • No integration with the virtual-memory system. Camelot acted as an external pager so that dirty recoverable pages were not paged out before commit. RVM instead copies a region from its external data segment (a file or partition) into ordinary memory when it is mapped. The swap space is separate from the data segment, so a page-out of uncommitted data does no harm to recovery. This trades resources for simplicity: disk space is duplicated, startup reads regions in whole, and regions must fit in memory. All are acceptable because RVM targets meta-data, a small fraction of disk with a working set that fits in memory.

6.3 The interface

callmeaning
map(region) / unmapcopy a region of a segment into memory; it starts as the last committed image
begin_transaction(tid, restore_mode)start; no-restore promises never to abort, so RVM keeps no old values
set_range(tid, addr, n)“I am about to modify these bytes” — RVM records the old value (unless no-restore)
end_transaction(tid, commit_mode)commit; no-flush commits without forcing the log
abort_transaction(tid)restore the old values
flush()force all committed no-flush transactions to the log
truncate()apply committed changes in the log to the data segments

Reads need no RVM call at all, and neither do writes: the application writes to memory directly. That is the whole point, and also the main hazard. RVM cannot see a store instruction. If the application forgets set_range, the change is committed in memory, never logged, and lost at the next crash. The paper names this the most common programming problem, and calls its result disastrous. In demo 05 Part A that is exactly what happened: the set_range-less field was gone after the restart.

No-flush and bounded persistence. A no-flush commit is atomic but not yet permanent. If the application calls flush() regularly, a crash loses at most the transactions since the last flush. On our machine (demo 05 Part D, real):

commit modetime per commit
flush each commit, fsync()~25 µs (not durable on macOS; Lecture 15 §2.4)
flush each commit, F_FULLFSYNC~3.6–3.7 ms
no-flush, flush() every 10 (F_FULLFSYNC)~330 µs
no-flush, flush() every 100~31 µs

Killing a real process that committed counter increments (Part E, 10 kills per mode): flush-each-commit lost no acknowledged commit; no-flush with a flush every 25 lost up to 23. That is bounded persistence: at most one flush interval, not none. The paper’s own measurements are in the same spirit. On its disks a log force took about 17.4 ms, which capped fully permanent transactions at about 57 per second.

6.4 Implementation: a no-undo/redo value log

RVM uses no-undo/redo value logging. That is the redo-only policy of §2: uncommitted changes are never reflected in the external data segment, so nothing on disk ever needs undoing.

  • Old values from set_range are kept in memory, only for aborts.
  • At commit, RVM writes one new-value record per modified range, however many times the range was updated, followed by a commit mark.
  • Recovery reads the log, builds the latest committed value of each modified range, applies them to the data segments, and only then marks the log empty. Delaying that last step is what makes recovery idempotent: a crash anywhere before it just repeats the work.
  • Truncation reclaims log space by applying committed changes to the segments. The authors report it was the hardest part of RVM to implement correctly. They first reused the recovery code on the oldest part of the log while new records went to the rest (epoch truncation). That is correct, but bursty, and it increases log traffic.
  • They were building incremental truncation, which writes the oldest pages out from memory. Each page carries a dirty bit and an uncommitted reference count, and a page still referenced by an uncommitted transaction cannot be written. When long transactions block it, RVM falls back to epoch truncation: §4.4’s finding, from the other side.

Our miniature (rvm.py) protects each record with a CRC-32 and an end mark. Demo 05 Part B shows why the length fields are not enough. A torn last record whose tail sectors still held old bytes was accepted as valid in 5 of 7 cases when recovery trusted only the length fields, and garbage was applied. With the CRC, 0.

6.5 Two optimizations

  • Intra-transaction: duplicate, overlapping and adjacent set_range calls within one transaction are coalesced. Modular, defensive code produces many: a routine and its callee both declare the same header, “just in case”. A duplicate set_range is harmless; a missing one is a disaster.
  • Inter-transaction: among no-flush transactions not yet flushed, a newer one whose ranges include all of an older one’s makes the older record redundant. The paper’s example is copying files into a directory: every file creation updates the directory, and only the last update needs to reach the log.

The paper’s measurements (its Table 2, four days of Coda use):

machinesintra-transaction savingsinter-transaction savingstotal
servers≈ 21%0 (servers flush every commit)≈ 21%
clients17–42%21–64%48–82%

Our toy directory workload (demo 05 Part C, 2,000 updates):

workloadintrainter (more)total
every commit flushes24.6%0%24.6%
no-flush, flush every 30, each update to a different entry24.6%0%24.6%
no-flush, flush every 30, whole directory declared (“cp d1/* d2”)4.3%92.5%96.8%

The inter-transaction optimization helps only when later transactions rewrite what earlier ones wrote. The final memory was identical with and without either optimization.

6.6 What the evaluation showed

The authors compared RVM against Camelot on a TPC-A-like benchmark, with all data in recoverable memory. Paraphrasing their findings:

  • Throughput. With sequential account access, RVM and Camelot were nearly identical, close to the log-force limit. With random access, RVM degraded once recoverable memory exceeded roughly 70% of physical memory, the cost of not integrating with VM. Even at 175% of physical memory, RVM still beat Camelot.
  • Locality. With good locality, an application can use up to about 40% of physical memory for active recoverable data with under 10% throughput loss; with poor locality, under about 25%.
  • CPU. RVM needed about half of Camelot’s CPU per transaction. The authors attribute this mostly to being a library rather than tasks talking over IPC.
  • Code size. About 10,000 lines of mainline C against Camelot’s 60,000 (plus Mach features Camelot relied on).

6.7 Lessons

  1. Minimalism pays when the abstraction is the right one. RVM gives up nesting, distribution and flexible logging. In return it gets portability, a small code base, and better performance over its intended range.
  2. Let applications buy only the guarantees they need. No-restore and no-flush are knobs, not hacks.
  3. Layering works. Nesting (§9) and distribution (Lecture 18) can be built on top, because the base offers clean local failure semantics.
  4. The log is also a debugging tool. Saving the log before truncation gave Coda’s developers a history of every modification to corrupted data structures.

7. Isolation: serializability

7.1 What concurrency breaks

Transactions run concurrently for throughput. Without control, their interleaving produces classic anomalies:

  • lost update: two read-modify-writes of the same item, each writing over the other’s result;
  • dirty read: reading a value written by a transaction that has not committed (and may abort);
  • unrepeatable read: reading the same item twice and getting different values, because someone committed in between;
  • read skew (inconsistent analysis): reading one item before and another after a concurrent transaction’s changes, seeing a state that never existed.

Demo 06 Part A interleaves two deposits (+10 and +20) to x = 100. Of the 6 orders of their reads and writes, 2 give 130 and 4 lose a deposit. Part B runs a transfer (30 from a to b) against an audit (a + b). Every one of the 10 serializable orders shows the auditor 200; the 5 others show 170 or 230.

7.2 Schedules and conflicts

A schedule is an interleaving of the operations of several transactions that preserves each transaction’s own order. Two operations conflict if they:

  • belong to different transactions;
  • touch the same item;
  • include at least one write.

Swapping two adjacent non-conflicting operations cannot change any read’s result or the final state. Two schedules are conflict-equivalent if one can be turned into the other by such swaps. A schedule is conflict-serializable if it is conflict-equivalent to some serial schedule: one transaction at a time, in some order.

Why serial is the reference: if every transaction, run alone, preserves the application’s invariants (consistency), any serial order preserves them. A schedule equivalent to a serial one inherits that guarantee without anyone knowing what the invariants are.

7.3 The precedence-graph test

Draw a node per committed transaction, and an edge Ti → Tj whenever an operation of Ti precedes a conflicting operation of Tj. The schedule is conflict-serializable iff the graph has no cycle. Any topological order of the graph is then an equivalent serial order.

Demo 06 Part C takes R1(a) W1(a) R1(b) R2(a) R2(b) C2 W1(b) C1:

  • W1(a) before R2(a) gives T1 → T2;
  • R2(b) before W1(b) gives T2 → T1.

The cycle means T2 saw T1’s new a but old b: no serial order matches. The test is one graph search, cheap enough for a scheduler.

7.4 View serializability, and why systems do not use it

View serializability is weaker. It requires that every read sees the same write as in some serial schedule, and that the final write of each item is the same. It admits more schedules: with blind writes (writes without a prior read), demo 06 Part D found 10 of 12 orders view-serializable but only 6 conflict-serializable.

Two reasons keep it out of practice:

  • Testing it is NP-complete (Papadimitriou 1979).
  • A scheduler would need to see the future. Whether an early write matters depends on later blind writes.

Conflict serializability is what locking and most other schedulers enforce.

7.5 Recoverability and cascading aborts

Serializability is about committed transactions. It says nothing about reading data that may still be aborted. In demo 06 Part E, three transactions (transfer, audit, deposit) produced 9,240 interleavings, commits included, of which 42.3% were conflict-serializable:

anomalyschedulesshareof which conflict-serializable
dirty read6,36768.9%2,995
lost update3,96042.9%0
read skew2,45426.6%0

Lost updates and read skew never occur in a serializable schedule; dirty reads often do. If the writer later aborts, every transaction that read its data must abort too: a cascading abort. If a reader has already committed, the schedule is unrecoverable. The committed transaction depended on data that never existed, and atomicity can no longer be honoured. Schedules that read only committed data are cascadeless. Strict two-phase locking (§8.3) produces only those.


8. Two-phase locking and deadlock

8.1 Locks

A shared (S) lock allows reading; an exclusive (X) lock allows writing. S is compatible with S; X is compatible with nothing. A transaction holding S may upgrade to X if it is the only holder.

8.2 The two-phase rule

Two-phase locking (2PL) (Eswaran, Gray, Lorie and Traiger 1976) has one rule: a transaction never acquires a lock after it has released one. Its life has a growing phase (acquiring) and a shrinking phase (releasing). The moment between is its lock point.

Why this guarantees conflict serializability, intuitively:

  • Suppose Ti → Tj in the precedence graph. They had conflicting operations on some item, Ti’s first. So Ti released that item’s lock before Tj acquired it.
  • Ti had therefore reached its lock point before Tj reached its own.
  • So every edge goes from an earlier lock point to a later one, and a cycle would need a lock point earlier than itself.

The lock points give the serial order.

Demo 07 Part A explored every schedule each protocol can produce, scheduling the commits too:

workloadprotocolschedulesnot serializabledeadlocksread uncommitted data
two deposits to xnone201206
2PL8026
strict2020
transfer + auditnone5616023
2PL20003
strict17000
opposite transfersnone2522400226
2PL1201410
strict20140

Every locking protocol admitted zero non-serializable schedules. The price is visible in the other columns: fewer schedules allowed (less concurrency) and deadlocks.

8.3 Strict and strong strict 2PL

Basic 2PL lets a transaction release a write lock once it has passed its lock point, before it commits. Others may then read its uncommitted writes: 19 such schedules in the table. If it then aborts, they must too.

  • Strict 2PL holds every exclusive lock until commit or abort. Every schedule is then cascadeless and recoverable.
  • Strong strict 2PL (rigorous) holds all locks until the end. It is what most systems implement, and it makes the commit order a valid serial order.

With a transfer that aborts at the end (demo 07 Part B), the audit had read the doomed writes in:

  • 23 schedules with no locks, 12 of them unrecoverable (the audit had already committed);
  • 3 schedules with basic 2PL, 1 unrecoverable;
  • 0 with strict 2PL.

8.4 Deadlock

Locking transactions can wait for each other in a cycle. In demo 07 Part C, two opposite transfers deadlock after R1(a) W1(a) R2(b) W2(b): T1 wants b, held by T2; T2 wants a, held by T1. A subtler kind needs only one item. Two deposits that both read x hold S(x), and both need X(x) to write. Of the 14 deadlocks of the opposite transfers, 8 are such upgrade deadlocks. That is why systems let read-modify-write code take an update or exclusive lock up front (SELECT … FOR UPDATE).

The policies for dealing with deadlock:

policyideaproperty
detectionbuild the wait-for graph; on a cycle, abort a victim (e.g. the youngest)aborts only real deadlocks; needs the graph
timeoutabort a transaction that waited too longsimple; aborts some non-deadlocked waiters, and detects slowly
wait-diean older requester waits; a younger requester aborts (“dies”)no cycles: waits go only from old to young
wound-waitan older requester aborts (“wounds”) younger holders; a younger one waitsno cycles: waits go only from young to old
no-waitabort immediately on any conflictno waiting at all; many aborts

Wait-die and wound-wait (Rosenkrantz, Stearns and Lewis 1978) use transaction timestamps. An aborted transaction restarts with its original timestamp, so it eventually becomes the oldest and cannot starve.

8.5 Under load (demo 07 Part D)

Eight workers ran transactions of 4 random items (half writes) for 20,000 steps, one operation per step, under strong strict 2PL:

itemsdetecttimeoutwait-diewound-waitno-waitone global lock
200 (cold)1,4571,4531,3571,4071,317242
20 (warm)472359560490508242
8 (red hot)169100269228257242

Commits per 1,000 steps. Three lessons:

  • When conflicts are rare, the policy barely matters, and fine-grained locking beats a single global lock six-fold.
  • When conflicts are common, aborts eat the work. At 8 items, 44–56% of all executed operations belonged to aborted attempts. The global lock, which never aborts, is as good as the best policy. Locking cannot create concurrency the workload does not have.
  • Timeouts are worst under contention. They wait out the whole timeout before discovering a deadlock.

8.6 A lock manager must queue (demo 07 Part E)

Our first simulation let a newcomer take a free lock even when an older transaction was already waiting for it. Under deadlock detection it livelocked:

  • 454 commits in the first 1,000 steps;
  • then almost none: 565 in 20,000.

An old transaction holding three locks kept losing the fourth to newcomers. Each newcomer then needed one of the old transaction’s locks, formed a cycle, and was aborted as the youngest, forever. With a FIFO wait queue per item, which is what real lock managers keep, the same run committed 9,430. Fairness is part of correctness once you depend on “eventually”.

8.7 Beyond the basics

  • Granularity: locking a whole table is cheap but serializes; locking rows allows concurrency but costs memory and lock calls. Hierarchical (multi-granularity) locking with intention locks (IS, IX) lets both coexist.
  • Phantoms: locking the rows that exist does not stop another transaction from inserting a row that would have matched a query. Predicate or range (next-key) locks close that gap.
  • Optimistic concurrency control (Kung and Robinson 1981): run without locks, then validate at commit that nothing read was overwritten; abort if it was. Good when conflicts are rare, wasteful when they are not.
  • Multiversion concurrency control and snapshot isolation: readers see a consistent snapshot and never block writers. Snapshot isolation is not serializable; it permits write skew, where two transactions each read both items and each update a different one. Serializable snapshot isolation adds checks to forbid it.

9. Nested transactions

9.1 Why nest

A trip is a flight plus a hotel. If the first flight is full, the program should try another flight, without abandoning the hotel reservation or the whole trip. Flat transactions offer only all-or-nothing for the entire trip. Nested transactions (Moss 1981) let a transaction contain subtransactions that can fail independently, and that may run concurrently with their siblings.

9.2 The rules

  1. A subtransaction’s abort is real. Its effects vanish; its parent continues and may try something else.
  2. A subtransaction’s commit is relative. Its effects pass to its parent: its undo information, its locks, its changes. They become permanent only when the top-level transaction commits. If any ancestor aborts, they are undone.
  3. Locks are inherited and retained. At a child’s commit, its parent retains the child’s locks. A transaction may acquire a lock only if every holder or retainer is itself or one of its ancestors. So a sibling may use what its committed sibling locked, but an outsider must wait until the top level ends.
  4. Durability belongs to the top level alone. Only the top-level commit needs to reach stable storage.

9.3 Built on RVM (demo 08)

The RVM paper proposes building nesting as a layer above RVM, with RVM handling only top-level begin, commit and abort, and notes that the Venari project did so. Demo 08 does exactly that:

  • the layer keeps an undo list per (sub)transaction and implements Moss’s lock rule;
  • the top-level commit is one RVM transaction (no-restore, since the layer handles undo) that declares every range the tree modified.

The results:

  • Part A. The full-flight subtransaction aborted and the trip continued. After a crash and restart, the booking was there, committed with a single log force.
  • Part B. Both children committed, then the machine crashed before the top-level commit. Memory had shown the booking, but after restart every field was back at its initial value. A child’s commit is relative.
  • Part C. The parent aborted after its children committed, and all fields were restored, because the parent had inherited the children’s undo lists.
  • Part D. Another trip’s subtransaction was blocked while T1 merely retained the hotel’s lock. T1’s own child was granted the same lock, because the retainer was its parent. After T1 committed, the other trip found no room and booked a different hotel.
  • Part E. Ten trips, every third failing at payment. Nested trips forced the log 7 times; flat ones (each step its own RVM transaction) 37. The flat design also kept the 3 failed trips’ bookings: 10 seats and 10 rooms taken, against 7 and 7. A committed flat step can only be undone by a separate compensating transaction, the idea behind sagas (Garcia-Molina and Salem 1987).

10. Design rules

  1. Log first. A change reaches its home only after its log record (WAL rule); a commit is acknowledged only after its COMMIT record (commit rule).
  2. Match the log to the buffer policy. Steal needs undo information, no-force needs redo information.
  3. Make every record and every recovery step idempotent. Use absolute values, or operations guarded by page LSNs.
  4. Log compensations and never undo them. Order the recovery passes so that no undo follows a later committed redo.
  5. Reserve log space for aborting.
  6. Checkpoint to bound recovery; truncate only what no one can need. Watch long transactions.
  7. Keep operation records to one page each (physiological logging).
  8. Protect log records with checksums. Length fields cannot tell a torn tail from a real record.
  9. Use strict two-phase locking unless you can prove a weaker isolation level is enough. Queue waiters fairly and plan for deadlocks.
  10. Build rich features as layers over a simple, well-understood core (RVM).

Summary

  • A write-ahead log lets many transactions commit with one sequential flush, while a buffer pool writes pages home lazily.
  • Steal needs undo, no-force needs redo. The four combinations, exhaustively tested:
    • all three logged policies survived every crash state;
    • mismatches broke 22–27 of ~40 in-order states;
    • breaking the WAL rule broke 8 of 77; early acknowledgement broke 50 of 86.
  • Recovery = analysis, then redo (repeat history, CLRs included), then undo of losers. Redoing winners and then undoing every non-winner broke 20 of 68 states, by re-undoing an aborted transaction. Recovery that crashes and reruns was correct everywhere.
  • Checkpoints bound recovery (74 records to read with a sharp checkpoint every 50 commits, 2 every 2, at 2.6× the page writes). Fuzzy checkpoints plus a cleaner cost no checkpoint writes. Long transactions fill the log under undo/redo and even under redo-only, unless truncation copies committed values from the log (RVM’s epoch truncation).
  • Operation logging is up to 200× smaller than value logging for data-moving updates. It needs page LSNs (without them, 26 of 35 states broke) and per-page (physiological) records.
  • RVM gives memory regions atomicity and permanence and leaves out everything else:
    • a redo-only value log, written at commit;
    • no-restore and no-flush transactions;
    • truncation that copies committed values from the log;
    • two log optimizations: ≈21% savings on Coda servers, 48–82% on clients. Forgetting set_range silently loses data.
  • Serializability: an acyclic precedence graph means equivalent to a serial order. In 9,240 interleavings of three transactions only 42.3% were serializable. Lost updates and read skew never were; dirty reads often were.
  • 2PL admitted no non-serializable schedule. Strict 2PL also removed cascading aborts. Deadlocks are the price. Under heavy contention aborts wasted up to half the work and a global lock was as good. A lock manager without FIFO queues livelocked.
  • Nested transactions: real aborts, relative commits, inherited locks, one durable commit at the top. Building them on RVM took 7 log forces for 10 trips where flat steps took 37 and left orphaned bookings.

Common pitfalls

  • Writing a stolen page before its log record is durable.
  • Acknowledging a commit before its COMMIT record is flushed, without declaring it as no-flush.
  • A buffer policy the log cannot recover: steal with a redo-only log, no-force with an undo-only log.
  • Re-undoing an aborted transaction after redoing later winners.
  • Non-idempotent redo: operation records without page LSNs, or one record for a multi-page operation.
  • Truncating the log at the checkpoint record while active transactions or dirty pages still need older records.
  • No log space reserved for compensations: a full log that cannot even abort.
  • Forgetting set_range (RVM), or any “declare before modify” call.
  • Trusting length fields to find the log’s tail.
  • Releasing write locks before commit (basic 2PL): cascading aborts and unrecoverable schedules.
  • Read-modify-write with shared locks: upgrade deadlocks.
  • A lock manager without fair queuing.
  • Treating snapshot isolation as serializable (write skew).
  • Thinking a subtransaction’s commit is durable.

Exercises

  1. Which log, which rules? A storage engine writes dirty pages of running transactions to disk whenever memory is tight, and does not write pages at commit. (a) What must each update’s log record contain? (b) What must happen before a dirty page is written? (c) Before a commit is acknowledged? (d) What must recovery do?

    AnswerThis is steal + no-force: undo/redo. (a) Both a before value (for undo, since an uncommitted page may be on disk) and an after value (for redo, since a committed change may not be). Or an operation plus enough to invert it, with page LSNs. (b) The WAL rule: the log must be flushed at least up to the page's LSN, the last record describing a change on it. (c) The commit rule: all the transaction's records and its COMMIT record must be on disk. (d) Analysis (winners, aborted, losers), redo of all history (or of winners), and undo of losers, in an order such that no undo overwrites a later committed change (§3.4). Then it must make itself restartable, by logging compensations or writing absolute values before emptying the log.
  2. Recover by hand. An undo/redo log contains [1] T1 UPD x: 5 -> 8, [2] T2 UPD y: 1 -> 4, [3] T1 COMMIT, [4] T2 UPD x: 8 -> 9, [5] T2 CLR x = 8, and then the crash (T2 was aborting). On disk: x = 9, y = 4. Using repeat-history, list the redo and undo steps and the final values.

    AnswerAnalysis: T1 is a winner; T2 has no ABORT record, so it is a loser (its abort was in progress). Redo, all history: x := 8 [1], y := 4 [2], x := 9 [4], x := 8 [5] (the CLR). Undo T2's updates backwards: [4] gives x := 8, then [2] gives y := 1. The CLR is not undone. Final: x = 8 (T1's committed value), y = 1. Recovery then logs T2's abort (or simply empties the log once the pages are durable).
  3. Why never undo a CLR? Suppose recovery treated CLRs as ordinary updates and undid them in the undo pass. Using exercise 2’s log, what would undoing [5] mean? Why is the real damage done when recovery itself keeps crashing?

    AnswerUndoing [5] means restoring its "before" value, x = 9, which is T2's uncommitted value. Undoing [4] then puts back 8. With absolute values and one complete backward pass the result happens to be right, but every compensated update is undone twice. The damage comes with restarts. A recovery interrupted after writing some CLRs would, on the next run, undo those CLRs (writing CLRs for the CLRs) and then undo the original updates again. Every crash during recovery would add work and log records, without bound. With logical undo ("c −= 5") it is worse: an undo applied to a page in an unexpected state breaks action consistency. ARIES therefore makes CLRs redo-only and gives each one a pointer (UndoNxtLSN) to the next record still to undo. Each update is then undone exactly once, however often recovery restarts.
  4. How far can we truncate? A checkpoint record is written at LSN 500. Active transactions began at LSNs 430 (T7) and 488 (T9). Dirty pages in the buffer have oldest unwritten changes at LSNs 455, 470 and 497. (a) Under undo/redo, what is the earliest LSN that must be kept? (b) Under redo-only (no-steal), where T7 and T9 have logged nothing yet? (c) What should the system do if T7 runs for another hour?

    Answer(a) min(500, 430, 488, 455, 470, 497) = 430: T7 may need undoing. (b) Active transactions log nothing before commit, so only the pages count: min(500, 455, 470, 497) = 455. But if those pages cannot be written because active transactions hold them (no-steal), the start stays pinned. (c) T7 pins the log at 430. As the log fills, the system must either abort T7, or write the pages that hold the start back. Under no-steal it can write their committed versions, as RVM's epoch truncation does, by applying committed records from the log. Under steal it can always write them; only T7's own undo records then pin the log.
  5. Page LSNs. A page holds a counter c = 50 and page LSN 40. The log has committed operation records [38] c += 5, [41] c += 2, [44] c += 1. Which does redo apply, and what is the result? What would a redo without LSN checks produce?

    AnswerThe page already reflects every change up to LSN 40, so [38] is skipped. [41] and [44] are applied: c = 53, page LSN 44. Without the check, all three are applied: c = 58, double-counting the +5. The value 50 already included it.
  6. Is it serializable? R1(x) R2(y) W1(y) R3(x) W2(x) W3(z) R1(z), all three commit at the end. Draw the precedence graph. Is the schedule conflict-serializable? If so, give the equivalent serial order.

    AnswerConflicts: R1(x) before W2(x) gives T1 → T2. R2(y) before W1(y) gives T2 → T1. That is already a cycle T1 → T2 → T1, so the schedule is not conflict-serializable. (Also R3(x) before W2(x) gives T3 → T2, and W3(z) before R1(z) gives T3 → T1.) Removing T2 would leave the order T3, T1.
  7. Wait-die vs wound-wait. Timestamps: T1 = 10 (oldest), T2 = 20, T3 = 30. T2 holds X(a); T1 and then T3 request X(a). What happens under wait-die, and under wound-wait? Why can neither deadlock?

    AnswerWait-die: T1 is older than holder T2, so it waits. T3 is younger, so it dies (aborts and restarts later with timestamp 30). Wound-wait: T1 is older, so it wounds T2 (T2 aborts and releases a), and T1 gets the lock. T3 is younger than the holder, so it waits. Neither can deadlock because waits go in only one direction of age: old waits for young under wait-die, young waits for old under wound-wait. A cycle would need someone to wait for an older and a younger transaction at once. Restarted transactions keep their original timestamps, so each eventually becomes the oldest and cannot starve.
  8. RVM in practice. A client caches file-system meta-data in RVM. It commits each update as no-flush and calls flush() every 5 seconds. (a) What can a crash lose, and what can it not corrupt? (b) One operation, “user pressed Save”, must be durable before the application says “Saved”. How? (c) A routine updates a struct’s fields but issues set_range only for the first one. What happens at the next crash?

    Answer(a) It can lose up to the last 5 seconds of committed transactions (bounded persistence). It cannot leave a torn transaction: each is atomic, recovery applies only complete, checksummed records, and later transactions' records come after earlier ones in the log. (b) Commit that transaction with flush mode (or call `flush()` before replying). The force also writes out every earlier spooled no-flush transaction, since the log is sequential. (c) Only the first field is logged. The others change in memory, are never logged, and revert after the crash, silently. The struct is then inconsistent, which RVM cannot detect. The defence is to declare the whole struct (duplicates are coalesced at no cost), or to use a language or library that issues set_range automatically.
  • Problem Set 3 asks for the contents of a no-undo/redo write-ahead log for a given interleaving, with and without truncation, and for the result of recovery. §2 (what a redo-only log records and when it is forced), §3 (which transactions recovery redoes) and §4 (what truncation discards) give the concepts. The scenarios here are different, and the answers are not here.
  • Problem Set 4 asks you to judge a transfer routine that logs and locks against ACID and liveness. §2’s two rules, §7.5 (recoverability) and §8 (strict 2PL, deadlock) give the concepts; no answers here.
  • Project 4 needs every node to make its decisions durable before acting on them, and to recover from its own log. §2.2 and §3.5 (restartable recovery) apply directly; Lecture 18 adds the commit protocol. No project code here.

Further reading

  • M. Satyanarayanan et al., “Lightweight Recoverable Virtual Memory”, SOSP 1993 / ACM TOCS 12(1), 1994 — the reading.
  • T. Haerder and A. Reuter, “Principles of Transaction-Oriented Database Recovery”, ACM Computing Surveys 15(4), 1983.
  • C. Mohan et al., “ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging”, ACM TODS 17(1), 1992.
  • P. A. Bernstein, V. Hadzilacos and N. Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987 (free online from the authors).
  • K. P. Eswaran et al., “The Notions of Consistency and Predicate Locks in a Database System”, CACM 19(11), 1976.
  • C. H. Papadimitriou, “The Serializability of Concurrent Database Updates”, JACM 26(4), 1979.
  • D. J. Rosenkrantz, R. E. Stearns and P. M. Lewis, “System Level Concurrency Control for Distributed Database Systems”, ACM TODS 3(2), 1978.
  • H. T. Kung and J. T. Robinson, “On Optimistic Methods for Concurrency Control”, ACM TODS 6(2), 1981.
  • H. Berenson et al., “A Critique of ANSI SQL Isolation Levels”, SIGMOD 1995 — snapshot isolation and write skew.
  • J. E. B. Moss, Nested Transactions: An Approach to Reliable Distributed Computing, MIT, 1981 (MIT Press 1985).
  • H. Garcia-Molina and K. Salem, “Sagas”, SIGMOD 1987.
  • J. Gray and A. Reuter, Transaction Processing: Concepts and Techniques, Morgan Kaufmann, 1993.

Preview of Lecture 18 — Distributed transactions and two-phase commit

Everything here ran on one machine with one log. When a transaction updates data on several machines, each can log and lock locally, but they must all reach the same decision: commit everywhere or abort everywhere, even if some of them, or the coordinator, crash at the worst moment. Lecture 18 covers:

  • why this needs unanimity;
  • the two-phase commit protocol, and what each side must log and when (this lecture’s rules, across machines);
  • the failure cases, and why 2PC blocks;
  • presumed abort, and three-phase commit.

术语表 (Glossary, English → 中文)

English中文
write-ahead log (WAL)预写日志
log record / log sequence number (LSN)日志记录 / 日志序列号
log buffer / log tail / log head日志缓冲区 / 日志尾 / 日志头
buffer pool / buffer manager缓冲池 / 缓冲区管理器
dirty page / clean (write back)脏页 / 清理(写回)
home location原位(本位)
steal / no-steal窃取 / 不窃取
force / no-force强制 / 不强制
undo / redo撤销 / 重做
undo/redo, redo-only (no-undo/redo), undo-only (undo/no-redo)撤销/重做、仅重做(无撤销/重做)、仅撤销(撤销/无重做)
WAL rule / commit rule预写日志规则 / 提交规则
group commit组提交
before image / after image前像 / 后像
analysis pass / redo pass / undo pass分析阶段 / 重做阶段 / 撤销阶段
winner / loser transaction胜者事务 / 败者事务
repeating history重演历史
compensation log record (CLR)补偿日志记录
idempotent recovery幂等恢复
checkpoint (sharp / fuzzy)检查点(尖锐 / 模糊)
log truncation日志截断
recovery LSN (recLSN)恢复日志序列号
background cleaner后台清理器
log-space reservation日志空间预留
physical (value) logging物理(值)日志
logical (operation) logging逻辑(操作)日志
physiological logging物理逻辑日志
page LSN页日志序列号
action consistency操作一致性
recoverable virtual memory (RVM)可恢复虚拟内存
segment / region / external data segment段 / 区域 / 外部数据段
set_range设置范围(声明将修改的内存区间)
no-restore transaction不可恢复(不保存旧值)事务
no-flush (lazy) transaction不刷新(惰性)事务
bounded persistence有界持久性
epoch truncation / incremental truncation纪元截断 / 增量截断
intra- / inter-transaction optimization事务内 / 事务间优化
external pager外部分页器
concurrency control并发控制
schedule / serial schedule调度 / 串行调度
conflict / conflict-equivalent冲突 / 冲突等价
conflict serializability / view serializability冲突可串行化 / 视图可串行化
precedence (serialization) graph优先图(串行化图)
lost update / dirty read / unrepeatable read / read skew丢失更新 / 脏读 / 不可重复读 / 读偏斜
recoverable / cascadeless schedule可恢复 / 无级联调度
cascading abort级联中止
shared (S) / exclusive (X) lock / lock upgrade共享锁 / 排他锁 / 锁升级
two-phase locking (2PL) / lock point两阶段锁 / 锁点
growing phase / shrinking phase增长阶段 / 收缩阶段
strict 2PL / strong strict (rigorous) 2PL严格两阶段锁 / 强严格两阶段锁
deadlock / wait-for graph死锁 / 等待图
wait-die / wound-wait / no-wait / timeout等待-死亡 / 伤害-等待 / 不等待 / 超时
livelock / starvation活锁 / 饥饿
lock granularity / intention lock锁粒度 / 意向锁
phantom / predicate lock幻影 / 谓词锁
optimistic concurrency control (OCC)乐观并发控制
multiversion concurrency control (MVCC)多版本并发控制
snapshot isolation / write skew快照隔离 / 写偏斜
nested transaction / subtransaction嵌套事务 / 子事务
top-level transaction顶层事务
lock inheritance / lock retention锁继承 / 锁保留
compensating transaction / saga补偿事务 / 长事务(Saga)
← 返回课程目录