Lecture 16 · Atomic transactions I: ACID, shadowing and intentions lists

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

课程源码 ZIP ↓

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

本篇目录

Maps to: CMU 15-440/640 Spring 2026, learning outcomes “fault tolerance: atomic transactions; ACID” and “shadowing, intentions lists”. Problem set: PS3 asks you to spot ACID violations in code and to find a bug in an intentions list. This lecture teaches the concepts with different scenarios, and gives no answers. Project: P4’s participants must record decisions durably before acting on them; no project code here. Sources:

  • T. Haerder and A. Reuter, Principles of Transaction-Oriented Database Recovery (ACM Computing Surveys 1983), where ACID was named;
  • B. Lampson and H. Sturgis, Crash Recovery in a Distributed Data Storage System (Xerox PARC 1979), stable storage and intentions lists;
  • R. A. Lorie, Physical Integrity in a Large Segmented Database (ACM TODS 1977), shadow pages;
  • J. Gray and A. Reuter, Transaction Processing: Concepts and Techniques (Morgan Kaufmann 1993);
  • J. Gray, Why Do Computers Stop (1985), Lecture 13’s reading;
  • T. S. Pillai et al., All File Systems Are Not Created Equal: On the Complexity of Crafting Crash-Consistent Applications (OSDI 2014);
  • J. Mohan et al., Finding Crash-Consistency Bugs with Bounded Black-Box Crash Testing (OSDI 2018).

The slides are not public; this is not a transcript. Every number not attributed to a paper comes from code/lecture16/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9). Demos 01–04 are exhaustive and deterministic; demo 05 measures real files and varies from run to run. Code: code/lecture16/. Reading time: ~80 minutes, plus ~5 to run the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Define a transaction and its ACID properties, and say which mechanism provides each.
  2. Explain why updating several records “at once” is hard: crashes at any instant, non-atomic multi-block writes, reordered writes, concurrency.
  3. Build stable storage from two unreliable disks (Lampson and Sturgis), and explain why scrubbing matters.
  4. Implement shadowing (shadow paging; write-temp-then-rename), identify its commit point, and state its ordering rule and costs.
  5. Implement an intentions list, and state its three rules: nothing changes before the commit record, intentions are durable before it, and they are idempotent.
  6. Do a crash-point analysis: enumerate crash states, including reordered writes and crashes during recovery, and check all-or-nothing and durability.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 15: durable writes (fsync vs F_FULLFSYNC), the output-commit rule;
    • Lecture 13: Gray’s “transactions + persistent process pairs”;
    • Lecture 4: idempotence.
  • Scope: atomicity and durability on one machine, for a single transaction at a time. Write-ahead logging (undo/redo), recovery algorithms and concurrency control (serializability, two-phase locking) are Lecture 17. Transactions across machines (two-phase commit) are Lecture 18.

0.3 Section → code map

SectionIdeaDemo in code/lecture16/
§1–2what goes wrong without transactions01_why_transactions.py
§3stable storage02_stable_storage.py
§4shadowing03_shadowing.py, 05_real_files.py (real)
§5–6intentions lists; comparison04_intentions_lists.py
§7crash-point analysistoydisk.py, txstore.py

0.4 Notation and the toy world

  • A block is the unit of atomic writing: a write of one block either happens completely or not at all (“sector atomicity”). A write of several blocks is not atomic.
  • Flush (a write barrier, fsync with a full cache flush): every write issued before it is durable before any write issued after it. Between flushes, writes may become durable in any order.
  • The commit point of a transaction is the instant after which it is guaranteed to happen, and before which it is guaranteed not to.
  • The toy bank: 4 accounts of 100 units. A workload of three transfers (30 from account 0 to 2, 50 from 1 to 3, 20 from 3 to 0), each acknowledged to its caller when commit() returns.

1. The transaction abstraction

1.1 The intuition

