Este livro ainda não está disponível em Português. Edições: English.
University Computer Science — Year 3 · Graduação — Ano 3
23Concurrency Control and Recovery
A database promises each transaction two things it cannot see being kept: that the other transactions running at the same time do not disturb it, and that a crash at any moment loses nothing it committed and keeps nothing it did not. This chapter builds both promises. A schedule of interleaved reads and writes is judged by a graph; two-phase locking makes every schedule pass the test, at the price of waiting and deadlocks; multiversion concurrency avoids most of the waiting and lets one anomaly through, which the two doctors of the Brenmoor clinic meet at the end of the chapter. SQLite is then watched doing all this with two connections, and a mini database with a write-ahead log is crashed after every single write it makes to its disk and recovered each time.
You already know
A transaction is a sequence of reads and writes that the database runs as one unit: it ends by a commit, which makes its changes permanent, or by a rollback, which cancels them. ACID names its four guarantees: atomicity, consistency, isolation and durability. A schedule interleaves the operations of several transactions. The anomalies an interleaving can show are the dirty read, the non-repeatable read, the phantom read, the lost update and the write skew; an isolation level names the anomalies a database rules out (Year 2 volume). A set of threads is in deadlock when each waits for something only another of the set can provide (Definition 13.2). A directed graph has a topological order, listing every edge’s tail before its head, exactly when it has no cycle (Year 1 volume).
23.1 Schedules and serialisability
A schedule is written as a list of operations: is a read of item by transaction , a write of it by . A schedule is serial when the transactions run one after the other, with no interleaving. Serial schedules are correct by definition, since each transaction alone keeps the database consistent; the question is which interleaved schedules are as good as a serial one.
Definition 23.1 (Conflicting operations, conflict serialisability, precedence graph, view serialisability, serial schedule)
A schedule is serial when the operations of each transaction are consecutive. Two operations are conflicting operations when they belong to different transactions, touch the same item and at least one of them is a write. Two schedules of the same operations are conflict-equivalent when every pair of conflicting operations comes in the same order in both. A schedule has conflict serialisability when it is conflict-equivalent to a serial schedule. Its precedence graph has one node per transaction and an edge whenever an operation of conflicts with a later operation of . View serialisability is the weaker property of being view-equivalent to a serial schedule: every read reads the value written by the same write in both, and every item’s last write is the same.
Swapping two adjacent operations that do not conflict changes nothing any transaction can observe: two reads see the same values in either order, and operations on different items are independent. Conflict-equivalent schedules are exactly those that such swaps transform into each other, which is why they leave the database in the same state.
Theorem 23.2 (The precedence-graph test)
A schedule is conflict serialisable if and only if its precedence graph has no cycle. When it has none, every topological order of the graph is the order of a conflict-equivalent serial schedule.
Proof. Suppose the schedule is conflict-equivalent to the serial schedule . An edge comes from conflicting operations of and of with before in , hence in , where every operation of then precedes every operation of . So every edge goes forwards in the order of , and a cycle would put before itself.
Conversely, let the graph be acyclic and take a topological order of it; let run the transactions serially in that order, each with its operations in their order in . The two schedules have the same operations. Let of and of conflict, with before in . Then is an edge, comes before in the topological order, and comes before in . Every conflicting pair is thus ordered alike, and is conflict-equivalent to . ∎
def conflict(p, q):
return p[0] != q[0] and p[2] == q[2] and "W" in (p[1], q[1])
def precedence_graph(schedule):
"""An edge Ti -> Tj for each conflict in which Ti's operation comes first."""
edges = set()
for i, j in combinations(range(len(schedule)), 2):
if conflict(schedule[i], schedule[j]):
edges.add((schedule[i][0], schedule[j][0]))
return edges
def serial_order(schedule):
"""A serial order of the transactions with the same conflicts (a topological
order of the graph), or None if the graph has a cycle."""
nodes = sorted({op[0] for op in schedule})
edges = precedence_graph(schedule)
order = []
while nodes:
free = [n for n in nodes if not any(b == n and a in nodes for a, b in edges)]
if not free:
return None # every remaining transaction has a predecessor: a cycle
order.append(free[0])
nodes.remove(free[0])
return order
$ python schedules.py
serial T1->T2 T1 T2
interleaved T1->T2 T1 T2
lost update T1->T2 T2->T1 not serialisable
crossed T1->T2 T2->T1 not serialisable
three T1->T2 T2->T3 T3->T1 not serialisable
blind writes T1->T2 T1->T3 T2->T1 T2->T3 not serialisable
70 interleavings of two 4-step transactions: 12 serialisable
The interleaved schedule passes: touches only after is done with it, and likewise. The lost update fails: both read before either writes, so each write erases the other’s work, and the graph shows both edges. The three schedule fails with a cycle through all three transactions, drawn below, though no two of them alone are in a cycle.
The last schedule, blind writes, fails the test too, yet it is view serialisable: no transaction reads, and writes both items last, as in the serial order . View serialisability accepts more schedules, this one among them; the chapter only tells it, and exercise 23.7 works through the example.
23.2 Two-phase locking
A scheduler must produce only serialisable schedules, without knowing in advance what each transaction will do. Locks give it the means: a read takes a shared lock on its item, which other readers may share; a write takes an exclusive lock, which nobody else may hold; a transaction that asks for a lock in conflict with one held waits.
Definition 23.3 (Two-phase locking, strict two-phase locking, cascading abort, recoverable schedule)
A transaction follows two-phase locking when it acquires all its locks before it releases any: a growing phase, then a shrinking phase. The moment of its last acquisition is its lock point. Under strict two-phase locking it also keeps its exclusive locks until it commits or aborts; the scheduler of this chapter keeps all its locks until then. A cascading abort is the abort of a transaction forced because it read a value written by a transaction that then aborted. A schedule is a recoverable schedule when each transaction commits only after every transaction whose writes it read has committed.
The rule goes back to Eswaran, Gray, Lorie and Traiger in 1976: their paper defines the transaction and the schedule and shows that consistency requires that a transaction request no new lock after releasing one.
Theorem 23.4 (Two-phase locking gives conflict serialisability)
If every transaction follows two-phase locking, the schedule of the committed transactions is conflict serialisable, and the order of their lock points is a conflict-equivalent serial order.
Proof. Let be an edge of the precedence graph: an operation of on an item conflicts with a later operation of on . At least one of them is a write, so the two locks on are incompatible, and obtained its lock only after released its own (a shared lock upgraded to exclusive counts as an acquisition). Call and the lock points. By two-phase locking released nothing before , so the release of ’s lock on the acquisition of ’s lock on . Every edge thus goes from an earlier lock point to a strictly later one, so the graph has no cycle, and listing the transactions by lock point is a topological order. Theorem 23.2 concludes. ∎
Releasing locks early, as on the left, lets another transaction read a write of before commits; if then aborts, the reader must abort too, a cascading abort, and if the reader has already committed the schedule is not even recoverable. Strict two-phase locking rules both out (exercise 23.9), which is why databases use it. The scheduler below runs transactions written as programs, in an order given step by step, and prints what each lock request does.
def blockers(self, t, op, item):
held = self.locks.get(item, {})
if op == "R":
return {u for u, m in held.items() if u != t and m == "X"}
return {u for u in held if u != t}
def step(self, t):
"""Try t's next operation; return False if it must wait."""
op, item = self.prog[t][0]
if op == "C":
for held in self.locks.values():
held.pop(t, None)
self.prog[t].pop(0)
self.done.append(t)
self.say(f"T{t} commits and releases its locks")
return True
others = self.blockers(t, op, item)
if others:
new = t not in self.waits
self.waits[t] = others
self.on_wait(t) # may abort t, or another transaction
if new and t in self.waits:
names = ", ".join(f"T{u}" for u in sorted(others))
self.say(f"T{t} {op}({item}) waits for {names}")
return False
self.waits.pop(t, None)
mode = "X" if op == "W" else self.locks.get(item, {}).get(t, "S")
self.locks.setdefault(item, {})[t] = mode
self.prog[t].pop(0)
self.history.append((t, op, item))
self.say(f"T{t} {op}({item}) with an {mode} lock")
return True
Waiting creates the danger of Chapter 13: two transactions each holding a lock the other wants.
Definition 23.5 (Wait-for graph, wound–wait, wait–die)
The wait-for graph has one node per active transaction and an edge when waits for a lock that holds; with one lock per request, the transactions are in deadlock exactly when the graph has a cycle. Two schemes prevent the cycles instead, by giving each transaction a timestamp at its start, the smaller the older, kept when it restarts. Under wait–die an older transaction asking for a lock held by a younger one waits, and a younger one asking for a lock an older one holds aborts (dies). Under wound–wait an older transaction asking for a lock held by a younger one aborts the younger (wounds it), and a younger one asking waits.
$ python twopl.py
-- no conflict: order T1 T2 T1 T2 T1 T2
T1 R(A) with an S lock
T2 R(B) with an S lock
T1 W(A) with an X lock
T2 W(B) with an X lock
T1 commits and releases its locks
T2 commits and releases its locks
-- blocked: order T1 T1 T2 T1 T1 T1 T2
T1 R(A) with an S lock
T1 W(A) with an X lock
T2 R(A) waits for T1
T1 R(B) with an S lock
T1 W(B) with an X lock
T1 commits and releases its locks
T2 R(A) with an S lock
T2 W(A) with an X lock
T2 commits and releases its locks
-- deadlock: order T1 T2 T1 T2
T1 R(A) with an S lock
T2 R(B) with an S lock
T1 W(B) waits for T2
deadlock, T2 waits for T1 waits for T2: abort T2
T1 W(B) with an X lock
T1 commits and releases its locks
The scheduler looks for a cycle each time a transaction starts to wait, by following the edges from it, and aborts the youngest transaction on the cycle; a real system would restart it. A timeout is the other answer: it needs no graph, but it also aborts transactions that were only slow.
23.3 Multiversion concurrency
Under locking, a reader waits for a writer and a writer for a reader. If the database keeps the old value when it writes a new one, a reader can read the old value and nobody waits.
Definition 23.6 (Multiversion concurrency control, snapshot isolation, serialisable snapshot isolation)
Under multiversion concurrency control each item keeps several versions, each tagged with the commit timestamp of the transaction that wrote it. Under snapshot isolation a transaction reads, for each item, the newest version committed before it started, together with its own writes; two transactions are concurrent when each starts before the other commits, and of two concurrent transactions that write the same item, the second to commit aborts (first committer wins). Serialisable snapshot isolation adds a check at commit that aborts a transaction in a dangerous structure: one where it has read an item that a concurrent transaction writes, and has written an item that a concurrent transaction read.
A read by of a version older than one a concurrent writes is a read–write antidependency : in any equivalent serial order must come first, since it did not see ’s write. Snapshot isolation was first described by Berenson and his co-authors in 1995, and was implemented by Oracle and Microsoft SQL Server.
def commit(self):
s = self.store
for item in self.writes: # first committer wins
if s.versions[item][-1][0] > self.start:
return self.abort(f"{item} was changed by a concurrent commit")
if s.ssi:
others = self.concurrent()
out_ = [u for u in others if self.reads & set(u.writes)]
in_ = [u for u in others if u.reads & set(self.writes)]
if out_ and in_:
return self.abort("dangerous structure: rw-antidependencies in and out")
s.clock += 1
self.commit_ts, self.state = s.clock, "committed"
for item, value in self.writes.items():
s.versions[item].append((s.clock, value))
return f"{self.name} commits at {s.clock}"
ssi, the dangerous-structure check, then the new versions. code/bachelor-3/23-transactions-and-recovery/listings/mvcc.py$ python mvcc.py
-- lost update under snapshot isolation
T1 commits at 1
T2 aborts: copies was changed by a concurrent commit
copies: 2
-- write skew under snapshot isolation
T1 sees 2 on call
T2 sees 2 on call
T1 commits at 1
T2 commits at 2
on call now: nobody
-- the same under serialisable snapshot isolation
T1 sees 2 on call
T2 sees 2 on call
T1 aborts: dangerous structure: rw-antidependencies in and out
T2 commits at 1
on call now: ['alice']
The doctors are a write skew. Each transaction reads both rows, writes a different one, and commits; no item is written by both, so first committer wins does not fire, and no transaction saw a value another one had not committed. The result is the one no serial order gives: in a serial order the second doctor would have seen the first one go off.
Snapshot isolation rules out the lost update but allows write skew (exercise 23.12). Fekete and his co-authors gave in 2005 a theory of when a program can run non-serialisably under snapshot isolation, and ways to change a program so that it cannot; Cahill, Röhm and Fekete showed in 2008 that write skew is prevented by detecting and aborting dangerous triplets of concurrent transactions, and their method became the Serializable level of PostgreSQL 9.1. The check in mvcc.py is the simplest form of the idea: at its own commit, a transaction with antidependencies both in and out among concurrent transactions aborts. That aborts more often than needed, and it stops write skew, but it is not complete, since a transaction is checked only once, when it commits. Fekete’s read-only anomaly passes it. reads two accounts, and ; deposits 20 into and commits; begins; , which saw no deposit, withdraws 10 from with a penalty of 1 and commits, since no one has read yet; reads and and commits. The cycle has a write–read edge, and , its pivot, had committed before its incoming antidependency appeared; no serial order gives its view. Cahill’s method keeps the flags of committed transactions, and aborts here. A test of the chapter runs this schedule through mvcc.py and finds all three committed.
23.4 Isolation levels in practice
An isolation level names the anomalies a database rules out (Year 2 volume). The levels map onto the mechanisms of this chapter. Read uncommitted takes no read locks at all. Read committed takes a read lock only for the duration of each read, or reads a snapshot taken at each statement. Repeatable read keeps read and write locks to the end of the transaction, but does not lock ranges, so a repeated query can meet a phantom row inserted in between. Serializable needs more: a lock on every row a condition may cover, including rows that do not exist yet.
Definition 23.7 (Predicate lock)
A predicate lock locks the set of rows that satisfy a condition, such as member_id = 41, rather than rows by name: an insert or update producing a row that satisfies it conflicts with the lock. Locking the key range of an index that covers the condition is a cheaper, coarser form of it.
Berenson and his co-authors criticised the definitions of the SQL standard of 1992 with snapshot isolation: it shows none of the anomalies the standard forbids, yet it is not serialisable. A level defined by a list of forbidden anomalies is thus weaker than its name may suggest.
SQLite runs every transaction serialisably: what one connection changes is invisible to the others until it commits. In its default rollback-journal mode it locks the whole file. Readers hold SHARED locks, any number at once; a writer-to-be holds the single RESERVED lock while it prepares its changes in memory; to write the file at commit it needs the EXCLUSIVE lock, waiting in PENDING for the readers to finish. A plain BEGIN starts nothing until the first access, while BEGIN IMMEDIATE starts a write transaction at once and fails with SQLITE_BUSY if another one is active. In WAL mode a reader instead sees a snapshot of the database as it was when its read began; readers do not block the writer, nor the writer the readers, but there is one writer at a time. The script below drives two connections to one file from one Python program, step by step, with a busy timeout of zero, so that a step that would wait fails at once and the run is the same every time.
a = sqlite3.connect(path, timeout=0, isolation_level=None)
b = sqlite3.connect(path, timeout=0, isolation_level=None)
print(f"-- journal mode {mode}")
q = "SELECT copies FROM stock WHERE book = 'atlas'"
run(a, "A", "BEGIN IMMEDIATE")
run(a, "A", "UPDATE stock SET copies = 2 WHERE book = 'atlas'")
run(b, "B", "BEGIN IMMEDIATE")
run(b, "B", "BEGIN")
run(b, "B", q)
committed = run(a, "A", "COMMIT")
run(b, "B", q)
run(b, "B", "COMMIT")
if not committed:
run(a, "A", "COMMIT")
run(b, "B", q)
$ python sqlite_isolation.py
-- journal mode delete
A: BEGIN IMMEDIATE
A: UPDATE stock SET copies = 2 WHERE book = 'atlas'
B: BEGIN IMMEDIATE -> error: database is locked
B: BEGIN
B: SELECT copies FROM stock WHERE book = 'atlas' -> 3
A: COMMIT -> error: database is locked
B: SELECT copies FROM stock WHERE book = 'atlas' -> 3
B: COMMIT
A: COMMIT
B: SELECT copies FROM stock WHERE book = 'atlas' -> 2
-- journal mode wal
A: BEGIN IMMEDIATE
A: UPDATE stock SET copies = 2 WHERE book = 'atlas'
B: BEGIN IMMEDIATE -> error: database is locked
B: BEGIN
B: SELECT copies FROM stock WHERE book = 'atlas' -> 3
A: COMMIT
B: SELECT copies FROM stock WHERE book = 'atlas' -> 3
B: COMMIT
B: SELECT copies FROM stock WHERE book = 'atlas' -> 2
Some invariants span rows: the library allows a member at most five books out at once. Every program that lends books could check it, but the check is safer in the database, where no program can forget it.
Definition 23.8 (Trigger)
A trigger is a statement stored in the database and run automatically before or after each insertion, update or deletion on a given table, for each row affected; it can read the row through NEW and OLD and abort the statement that fired it.
CREATE TRIGGER five_books_out BEFORE INSERT ON loans
WHEN (SELECT count(*) FROM loans
WHERE member_id = NEW.member_id AND return_date IS NULL) >= 5
BEGIN
SELECT RAISE(ABORT, 'member already has five books out');
END;
$ python sqlrun.py trigger.sql
sql> SELECT count(*) AS out_now FROM loans WHERE member_id = 41 AND return_date IS NULL;
+---------+
| out_now |
+---------+
| 4 |
+---------+
(1 row)
sql> INSERT INTO loans (book_id, member_id, out_date, due_date)
...> VALUES (5, 41, '2025-12-02', '2025-12-23');
OK (1 row changed)
sql> INSERT INTO loans (book_id, member_id, out_date, due_date)
...> VALUES (6, 41, '2025-12-02', '2025-12-23');
Error: member already has five books out
sql> SELECT count(*) AS out_now FROM loans WHERE member_id = 41 AND return_date IS NULL;
+---------+
| out_now |
+---------+
| 5 |
+---------+
(1 row)
RAISE(ABORT, ...) ends the statement with an error, and the sixth row is not inserted. The trigger keeps its invariant against concurrent loans only because SQLite is serialisable; under snapshot isolation, two loans counted from the same snapshot could both pass the check, a write skew again.
23.5 Write-ahead logging and recovery
The buffer pool of Chapter 21 writes pages when it needs frames, not when transactions end. A page may thus reach the disk with changes of a transaction that has not committed (steal), and a committed transaction’s pages may still be only in memory (no force). After a crash, the disk holds a mixture, and a log must say how to repair it.
Definition 23.9 (Write-ahead log, undo record, redo record, log sequence number, checkpoint)
A write-ahead log is an append-only file of records describing every change, whose records reach the disk before the pages they describe. Each record has a log sequence number (LSN), increasing along the log, and each page carries the LSN of the last record applied to it, its page LSN. An update record carries a redo record part, the new value, to repeat the change, and an undo record part, the old value, to cancel it; a compensation log record, or CLR, logs an undo already done. A checkpoint is a record of the active transactions with their last LSNs, and of the dirty pages with, for each, the LSN of its first change not yet on disk (its recLSN), from which recovery can start reading.
Two rules make the log sufficient. The WAL rule: a page goes to disk only after every log record describing it. The commit rule: a transaction is committed once its commit record is on disk, so the log is flushed up to that record before the commit returns. Recovery then follows the three passes of ARIES, the algorithm of Mohan, Haderle, Lindsay, Pirahesh and Schwarz published in 1992, designed for steal and no force, and used by IBM Db2 and Microsoft SQL Server.
Definition 23.10 (ARIES recovery)
Analysis reads the log from the last checkpoint and rebuilds the table of transactions active at the crash, the losers, and the table of dirty pages. Redo repeats history: from the smallest recLSN, it reapplies every update and CLR whose page LSN shows it is not on its page, losers’ records included. Undo rolls the losers back, newest record first, writing a CLR for each update it undoes; the CLR’s undo_next points to the next record to undo, so that a CLR met later is never undone twice.
The mini database of minidb.py has eight items on four pages, a buffer pool that steals and does not force, a log flushed by the WAL rule and at commit, rollback with CLRs, and checkpoints. Every write to its simulated disk, of a log record or of a page, is an event after which the disk is copied: a crash after that event leaves exactly that copy.
def undo(log, pages, losers, say, crash_after=None):
"""Roll the losers back, newest record first, logging a CLR for each update
undone; a CLR met on the way sends the walk to its undo_next."""
lsn, by_lsn = max((r["lsn"] for r in log), default=0), {r["lsn"]: r for r in log}
todo, written = dict(losers), 0
while todo:
t = max(todo, key=todo.get)
r = by_lsn[todo[t]]
nxt = r["undo_next"] if r["kind"] == "clr" else r["prev"]
if r["kind"] == "update":
if written == crash_after:
return False # the crash: the CLRs logged so far are durable
lsn += 1
log.append(
{
"lsn": lsn,
"kind": "clr",
"txn": t,
"item": r["item"],
"after": r["before"],
"undo_next": nxt,
"prev": todo[t],
}
)
written += 1
p = pages[page_of(r["item"])]
p["items"][r["item"]], p["lsn"] = r["before"], lsn
say(f"undo {r['lsn']}: {r['item']} = {r['before']} (CLR {lsn})")
if nxt is None:
lsn += 1
log.append({"lsn": lsn, "kind": "end", "txn": t, "prev": todo.pop(t)})
else:
todo[t] = nxt
return True
def workload():
db = MiniDB(INITIAL)
db.update(1, "a", 10)
db.update(2, "c", 20)
db.update(1, "b", 11)
db.write_page(1) # steal: T2's uncommitted c goes to disk
db.commit(1)
db.update(3, "e", 30)
db.write_page(2) # steal again: T3's e goes to disk, then T3 aborts
db.update(2, "d", 21)
db.checkpoint()
db.update(4, "g", 40)
db.update(3, "f", 31)
db.rollback(3) # T3 aborts: its two updates are undone, with CLRs
db.write_page(2)
db.commit(2)
db.update(5, "h", 50)
db.update(4, "a", 41)
db.write_page(0)
db.write_page(3) # T4 and T5 never commit
db.update(5, "e", 51)
db.flush_log(db.lsn)
return db
$ python crash_all.py
crash 1, after log record 1 flushed committed [] ok: True
crash 2, after log record 2 flushed committed [] ok: True
crash 3, after page 1 written committed [] ok: True
crash 4, after log record 3 flushed committed [] ok: True
crash 5, after log record 4 flushed committed [1] ok: True
crash 6, after log record 5 flushed committed [1] ok: True
crash 7, after log record 6 flushed committed [1] ok: True
crash 8, after page 2 written committed [1] ok: True
crash 9, after log record 7 flushed committed [1] ok: True
crash 10, after log record 8 flushed committed [1] ok: True
crash 11, after log record 9 flushed committed [1] ok: True
crash 12, after log record 10 flushed committed [1] ok: True
crash 13, after log record 11 flushed committed [1] ok: True
crash 14, after log record 12 flushed committed [1] ok: True
crash 15, after page 2 written committed [1] ok: True
crash 16, after log record 13 flushed committed [1] ok: True
crash 17, after log record 14 flushed committed [1, 2] ok: True
crash 18, after log record 15 flushed committed [1, 2] ok: True
crash 19, after log record 16 flushed committed [1, 2] ok: True
crash 20, after log record 17 flushed committed [1, 2] ok: True
crash 21, after page 0 written committed [1, 2] ok: True
crash 22, after page 3 written committed [1, 2] ok: True
crash 23, after log record 18 flushed committed [1, 2] ok: True
23 of 23 crashes recover consistently; 2 disks were consistent before recovery
59 of 59 crashes during undo recover consistently
Theorem 23.11 (Recovery is correct)
Let transactions hold their exclusive locks to the end, as under strict two-phase locking, and let the WAL and commit rules hold. After a crash at any moment, analysis, redo and undo leave each item with the value of the last write to it by a transaction whose commit record is on disk, or its initial value if there is none.
Proof. After redo, every page holds the effect of every durable update and CLR, in log order. A page on disk holds the effect of the records with LSN at most its page LSN, all durable by the WAL rule. A durable record of page that is not on disk has above ’s page LSN, so was dirty from on: either was in the checkpoint’s dirty page table with a recLSN at most , or it was clean at the checkpoint, is later, and analysis adds with a recLSN at most . Redo reads from the smallest recLSN, meets and applies it, since ’s page LSN is below ; records already on the page are skipped by the same test. Records not on disk at the crash did not reach any page either, by the WAL rule.
Losers are exactly the transactions with durable updates and no durable commit or end record. This is what analysis computes from the checkpoint’s table and the records after it.
After undo, each item has its correct value. Take an item . Because exclusive locks are held to the end, the writes to come in blocks, one transaction at a time, each block ending in that transaction’s commit or in its complete rollback by CLRs before anyone else writes . After redo, holds the last durable write to it. If that write belongs to a committed transaction, or to a rollback already finished, is right: a finished rollback restored the value before its block. Otherwise the last block belongs to a loser , possibly partly rolled back already. Undo follows ’s chain from its last record; a CLR’s undo_next skips the updates already undone, and each remaining update of is undone in decreasing LSN order, ending with the value before ’s first write to : the value the previous block left, which is right by the same argument. Undoing several losers newest record first never interleaves wrongly, since their writes touch disjoint items while they are active. ∎
$ python recovery_trace.py
1 update txn=1 item=a before=0 after=10
2 update txn=2 item=c before=0 after=20
3 update txn=1 item=b before=0 after=11
4 commit txn=1
5 end txn=1
6 update txn=3 item=e before=0 after=30
7 update txn=2 item=d before=0 after=21
8 checkpoint att={2: 7, 3: 6} dpt={0: 1, 1: 7}
9 update txn=4 item=g before=0 after=40
10 update txn=3 item=f before=0 after=31
11 clr txn=3 item=f after=0 undo_next=6
12 clr txn=3 item=e after=0
13 end txn=3
14 commit txn=2
15 end txn=2
16 update txn=5 item=h before=0 after=50
17 update txn=4 item=a before=10 after=41
on disk, page 0: {'a': 41, 'b': 11}, page LSN 17
on disk, page 1: {'c': 20, 'd': 0}, page LSN 2
on disk, page 2: {'e': 0, 'f': 0}, page LSN 12
on disk, page 3: {'g': 40, 'h': 50}, page LSN 16
analysis: losers [4, 5], dirty pages {0: 1, 1: 7, 2: 10, 3: 9}
redo 7: d = 21
redo from LSN 1: 10 records skipped, already on disk
undo 17: a = 10 (CLR 18)
undo 16: h = 0 (CLR 19)
undo 9: g = 0 (CLR 21)
after recovery: {'a': 10, 'b': 11, 'c': 20, 'd': 21, 'e': 0, 'f': 0, 'g': 0, 'h': 0}
expected: {'a': 10, 'b': 11, 'c': 20, 'd': 21, 'e': 0, 'f': 0, 'g': 0, 'h': 0}
The trace shows why redo repeats the losers’ history too. Record 9, ’s write of , is on disk already, and record 16 as well; had either been missing, redo would have reapplied it, so that undo, which writes the old values and logged, starts from the state the log describes. A redo that skipped them would be fine here, but exercise 23.5 finds the one crash where skipping a loser’s CLR leaves a wrong value.
23.6 Exercises
Exercise 23.1 ★
Draw the precedence graph of each schedule and say whether it is conflict serialisable; if it is, give an equivalent serial order.
(a) .
(b) .
(c) .
Solution
Solution of Exercise 23.1.
(a) before gives ; before gives . The graph has a cycle: not serialisable. (b) before , and and before , all give , the only edge: serialisable, as . (c) before gives ; and before give ; before gives ; before gives . The cycle makes it not serialisable. A test checks the three verdicts with schedules.py.
Exercise 23.2 ★
Which of these schedules can the strict two-phase locking scheduler of Listing 23.2 run exactly as written, being ’s commit? (a) . (b) . (c) . (d) the interleaved schedule of Output 23.1 followed by . What does (d) show about the theorem of two-phase locking?
Solution
Solution of Exercise 23.2.
(a) Yes: both shared locks on coexist, and and are free. (b) No: needs an exclusive lock on while holds a shared one until ; would wait. (c) Yes: releases at . (d) No: comes after and before , while holds an exclusive lock on . Yet (d) is conflict serialisable, as . The theorem of two-phase locking is a sufficient condition only: the schedules two-phase locking can produce are a strict subset of the serialisable ones. A test runs the four schedules through the scheduler step by step.
Exercise 23.3 ★
Name the anomaly each trace shows, and being 10 at the start. (a) writes ; reads ; rolls back. (b) reads ; writes and commits; reads . (c) counts the rows with copies > 0: 3; inserts such a row and commits; counts again: 4. (d) and each read , which must stay at least 10, and each lowers a different item by 10; both commit.
Solution
Solution of Exercise 23.3.
(a) A dirty read: read a value that was never committed. (b) A non-repeatable read: the same item read twice in gives two values. (c) A phantom read: the set of rows satisfying the condition changed between two queries of . (d) A write skew: each read the same two items and wrote a different one; together they leave , below 10, though each alone kept the invariant.
Exercise 23.4 ★
Without looking at Output 23.4, predict for each journal mode which steps of Listing 23.4 fail, and what B’s three reads return. Explain each failure by the locks of SQLite, and why A’s commit is retried in one mode only.
Solution
Solution of Exercise 23.4.
Rollback-journal mode: B’s BEGIN IMMEDIATE fails, since A’s update holds the single RESERVED lock. B’s plain BEGIN succeeds and starts nothing; its SELECT takes a SHARED lock and reads 3, A’s change being only in A’s memory. A’s COMMIT fails, database is locked: writing the file needs the EXCLUSIVE lock, which waits for B’s SHARED lock to clear, and the busy timeout is 0. B reads 3 again and commits, releasing its lock; A’s retried commit succeeds, and B’s last read gives 2. WAL mode: B’s BEGIN IMMEDIATE fails as well, there being one writer at a time. B reads 3; A’s commit succeeds at once, since readers do not block the writer; B’s second read still gives 3, from the snapshot of its read transaction; after B’s commit, the new read gives 2. A’s commit is retried only in rollback-journal mode, the only mode in which it failed: a failed COMMIT leaves the transaction open, so the program must try again.
Exercise 23.5 ★★
ex5_redo.py recovers with a redo pass that reapplies only the records of committed transactions, since the others will be undone anyway. Run it on every crash point of Listing 23.7. At which crash does it go wrong, which item is wrong, and why? Why would the shortcut be correct if pages were never stolen?
Solution
Solution of Exercise 23.5.
ex5_redo.py prints one wrong recovery: crash 14, after log record 12 is flushed, where is left at 30 instead of 0. Page 2 was stolen at event 8 with ’s write (LSN 6). then rolled back: CLRs 11 (for ) and 12 (for ) are durable, but the end record 13 is not, and page 2 has not been written again. Analysis makes a loser whose last record is CLR 12, whose undo_next is empty: undo considers fully rolled back and does nothing. The shortcut skipped CLR 12, since did not commit, so nothing ever writes . At crash 13, one record earlier, ’s last record is CLR 11, whose undo_next is 6, and undo writes itself: the right value by luck. Undo trusts that redo has put every CLR back on its page; that is what repeating history guarantees. Without steal, no page on disk ever holds an uncommitted change or the state between an update and its CLR, so the committed records redone in log order give every item its committed value, and undoing the losers only rewrites values that are already there.
Exercise 23.6 ★★
Write WaitDie, a subclass of the scheduler of Listing 23.2 whose on_wait applies wait–die, a transaction’s number being its timestamp. Test that every wait it allows is of an older transaction for a younger one, on random programs, and count the orders of the doctors’ problem in which it aborts a transaction.
Solution
Solution of Exercise 23.6.
The class in exercises/ex6_waitdie.py overrides only on_wait. The scheduler has just recorded the holders that block in self.waits[t]; if one of them has a smaller number, is younger than it and dies, through abort, which releases its locks; otherwise waits. The test runs random programs of up to three transactions in random orders, wraps on_wait to record every wait the scheduler keeps, and checks that each goes from a smaller to a larger number and that no deadlock is ever reported. On the doctors’ problem, wait–die aborts a transaction in 52 of the 70 orders: the 48 deadlocks of Output 23.8, and 4 orders in which has written before starts, where ’s read of makes it die although waiting would have been safe.
Exercise 23.7 ★★
Show that the blind writes schedule of Output 23.1 is view serialisable but not conflict serialisable. Then prove that every conflict-serialisable schedule is view serialisable.
Solution
Solution of Exercise 23.7.
In the blind writes schedule, precedes , giving , and precedes , giving : a cycle, so it is not conflict serialisable. Nobody reads, and writes and last; the serial schedule has no read either and the same last writes, so the two are view-equivalent.
Facts used: the definitions of conflict and view equivalence. Let be conflict-equivalent to the serial . Two writes of the same item by different transactions conflict, and two by the same transaction keep their order, so the writes to each item come in the same order in and ; in particular the last write to is the same. A read reads from the last write to before it. A write to by another transaction conflicts with , so it is before in exactly when it is in ; a write by itself keeps its place relative to the read. The writes before are therefore the same set, in the same order, and the last of them is the same. and are thus view-equivalent, and is view serialisable.
Exercise 23.8 ★★
Two transactions each read then write the items in this order. Count by hand their serialisable interleavings for . Prove that an interleaving is conflict serialisable exactly when, on every item, one transaction’s two operations both come before the other’s, and the same transaction comes first on every item. Count by program for .
Solution
Solution of Exercise 23.8.
For the six interleavings of and are , (serial) and four others, such as , in which precedes and precedes : a cycle. Two are serialisable.
Facts used: Theorem 23.2. Conflicts occur only between the four operations on one item. If on item both operations of come before those of , the conflicts on give the single edge . Otherwise the two pairs interleave; say ’s read comes first. Then an operation of , hence , which is ’s first on , comes before , giving , while before gives : a cycle on that item alone. So the graph is acyclic exactly when no item interleaves and every item gives the same edge, that is when the same transaction comes first on every item. exercises/ex8_count.py counts both ways: 2, 12, 106 and 1,108 serialisable interleavings out of 6, 70, 924 and 12,870 for to 4; the fraction falls from 0.33 to 0.086.
Exercise 23.9 ★★
Prove that every schedule produced by strict two-phase locking is recoverable and has no cascading abort.
Solution
Solution of Exercise 23.9.
Facts used: strict two-phase locking keeps exclusive locks to commit or abort; a rollback restores the old values before its locks are released. Let read an item last written by another transaction . The read needs a shared lock on , granted only once ’s exclusive lock is released, at ’s commit or after its rollback. If rolled back, its write is undone before the release, so does not read it; hence committed before read . Every transaction thus reads only committed values. It follows that commits after every transaction it read from: the schedule is recoverable. And no abort can force another, since no transaction has read a value of an uncommitted one: there are no cascading aborts.
Exercise 23.10 ★★★
Prove that wait–die never lets a deadlock form, and that if an aborted transaction restarts with its original timestamp, every transaction eventually commits, on the assumption that each transaction, once it holds all its locks, finishes in finite time. Does the same hold for wound–wait?
Solution
Solution of Exercise 23.10.
Facts used: a deadlock is a cycle of the wait-for graph; assumptions: finitely many transactions, each lock granted to its waiting requesters in the order they asked, and a transaction holding all the locks it needs finishes in finite time. Under wait–die, an edge exists only when is older: a younger requester dies instead of waiting. Timestamps strictly increase along every path of the wait-for graph, so it has no cycle and no deadlock forms.
No transaction starves. Since an aborted transaction keeps its timestamp and the transactions are finitely many, order them by timestamp and argue by induction that each finishes, the older ones first. Let be the oldest of those not yet finished. never dies, since only a request to an older holder kills, and every older transaction has finished. When waits, it waits for younger holders; none of them ever waits for , and each chain of waits starting from them climbs in timestamps, so it is finite and ends at a transaction that is not waiting, which runs. A transaction that runs either finishes, releasing its locks, or dies, releasing them too; each lock that is queued for is thus released after finitely many steps and, being first in its queue among the transactions that keep their place, granted to . Then holds all its locks and finishes. Under wound–wait the same holds: edges go from younger to older, so there is no cycle; the oldest transaction never waits, since it wounds every younger holder in its way, and never dies, since only an older one could wound it.
Exercise 23.11 ★★★
Prove that recovery is idempotent under crashes during recovery: if recovery itself crashes after writing some CLRs, a new recovery from the extended log gives the same result as one uninterrupted recovery. crash_all.py checks it at 59 points.
Solution
Solution of Exercise 23.11.
Facts used: Theorem 23.11 and the form of a CLR. Let be the durable log at the first crash and the log extended by an interrupted recovery: followed by CLRs and end records, in the order undo wrote them. Recovery writes no commit record, so and have the same committed transactions. is itself a log the theorem applies to: each is a CLR for a loser’s update, its undo_next pointing to the next update of that loser not yet undone, exactly as a rollback in normal operation would have logged it; the pages on disk are older than or equal to what the first recovery produced, and their page LSNs tell which records they hold. A second recovery thus redoes including the CLRs, which puts back the state the first recovery reached, and then continues each loser’s chain from its last CLR’s undo_next: it never undoes an update twice, because CLRs are never undone and the chain skips what they covered. By the theorem it ends with the values of the transactions committed in , which are those of : the result of one uninterrupted recovery. By induction, any number of crashes during recovery gives the same result. crash_all.py crashes recovery before each of its CLRs at every crash point, 59 cases, and the test recovers each a third time.
Exercise 23.12 ★★★
Prove that snapshot isolation never allows a lost update: two concurrent transactions that both read an item and write it cannot both commit. Show by the doctors’ schedule that it allows write skew. Then prove the condition behind serialisable snapshot isolation: if an execution under snapshot isolation is not serialisable, some transaction has a read–write antidependency in and one out, both with concurrent transactions.
Solution
Solution of Exercise 23.12.
Facts used: the definition of snapshot isolation; an execution is serialisable when a serial order of its committed transactions makes every read see the same version. No lost update. Let and be concurrent, both writing , and let commit first. Being concurrent, commits after starts, so when commits, has a version newer than ’s start: first committer wins aborts . Write skew allowed. In the doctors’ schedule of Output 23.3, the two transactions write different rows, so neither commit finds a newer version of what it wrote; both commit, and nobody is on call, a state no serial order produces.
The condition. Draw an edge between committed transactions when reads or overwrites a version wrote, or when reads a version older than one wrote (a read–write antidependency). Every serial order with the same reads must follow these edges, and a topological order of an acyclic graph is such an order; so a non-serialisable execution has a cycle. For a write–read or write–write edge, committed before started: a read sees only versions committed before the reader’s start, and two concurrent writers of one item cannot both commit. For an antidependency between transactions that are not concurrent, the same holds, since if had committed before started, would have seen ’s version or a newer one. Take on the cycle the transaction that commits first, and its predecessors and . If the edge were not an antidependency between concurrent transactions, would commit before starts, so before commits, against the choice of . So and are concurrent, and starts before commits. If the edge were not an antidependency between concurrent transactions, would commit before starts, hence before commits, again against the choice of (if the cycle has length 2, , and would commit before starts, against their concurrency). So has an antidependency in, from , and one out, to , both with concurrent transactions: the dangerous structure.
23.7 Weekend problem
Problem 23.1
Weekend problem — Two doctors on call at the Brenmoor clinic
The Brenmoor clinic’s rule is that at least one of its two doctors, Alice and Bob, is on call at night. The rota is a table with one row per doctor; a doctor going off call runs a transaction of four steps: read Alice’s row, read Bob’s row, set their own row off if both were on call, commit. One evening both doctors ask to go off at the same moment. This problem runs every interleaving of their two transactions under several protocols and counts the nights the rule is broken.
def run_mvcc(order, ssi=False, materialise=False):
s = Store({"A": True, "B": True, "duty": 0}, ssi)
txns, step, seen = {}, {1: 0, 2: 0}, {1: 0, 2: 0}
for t in order:
if step[t] == 0:
txns[t] = s.begin(f"T{t}")
tx, k = txns[t], step[t]
if tx.state == "active":
if k < 2:
seen[t] += tx.read("AB"[k])
elif k == 2 and seen[t] == 2:
tx.write("AB"[t - 1], False)
if materialise: # both write one shared row: a write-write conflict
tx.write("duty", t)
elif k == 3:
tx.commit()
step[t] += 1
aborts = sum(tx.state == "aborted" for tx in txns.values())
return not (s.latest()["A"] or s.latest()["B"]), aborts
materialise, both transactions also write one shared row. code/bachelor-3/23-transactions-and-recovery/listings/doctors.py$ python doctors.py
protocol nobody on call aborts (of 70 orders)
snapshot isolation 68 0
SI, conflict materialised 0 68
serialisable SI 0 68
strict 2PL 0 48
Part I — The invariant.
- Write the two transactions as schedules of reads and writes, for Alice and for Bob, the write being conditional.
- Show that each transaction alone keeps the rule.
- Show that both serial orders keep it, and say what each doctor finds in each.
- How many interleavings of the two transactions are there, counted as orders of their eight steps?
- How many of them are serial?
- Draw the precedence graph of the interleaving . Is it serialisable?
Part II — Every interleaving.
- Under snapshot isolation, in which interleavings does each doctor see both on call?
- Why does first committer wins never fire here?
- How many interleavings break the rule under snapshot isolation, according to Output 23.8? Explain the number.
- Under strict two-phase locking, why does no interleaving break the rule?
- In which interleavings does a deadlock occur, and how many are there?
- Why do the other interleavings run without a deadlock?
Part III — The anomaly.
- Name the anomaly, and give the two read–write antidependencies of a broken night.
- Why does the dirty-read, non-repeatable-read and phantom check of an isolation level not see it?
- Would SQLite in WAL mode allow it, with each transaction started by a plain
BEGIN? WithBEGIN IMMEDIATE? - How would a trigger like Listing 23.5 fare against this anomaly under snapshot isolation?
- Suppose the rule were checked by a query
count(*) WHERE on_calland a third doctor could be inserted. Which anomaly would a lock on the two existing rows miss? - Which lock would stop it?
Part IV — The fixes.
- Materialise the conflict: both transactions also write one shared row of the rota. Why does snapshot isolation now abort 68 interleavings and break none?
- Serialisable snapshot isolation aborts the same 68 without the extra row. Which transaction does
mvcc.pyabort, and why? - Compare with two-phase locking: 48 aborts. Why fewer?
- Under wait–die, exercise 23.6 counts 52. Why more than 48?
- Which fix would you choose for the clinic, which runs this transaction twice a night?
- Sum up: out of the 70 interleavings, how many does snapshot isolation break, how many do the fixes break, and what do they cost in aborts?
Solution
Solution of Problem 23.1.
1. and , each write being done only if both reads found the doctor on call.
2. Alone, a transaction sets only its own row off, and only if both were on: the other doctor is still on call.
3. In the order , Alice sees both on and goes off; Bob then sees Alice off and stays on. The order is the mirror image. Exactly one doctor stays on call either way.
4. : the choice of the four positions of ’s steps among eight.
5. Two: all of then all of , and the reverse.
6. before gives ; before gives . A cycle: not serialisable.
7. Under snapshot isolation a transaction sees the other’s write only if the other committed before it started. thus sees Alice off only when all of comes before ’s first step, the serial order ; and symmetrically. In the 68 other interleavings both doctors see both on call.
8. First committer wins compares only the items written by both. writes and writes : there is no common item.
9. 68, every interleaving but the two serial ones: in each, both see both on call (answer 7), both write, and both commit (answer 8).
10. By Theorem 23.4 the committed transactions form a conflict-serialisable schedule, which leaves the database as a serial order would, and both serial orders keep the rule (answer 3). An aborted transaction changes nothing.
11. When ’s read of comes before ’s write of , and ’s read of before ’s write of : then waits for ’s shared lock on and for ’s shared lock on . The test counts these orders, 48, and checks that they are exactly the deadlocks of Output 23.8.
12. In the other 22, one write comes first: if writes before has read it, ’s first read waits for ’s commit, and the run is in effect the serial order ; if writes before reads it, waits for , and it is the order .
13. A write skew. read , which wrote, and read , which wrote: the antidependencies and , a cycle.
14. No transaction read an uncommitted value, none read the same row twice, and no set of rows changed under a query: each check concerns one item or one query. The anomaly lies in a constraint between two rows, which each transaction checked on its own snapshot.
15. No, in either case. In WAL mode there is one writer at a time, and with a plain BEGIN each transaction starts as a reader; the first to write becomes the writer, and when the second tries to write, another connection is modifying or has modified the database, so its upgrade to a write transaction fails with SQLITE_BUSY. With BEGIN IMMEDIATE the second transaction cannot even start until the first ends, as in Output 23.4, and then reads the first one’s write.
16. Badly: two loans for the same member, run concurrently, would each count the loans on their own snapshot, each find four, each insert a different row and commit, leaving six books out. It is a write skew again, through insertions.
17. A phantom: the count ranges over the rows satisfying the condition, and a newly inserted row was not among the rows locked.
18. A predicate lock on the condition on_call, or a lock on the index range that covers it, conflicting with any insertion or update that makes a row satisfy it.
19. In the 68 non-serial interleavings both transactions go off call, so both also write the shared row; they are concurrent, so the second to commit finds a newer version of that row and aborts. In the two serial ones the second transaction sees the first doctor off and writes nothing. No night is broken, and 68 transactions abort.
20. The transaction that, at its commit, has an antidependency in and one out with concurrent transactions. If the other transaction has already written its row, the first to commit is aborted, as in Output 23.3; otherwise the first commits, and the second, which then finds both antidependencies, is aborted. Exactly one aborts in each of the 68 interleavings.
21. Locking makes one transaction wait rather than abort whenever a write comes first (answer 12), and the waiting transaction then sees the other doctor off. That saves 20 of the 68 non-serial interleavings; only the 48 deadlocks abort.
22. Wait–die aborts at every request of a younger transaction for an older one’s lock, even without a cycle: in the 4 orders where reads and and writes before starts, ’s read of kills it, where two-phase locking with detection would let it wait.
23. At two transactions a night, aborts cost nothing: any of the three fixes, with the aborted transaction retried, keeps the rule. The simplest in practice is to run at a serialisable level, which SQLite gives by default; on a database offering only snapshot isolation, materialising the conflict in one row is the change that needs no special support.
24. Of the 70 interleavings, snapshot isolation breaks the rule in 68, all but the two serial ones. Materialising the conflict, serialisable snapshot isolation and strict two-phase locking break none. Their cost is 68 aborts for the first two, 48 deadlock aborts for two-phase locking with detection, and 52 for wait–die, each followed by a retry that then sees the other doctor off call.
Termos definidos neste capítulo
- ARIES recovery
- Conflicting operations, conflict serialisability, precedence graph, view serialisability, serial schedule
- Multiversion concurrency control, snapshot isolation, serialisable snapshot isolation
- Predicate lock
- Trigger
- Two-phase locking, strict two-phase locking, cascading abort, recoverable schedule
- Wait-for graph, wound–wait, wait–die
- Write-ahead log, undo record, redo record, log sequence number, checkpoint