Moving 30 units from account 0 to account 2 is two writes: account 0 becomes 70, account 2 becomes 130. If the machine crashes between them, 30 units have vanished. If another program reads both balances between them, it sees a total of 370 that never existed. The transfer is meaningful only as a whole.

A transaction packages a group of operations so that the rest of the world sees them as one indivisible step. The programmer writes

begin transaction
    read A; read B; write A - 30; write B + 30
commit            (or abort)

and the system guarantees that this step either happens completely or not at all, and that nobody sees it half done. Gray (Lecture 13) called this the key to software fault tolerance: when something goes wrong in the middle, abort the transaction and the system resets everything to how it was. The programmer does not have to write the clean-up code for every failure case.

1.2 ACID

Haerder and Reuter (1983) named the four properties:

propertymeaningthreatwho provides it
Atomicityall of the transaction’s effects happen, or none doa crash, or an abort, in the middlerecovery: shadowing, intentions lists, logs (this lecture, Lecture 17)
Consistencya transaction takes the database from one valid state to another (balances sum to 400, no negative balance)bugs in the transaction itselfthe application’s invariants, given A, I and D
Isolationconcurrent transactions behave as if run one at a timeinterleaving with other transactionsconcurrency control: locks, serializability (Lecture 17)
Durabilityonce committed, the effects survive any later crashcrashes after the commitstable storage, forcing data to disk before acknowledging

Gray’s 1985 paper (Lecture 13) used slightly different words, “consistency” and “integrity”, but the content is the same.

Consistency is the odd one out. The system cannot know which states are valid; the application defines them. What the system promises is that if every transaction, run alone from a valid state, leaves a valid state, then A + I + D preserve validity despite crashes and concurrency.

1.3 What goes wrong without them (demo 01)

Crashes. Demo 01 Part A runs the three transfers by overwriting the balances in place, then enumerates every state a crash could leave on the disk.

how writes reach the diskdistinct crash stateshalf a transfer (money created or destroyed)
in program order73 (e.g. (70, 100, 100, 100): −30)
in any order between flushes106 (e.g. (100, 100, 130, 100): +30)

Reordering adds states that no program order produces: the credit can reach the disk before the debit.

Concurrency. Part B runs two transfers (A→B 30, B→C 50) and an auditor that adds up all three balances. It enumerates all 11,550 ways their steps can interleave:

executionschedulesfinal balances wrongauditor sees a total ≠ 300
no isolation11,5508,580 (74.3%)4,638 (40.2%)
each program alone (serial orders)600

One example of a lost update:

  1. The first transfer reads B = 100.
  2. The second transfer reads B = 100 too.
  3. The first writes B = 130.
  4. The second writes B = 50, overwriting the first’s +30.

Crashes and concurrency are the same disease: somebody sees, or is left with, half of a change. This lecture cures it for crashes; Lecture 17 for concurrency.


2. Why atomicity is hard

2.1 The disk does not help

Everything rests on what a disk promises when power fails:

  • One sector (512 bytes or 4 KB) is written atomically: old or new, never a mixture. Even this is a promise that real devices sometimes break. A torn write leaves garbage; §3 handles it.
  • Several sectors are not atomic. A crash can leave any subset of them written.
  • Order is not preserved. The operating system’s page cache, the I/O scheduler and the drive’s own write cache may all make writes durable in a different order from the one the program issued them in. Only a flush (fsync; on macOS F_FULLFSYNC, Lecture 15 §2.4) puts a barrier between them.
  • Stored data can decay later (bit rot, a failing head).

2.2 The recipe

Every correct scheme in this and the next lecture follows the same recipe:

  1. Choose one atomic action as the commit point: a single block write.
  2. Before the commit point, nothing the reader can see has changed. At worst, invisible preparations have been made, and a crash simply forgets them.
  3. Everything the commit point depends on is durable before it is written. That means a flush.
  4. After the commit point, recovery can always finish the job, however many times it is itself interrupted. Its actions must be idempotent: doing them twice equals doing them once.

2.3 Crash-point analysis

Hand arguments about the recipe are error-prone, so the code checks it by brute force. toydisk.explore:

  1. runs the workload once and records every block write, flush and acknowledgement;
  2. rebuilds every disk state a crash could leave. In in-order mode that is after each write or acknowledgement. In reorder mode it is all writes before the last flush plus any subset of the writes since, with every acknowledgement issued before the next flush counted as already seen;
  3. runs the store’s recovery on each state, then crashes the recovery after each of its writes and recovers again;
  4. checks that the result is the state after j transfers, for some j at least the number already acknowledged. That covers atomicity and durability together.

The same idea, at industrial scale, underlies crash-consistency testers such as ALICE (Pillai et al. 2014) and CrashMonkey (Mohan et al. 2018). Both found many crash-consistency bugs in widely used software.


3. Stable storage

3.1 From an unreliable disk to a reliable block

Lampson and Sturgis (1979) start one level down. Before building transactions, build stable storage: a block abstraction whose write is atomic and whose contents never decay. Their construction:

  • Keep two copies of every block, on two disks with independent failures, each with a checksum.

  • Careful write: write copy 1, read it back to check it; then write copy 2. Never write both at once.

  • Careful read: read copy 1; if its checksum is bad, read copy 2.

  • Recovery after a crash, for every block:

    • if copy 1 is good and differs from copy 2 (or copy 2 is bad), copy 1 is the newer version: copy it over copy 2;
    • if copy 1 is bad, copy 2 still holds the old value: copy it back.

    Only the one block being written at the crash can differ, so recovery leaves every block holding either its old or its new value, the same on both disks.

3.2 Demo 02

Part A writes 20 new values to 5 blocks. It crashes after every write, with the next write either torn (the block becomes garbage) or not started, and asks what a reader finds in the block that was being written:

schemecrash casesold valuenew valuesilent garbageunreadable
one disk, no checksum40200200
one disk + checksum40200020
stable storage80404000

A plain disk returns garbage without knowing it: a Byzantine failure (Lecture 14). A checksum turns that into a detected failure (fail-fast), but the data is gone. Neither the old nor the new value survives. Stable storage always returns one of the two: a block write has become atomic.

3.3 Decay and scrubbing

Two copies protect against decay only if a bad copy is noticed and repaired before the other one fails too, exactly Lecture 13’s window of vulnerability. Part B lets each copy decay at random (mean once per 20 years) and scrubs at an interval S: it checks both copies of every block and repairs a bad one. Results for 1,000 blocks over 10 years:

scrub everyblocks lost (simulated)formula 10 yr × (365/S) × (λS)² × 1,000
1 day00.07
30 days32.05
365 days2025
never157—

The loss rate grows linearly with the scrub interval, MTTF²/(2 MTTR) in another guise. Storage systems and RAID controllers scrub routinely.


4. Shadowing

4.1 The idea

Never overwrite the current version. Build the new version beside it, in free space, and when it is complete and durable, switch to it by writing one pointer. Until that pointer write, the old version is intact. After it, the new one is complete. The pointer write is the commit point.

4.2 Shadow paging

Lorie (1977) applied this to databases, and it was used in System R. The toy version in txstore.Shadow: block 0 is the root, pointing to a two-block page table, which points to the data blocks. Demo 03 Part A shows one transaction (30 from account 0 to 2):

blockvalue writtenrole
470new data (free block)
5130new data (free block)
6(4, 11)new page table (free block)
7(5, 13)new page table (free block)
—flushbarrier
0(1, 6, 7)root: the commit point
—flushbarrier

The root went from version (0, 2, 3) to (1, 6, 7). Recovery is trivial: read the root and follow it. Whatever version it names is complete. Blocks of older versions are simply free space, reclaimed when nothing reachable points to them.

4.3 Crash-point analysis

Demo 03 Part B, three transfers, every crash state and every crash of recovery:

variantviolations (in-order writes)violations (reordered writes)
correct shadowing0 / 190 / 55
BUG: no flush before swinging the root0 / 1945 / 97
BUG: page table updated in place (two blocks)3 / 166 / 25
in place (for comparison)3 / 106 / 13
  • The flush before the root is the whole trick. Without it, a disk that reorders writes can make the root durable before the page table it points to. After a crash, the root points into garbage, and recovery reports a page table that never reached the disk. With in-order writes the bug is invisible. A test harness that only crashes between writes would ship it.
  • Updating the page table in place loses the single commit point. Two separate block writes cannot be one atomic step, so a crash between them leaves half the transfer, even with in-order writes. This is why the page table itself must be shadowed, and in a tree, every node on the path from the changed leaf to the root.

4.4 Shadowing in everyday life: write, flush, rename

The most widely used form of shadowing updates a file atomically:

  1. write the new contents to a temporary file;
  2. fsync it, so that it is durable before the pointer swings;
  3. rename it over the old name; POSIX rename is atomic, so the name now points at the new contents;
  4. fsync the directory, so that the rename itself survives a power failure.

Demo 05 tries it on real files, with a writer process that rewrites a 1 MiB file in 16 chunks:

in placewrite + rename
a concurrent reader saw two versions mixed (REAL, 1.5 s)29–53% of reads0%
writer killed (SIGKILL) mid-update: file left mixed (REAL, 20 kills)11–19 of 200 of 20
one durable 4 KB update, full cache flushes (REAL)~4 ms~8 ms

Rename never left a mixed file; the only debris was a leftover temporary file, which is harmless garbage. Killing a process does not test durability ordering, because the operating system survives. That is what steps 2 and 4 and the toy disk’s reorder mode are about. Pillai et al. (2014) found that real applications frequently get such update protocols wrong, for example by omitting one of the flushes, and that whether the omission matters depends on the file system.

The same pattern appears at larger scale:

  • copy-on-write file systems (ZFS, btrfs, WAFL, APFS) never overwrite live blocks, and commit by writing a new root block (an “uberblock” or superblock);
  • the LMDB key-value store keeps a copy-on-write B+-tree with two alternating root (“meta”) pages.

4.5 What shadowing costs

  • Write amplification. Changing one record rewrites the record, the page-table blocks that point to it and the root: in a tree, the whole path from leaf to root. In demo 03: 5 block writes and 2 flushes per transfer, against 2 writes and 1 flush in place.
  • Lost locality. Every update moves the data to a new place. Part C starts a 16-page file in one contiguous run; after 200 small transactions it is in 15 separate runs, so a sequential scan becomes 15 separate reads.
  • Garbage collection. Old versions must be found and freed (here by reachability from the root).
  • One commit at a time. With a single root, concurrent transactions must be serialized at the commit point, or merged.

These costs, above all lost clustering and page-table I/O, are a large part of why databases moved from shadow paging to logging (Lecture 17). File systems kept copy-on-write, because it also gives cheap snapshots.


5. Intentions lists

5.1 The idea

Lampson and Sturgis’s second construction leaves the data in place and records the change elsewhere first. An intentions list is a list of “I intend to set record k to value v”, written to stable storage. The protocol:

  1. write the intentions (new values) to the list;
  2. flush;
  3. write a commit record: the commit point;
  4. flush;
  5. apply the intentions to the records’ home locations;
  6. flush;
  7. mark the list done, so that it can be reused.

Recovery: if the commit record is present and the list is not done, apply every intention again, then mark it done. If there is no commit record, discard the list. Demo 04 Part A prints the 6 writes and 4 flushes of one transaction: two intention records, the COMMIT record, two home blocks, DONE.

5.2 The three rules

The protocol rests on three rules, and demo 04 Part B breaks each one:

variantin order, recovery once+ recovery crashesreordered writes
correct intentions list0 / 250 / 610 / 91
BUG: delta records (“+30”, not ”= 130”)6 / 2536 / 6160 / 91
BUG: no flush before the commit record0 / 250 / 619 / 97
BUG: home blocks updated before committing3 / 253 / 4324 / 79
BUG: recovery ignores the commit record3 / 259 / 769 / 115
  1. Before the commit record, the database does not change. Updating home blocks early, or letting recovery apply intentions that were never committed, exposes half a transfer. (Lecture 17’s undo logging relaxes this rule by recording the old values, so that early changes can be rolled back.)
  2. The intentions are durable before the commit record. Without the flush, a reordering disk can make the commit record durable first. Recovery then finds a committed transaction whose intentions are missing. Again the bug is invisible with in-order writes.
  3. Intentions must be idempotent. A crash can strike during the apply phase, and again during recovery’s apply, any number of times. Recovery cannot know which intentions already reached their home blocks, so it applies them all again. “Set account 0 to 70” can be applied twice harmlessly; “subtract 30 from account 0” cannot.

Part C shows rule 3 up close. The first transfer crashes right after its first home-block write, leaving (70, 100, 100, 100):

recordsafter recoverytotal
absolute (”= 70”, ”= 130”)(70, 100, 130, 100)400
delta (“−30”, “+30”)(40, 100, 130, 100)370

The delta list applies −30 to an account that had already been debited.

If an operation is naturally a delta, such as an increment or an append, there are two ways to make it idempotent:

  • turn it into an absolute value when the intention is written (read the old value, write the new one);
  • record enough information to tell whether it was already applied: a version number per record, which Lecture 17’s log sequence numbers make systematic.

5.3 Where intentions lists lead

An intentions list is a redo-only log:

  • the intentions are redo records;
  • the commit record marks the transaction as committed;
  • recovery redoes committed work and never has to undo anything, because rule 1 keeps uncommitted changes out of the database.

Lecture 17 calls this no-undo/redo logging and generalizes it to write-ahead logging: undo and redo records, logs shared by many transactions, checkpoints, and log sequence numbers.


6. Shadowing vs intentions

shadowingintentions list
commit pointthe root (one pointer)the commit record
datawritten to new placeswritten in place, after commit
writes per transfer (demo 04 Part D)56
flushes per transfer24
physical localitylost (pages move)kept (home blocks)
readsthrough the page tabledirect
recovery worknone: follow the rootredo any committed, unfinished list
garbageold versions to collectthe list, after DONE
concurrencyone root: commits serializelists per transaction; can be combined in one log
snapshotsfree (keep an old root)need extra work
everyday examplewrite-temp-then-rename; ZFS, btrfs, APFS; LMDBdatabase write-ahead logs; journaling file systems

Neither is free. Shadowing writes everything once, in a new place. Intentions write everything twice (in the list and at home) but keep the data where it belongs. Both have exactly one commit point and both need flushes in the right places.

The extra flushes of the intentions list can be shared. Many transactions’ intentions can go in one log write (group commit), and the apply phase can be done lazily in the background. That is how Lecture 17’s logs become fast.


7. Crash-point analysis as a design method

What the checker found, in one place:

  • Every scheme without a single commit point failed: in place, page table in place.
  • Both missing-flush bugs passed every in-order crash point and failed only when writes could be reordered. A crash test that does not model reordering misses exactly the bugs that real disks produce.
  • The delta-record bug needed no exotic scenario: an ordinary crash during the apply phase triggered it 6 times in 25 states.
  • Recovery must survive its own crashes: adding crashes during recovery raised the delta-record violations from 6 to 36 (in-order writes).

Our first enumeration of crash states was itself wrong. It never checked a state in which a transaction had been acknowledged but nothing more had been written, so it would have missed “acknowledge before flushing”. The checker’s self-test now contains exactly that bug. Test the tester.


8. Design rules

  • One commit point, one atomic block write. If you cannot name it, you do not have atomicity.
  • Before the commit point, change nothing visible. After it, be able to finish, however often recovery is interrupted.
  • Flush everything the commit point depends on before writing it, and flush the commit point before acknowledging (durability; Lecture 15’s output commit).
  • Make redo actions idempotent: absolute values, or version checks.
  • Shadow the metadata too: a page table updated in place is not atomic.
  • For files: write temp, fsync, rename, fsync the directory.
  • Build on stable storage: checksums detect damage; a second copy, written carefully and scrubbed, repairs it.
  • Test crash consistency by enumeration, including reordered writes and crashes during recovery.

Summary

  • Transactions make a group of operations one indivisible step.
    • ACID: atomicity and durability come from recovery, isolation from concurrency control, consistency from the application given the other three.
    • Without them, in-place transfers left half a transfer in 3 of 7 crash states (6 of 10 with reordered writes).
    • Unisolated interleavings lost updates 74.3% of the time.
  • The recipe:
    • one atomic commit point;
    • nothing visible changes before it;
    • its dependencies are flushed before it;
    • idempotent recovery after it.
  • Stable storage (two disks, careful writes, recovery) turned torn writes from silent garbage (plain disk) or unreadable blocks (checksum) into “old or new value”, every time. Scrubbing keeps decay at bay: 157 of 1,000 blocks lost in 10 years without it, 0 with daily scrubs.
  • Shadowing: new data and metadata go to free blocks, then the root swings.
    • Correct shadowing passed every crash state.
    • Without the flush before the root it broke 45 of 97 reordered states, and 0 in order.
    • It costs 5 writes and 2 flushes per transfer, and a contiguous file ended in 15 runs.
    • The real-file version (temp + fsync + rename + fsync dir) never left a mixed file, against 11–19 of 20 in place.
  • Intentions lists: write intentions, flush, commit record, flush, apply, flush, done.
    • The correct list passed every state.
    • Delta records broke 6 of 25 states (36 of 61 with recovery crashes).
    • A missing flush showed only under reordering (9 of 97).
    • It costs 6 writes and 4 flushes, but keeps data in place.
  • Crash-point analysis found every bug, and found a bug in its own first version.

Common pitfalls

  • “It’s just two writes, a crash is unlikely in between.” At scale, every window is hit.
  • Assuming writes reach the disk in the order issued. Without flushes, they do not.
  • Acknowledging before the commit is durable.
  • Shadowing the data but updating the page table (or any multi-block metadata) in place.
  • Rename without fsync before it (the new name points to unflushed data) or after it (the rename may be lost).
  • Non-idempotent redo records (“add 30”).
  • Changing the database before the commit record without a way to undo it.
  • Recovery code that cannot itself be interrupted and rerun.
  • Trusting a checksum to recover data: it only detects.
  • Testing crash consistency only at write boundaries, in order.

Exercises

  1. Who provides what? For each mechanism, say which ACID property (or properties) it mainly provides: (a) a lock manager that delays conflicting transactions; (b) the flush of a commit record before replying “OK”; (c) the rule “a transaction’s changes reach the home blocks only after its commit record”; (d) a check constraint “balance ≥ 0” that aborts any transaction violating it; (e) recovery re-applying committed intentions.

    Answer(a) Isolation. (b) Durability: the reply is the outside world's evidence of the commit, the output-commit rule. (c) Atomicity: a crash before the commit record leaves no trace in the database. (d) Consistency: the application's invariant, enforced by aborting (which relies on atomicity to remove the transaction's partial effects). (e) Atomicity and durability together: a committed transaction is completed after a crash, so all its effects appear and stay.
  2. Enumerate by hand. A transaction sets three records X, Y, Z (each in its own block) in place, with one flush at the end. (a) List the crash states with in-order writes, and say which violate atomicity. (b) How many crash states are there if the disk may reorder the three writes?

    Answer(a) In order, a crash leaves: nothing written; X; X and Y; X, Y and Z. The middle two violate atomicity (half the transaction). (b) Any subset of {X, Y, Z} can be durable: 2³ = 8 states, of which only {} and {X, Y, Z} are acceptable. 6 violate atomicity, including states like "only Z", which no program order produces.
  3. Shadowing a tree. A database stores its records in a B-tree of height 3 (root, internal node, leaf), with a fixed superblock pointing to the root. Using shadowing, which blocks must be written to update one record, in which order, and where are the flushes?

    AnswerCopy-on-write the whole path: (1) write a new leaf with the updated record; (2) write a new internal node pointing to the new leaf; (3) write a new root pointing to the new internal node; then **flush**; (4) write the superblock to point to the new root (the commit point); **flush** before acknowledging. That is 4 block writes (3 new nodes + superblock) for one record: write amplification grows with the tree's height. The old leaf, internal node and root become garbage once no snapshot needs them.
  4. Ordering the rename. A program saves its configuration with write(tmp); rename(tmp, conf) and nothing else. (a) What can a power failure leave? (b) Add the minimum calls for a durable, atomic update and explain each.

    Answer(a) The rename is a metadata update that may reach the disk before the temporary file's data. After a power failure `conf` may name an empty or partially written file, which is worse than the old one. The rename may also be lost entirely. (b) `write(tmp); fsync(tmp)` makes the new contents durable before the name points to them (the flush before the root). Then `rename(tmp, conf)` is the atomic pointer swing. Then `fsync(directory)` makes the rename itself durable, so that the update is not silently undone after acknowledging. On macOS, use `F_FULLFSYNC` where `fsync` is called for real durability.
  5. Idempotent intentions. A shopping-cart service wants an intentions list for “append item I to cart C”. (a) Why is an intention “append I to C” unsafe? (b) Give two ways to make it idempotent.

    Answer(a) If the crash happens after the append reached C's home block but before the list is marked done, recovery appends I again: the cart now has I twice. (b) Option 1: write an absolute intention, "set cart C to [old items…, I]", computing the new value when the intention is written. Applying it twice gives the same cart. Option 2: give the operation an identity and make application conditional, for example "append (txn 17, I) unless C already contains an entry from txn 17", or store a version number in C and apply "if C.version = 41, set version 42 and append I". The second form is the idea behind Lecture 17's log sequence numbers.
  6. Interrupted twice. With absolute intention records (”= 70”, ”= 130”), trace this: commit record written; home block of account 0 written (70); crash; recovery starts, writes account 0 = 70 and crashes again; recovery runs to completion. What is the final state, and why is it correct?

    AnswerAfter the first crash: account 0 = 70, account 2 = 100, commit record present, list not done. Recovery 1 writes 0 = 70 (unchanged) and crashes. Recovery 2 finds the commit record still there and the list not done. It applies 0 = 70 and 2 = 130, flushes, and marks the list done. Final (70, ·, 130, ·): the transfer happened exactly once. Each application of an absolute record is idempotent, so any number of partial recoveries followed by one complete one gives the same result.
  7. Why one disk at a time? In Lampson–Sturgis stable storage, why must copy 2 be written only after copy 1 has been written and checked? What could go wrong if both were written at the same time?

    AnswerIf both writes are in progress when power fails, both copies can be torn: neither the old nor the new value survives, and the block is lost. Writing them one after the other guarantees that at any instant at most one copy is being written, so the other holds a good value, old or new. Checking copy 1 before writing copy 2 ensures that by the time the old value is overwritten on disk 2, a good new value exists on disk 1. This lets recovery prefer copy 1 when both are good but different.
  8. Choose a design. A key-value store holds large values (1–10 MB) that are each replaced as a whole, rarely updated in place, and often read sequentially. Updates must be atomic per key. Would you use shadowing or an intentions list? Justify, and say what you would flush when.

    AnswerShadowing, per key: write the new value to fresh space, flush, then atomically switch the key's index entry (or the key's file, with rename) to it, and flush the index. An intentions list would write every 10 MB value twice (in the list and at home), doubling write traffic for whole-value replacements. Shadowing writes the value once, and locality within a value is preserved because each value is written contiguously when it is created. Shadowing's usual costs are small here: lost locality affects only small, scattered updates, and garbage is just the old value's space, reclaimed after the switch. The index entry update must itself be atomic: one block, or a shadowed index root.
  • Problem Set 3 asks you to spot ACID violations in pseudo-code and to diagnose a botched intentions list. §1–§2 (which property protects against what), §5.2 (the three rules: nothing changes before commit, intentions durable before commit, idempotent intentions) and §7 give the concepts. The scenarios here are different, and the answers are not here.
  • Project 4 requires participants and the coordinator to make decisions durable before acting on them and to recover from what is on disk. §2’s recipe and §5’s rules apply directly. Lectures 17–18 add logs and the commit protocol. No project code here.

Further reading

  • T. Haerder and A. Reuter, “Principles of Transaction-Oriented Database Recovery”, ACM Computing Surveys 15(4), 1983.
  • B. Lampson and H. Sturgis, “Crash Recovery in a Distributed Data Storage System”, Xerox PARC technical report, 1979 — stable storage and intentions lists; also in B. Lampson, “Atomic Transactions”, in Distributed Systems: Architecture and Implementation (LNCS 105), 1981.
  • R. A. Lorie, “Physical Integrity in a Large Segmented Database”, ACM TODS 2(1), 1977 — shadow pages.
  • J. Gray and A. Reuter, Transaction Processing: Concepts and Techniques, Morgan Kaufmann, 1993 — the reference text.
  • T. S. Pillai et al., “All File Systems Are Not Created Equal: On the Complexity of Crafting Crash-Consistent Applications”, OSDI 2014.
  • J. Mohan et al., “Finding Crash-Consistency Bugs with Bounded Black-Box Crash Testing”, OSDI 2018.
  • R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, chapters on crash consistency (fsck and journaling) and log-structured / copy-on-write file systems (free online).

Preview of Lecture 17 — Atomic transactions II: write-ahead logging, RVM and concurrency control

Intentions lists generalize to a single write-ahead log shared by all transactions. Lecture 17 covers:

  • undo, redo and undo/redo logging, and when each is needed;
  • recovery algorithms and checkpoints that bound them;
  • physical vs operation (logical) logging;
  • Satyanarayanan et al.’s Lightweight Recoverable Virtual Memory (the reading), which brings transactions to ordinary memory;
  • isolation: serializability, two-phase locking and deadlock, which cure the lost updates of §1.3.

术语表 (Glossary, English → 中文)

English中文
transaction事务
begin / commit / abort开始 / 提交 / 中止
atomicity / consistency / isolation / durability (ACID)原子性 / 一致性 / 隔离性 / 持久性
all-or-nothing全有或全无
invariant不变式
lost update丢失更新
inconsistent read不一致读
interleaving / schedule交错 / 调度
serial execution串行执行
sector atomicity扇区原子性
torn write撕裂写(部分写)
write cache / write reordering写缓存 / 写重排序
flush / write barrier刷新 / 写屏障
commit point提交点
idempotent幂等的
stable storage稳定存储
careful write / careful read谨慎写 / 谨慎读
decay (bit rot)衰变(位腐烂)
scrubbing擦洗(定期巡检修复)
shadowing / shadow paging影子技术 / 影子分页
copy-on-write写时复制
root block / superblock / uberblock根块 / 超级块 / 顶层块
page table页表
atomic rename原子重命名
write amplification写放大
fragmentation (loss of locality)碎片化(局部性丧失)
garbage collection垃圾回收
snapshot快照
intentions list意图列表
intention record / commit record意图记录 / 提交记录
redo / undo重做 / 撤销
redo-only log (no-undo/redo)仅重做日志(无撤销/重做)
write-ahead logging (WAL)预写日志
home location (home block)原位(本位块)
recovery procedure恢复过程
crash-point analysis崩溃点分析
crash consistency崩溃一致性
group commit组提交
journaling file system日志文件系统
← 返回课程目录