Ciência da computação · Livro 5 · Graduação — Ano 3

University Computer Science — Year 3

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: R1(A)R_1(A) is a read of item AA by transaction T1T_1, W2(A)W_2(A) a write of it by T2T_2. 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 Ti→TjT_i \to T_j whenever an operation of TiT_i conflicts with a later operation of TjT_j. 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 SS is conflict-equivalent to the serial schedule S′S'. An edge Ti→TjT_i \to T_j comes from conflicting operations pp of TiT_i and qq of TjT_j with pp before qq in SS, hence in S′S', where every operation of TiT_i then precedes every operation of TjT_j. So every edge goes forwards in the order of S′S', and a cycle Ti1→⋯→Ti1T_{i_1} \to \cdots \to T_{i_1} would put Ti1T_{i_1} before itself.

Conversely, let the graph be acyclic and take a topological order of it; let S′S' run the transactions serially in that order, each with its operations in their order in SS. The two schedules have the same operations. Let pp of TiT_i and qq of TjT_j conflict, with pp before qq in SS. Then Ti→TjT_i \to T_j is an edge, TiT_i comes before TjT_j in the topological order, and pp comes before qq in S′S'. Every conflicting pair is thus ordered alike, and S′S' is conflict-equivalent to SS. ∎

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
Listing 23.1. The conflict test, the precedence graph, and a serial order found by repeatedly removing a transaction with no predecessor left. code/bachelor-3/23-transactions-and-recovery/listings/schedules.py
$ 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
Output 23.1. Six schedules judged by their graphs, and the 70 interleavings of two transactions that each read and write AA, then BB: only 12 pass.

The interleaved schedule passes: T2T_2 touches AA only after T1T_1 is done with it, and BB likewise. The lost update fails: both read AA 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 precedence graph of the schedule R_1(A)\,W_2(A)\,R_2(B)\,W_3(B)\,R_3(C)\,W_1(C). Each edge is labelled with the conflict that creates it. The cycle means that no serial order has the same conflicts: T_1 would have to come before T_2, T_2 before T_3 and T_3 before T_1.
The precedence graph of the schedule R1(A) W2(A) R2(B) W3(B) R3(C) W1(C)R_1(A)\,W_2(A)\,R_2(B)\,W_3(B)\,R_3(C)\,W_1(C). Each edge is labelled with the conflict that creates it. The cycle means that no serial order has the same conflicts: T1T_1 would have to come before T2T_2, T2T_2 before T3T_3 and T3T_3 before T1T_1.

The last schedule, blind writes, fails the test too, yet it is view serialisable: no transaction reads, and T3T_3 writes both items last, as in the serial order T1,T2,T3T_1, T_2, T_3. 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 Ti→TjT_i \to T_j be an edge of the precedence graph: an operation pp of TiT_i on an item xx conflicts with a later operation qq of TjT_j on xx. At least one of them is a write, so the two locks on xx are incompatible, and TjT_j obtained its lock only after TiT_i released its own (a shared lock upgraded to exclusive counts as an acquisition). Call ℓi\ell_i and ℓj\ell_j the lock points. By two-phase locking TiT_i released nothing before ℓi\ell_i, so ℓi≤\ell_i \le the release of TiT_i’s lock on xx << the acquisition of TjT_j’s lock on x≤ℓjx \le \ell_j. 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. ∎

Locks held by one transaction over time. Under two-phase locking the count only grows until the lock point, then only falls. Strict two-phase locking keeps every lock until the commit and drops them all at once, so no other transaction ever reads a value that might still be rolled back.
Locks held by one transaction over time. Under two-phase locking the count only grows until the lock point, then only falls. Strict two-phase locking keeps every lock until the commit and drops them all at once, so no other transaction ever reads a value that might still be rolled back.

Releasing locks early, as on the left, lets another transaction read a write of TiT_i before TiT_i commits; if TiT_i 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
Listing 23.2. The lock manager’s two decisions: who blocks a request, and what a step does. A commit releases everything at once: strict two-phase locking. code/bachelor-3/23-transactions-and-recovery/listings/twopl.py

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 Ti→TjT_i \to T_j when TiT_i waits for a lock that TjT_j 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
Output 23.2. Three runs. Without shared items nothing waits; when T2T_2 wants AA, it waits for T1T_1’s commit; when each holds what the other needs, the cycle is found and the younger transaction aborted.

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 TiT_i of a version older than one a concurrent TjT_j writes is a read–write antidependency Ti→TjT_i \to T_j: in any equivalent serial order TiT_i must come first, since it did not see TjT_j’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}"
Listing 23.3. Commit under snapshot isolation: first committer wins, then, with 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']
Output 23.3. Two transactions each take a copy of a book: the second commit aborts. Two doctors each go off call because they saw the other on: both commit, and nobody is on call. Serialisable snapshot isolation aborts one of them.

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.

Write skew under snapshot isolation. Each transaction reads the snapshot taken at its start, so neither sees the other’s write; the items written are different, so both commit. The dashed arrows are the two read–write antidependencies, from T_1’s read of B to T_2’s write of it and from T_2’s read of A to T_1’s write; one each way, they form the cycle that serialisable snapshot isolation looks for.
Write skew under snapshot isolation. Each transaction reads the snapshot taken at its start, so neither sees the other’s write; the items written are different, so both commit. The dashed arrows are the two read–write antidependencies, from T1T_1’s read of BB to T2T_2’s write of it and from T2T_2’s read of AA to T1T_1’s write; one each way, they form the cycle that serialisable snapshot isolation looks for.

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. T2T_2 reads two accounts, X=0X = 0 and Y=0Y = 0; T1T_1 deposits 20 into YY and commits; T3T_3 begins; T2T_2, which saw no deposit, withdraws 10 from XX with a penalty of 1 and commits, since no one has read XX yet; T3T_3 reads X=0X = 0 and Y=20Y = 20 and commits. The cycle T2→T1→T3→T2T_2 \to T_1 \to T_3 \to T_2 has a write–read edge, and T2T_2, its pivot, had committed before its incoming antidependency appeared; no serial order gives T3T_3 its view. Cahill’s method keeps the flags of committed transactions, and aborts T3T_3 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)
Listing 23.4. The same steps in both journal modes: A updates, B tries to write and then reads, A commits while B reads. code/bachelor-3/23-transactions-and-recovery/listings/sqlite_isolation.py
$ 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
Output 23.4. In rollback-journal mode, A cannot commit while B holds its SHARED lock, and commits after B ends. In WAL mode A commits at once, and B keeps reading 3 from its snapshot until it ends.

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;
Listing 23.5. A trigger that refuses a sixth loan to the same member. code/bachelor-3/23-transactions-and-recovery/listings/trigger.sql
$ 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)
Output 23.5. Member 41 borrows four books, then a fifth; the sixth is refused, and the count stays at five. Some lines are left out.

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
Listing 23.6. Undo: the losers’ records newest first, each update undone and logged as a CLR; a crash during recovery is injected before a CLR. code/bachelor-3/23-transactions-and-recovery/listings/minidb.py
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
Listing 23.7. The workload: five transactions, two stolen pages, a checkpoint, a rollback, two commits; T4T_4 and T5T_5 never commit. code/bachelor-3/23-transactions-and-recovery/listings/crash_all.py
$ 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
Output 23.6. A crash after each of the 23 writes to the disk, recovered each time: always the writes of the committed transactions and no others. Before recovery only the two earliest disks were right. A second crash during undo, at each of 59 points, recovers too.

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 rr of page PP that is not on disk has lsn(r)\mathit{lsn}(r) above PP’s page LSN, so PP was dirty from rr on: either PP was in the checkpoint’s dirty page table with a recLSN at most lsn(r)\mathit{lsn}(r), or it was clean at the checkpoint, rr is later, and analysis adds PP with a recLSN at most lsn(r)\mathit{lsn}(r). Redo reads from the smallest recLSN, meets rr and applies it, since PP’s page LSN is below lsn(r)\mathit{lsn}(r); 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 xx. Because exclusive locks are held to the end, the writes to xx 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 xx. After redo, xx holds the last durable write to it. If that write belongs to a committed transaction, or to a rollback already finished, xx is right: a finished rollback restored the value before its block. Otherwise the last block belongs to a loser LL, possibly partly rolled back already. Undo follows LL’s chain from its last record; a CLR’s undo_next skips the updates already undone, and each remaining update of xx is undone in decreasing LSN order, ending with the value before LL’s first write to xx: 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}
Output 23.7. The durable log at crash 22, after page 3 is written, the four pages on disk, and the three passes. Redo reapplies the one record not on disk, T2T_2’s committed write of dd; undo cancels T4T_4 and T5T_5.
The log of the recovery trace, record by record: u_i an update by T_i, c_i a commit, e_i an end, ck the checkpoint (shaded), clr the compensation records of T_3’s rollback. Analysis reads from the checkpoint, redo from LSN 1, and undo walks back through the losers’ updates 17, 16 and 9.
The log of the recovery trace, record by record: uiu_i an update by TiT_i, cic_i a commit, eie_i an end, ck the checkpoint (shaded), clr the compensation records of T3T_3’s rollback. Analysis reads from the checkpoint, redo from LSN 1, and undo walks back through the losers’ updates 17, 16 and 9.

The trace shows why redo repeats the losers’ history too. Record 9, T4T_4’s write of gg, 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 T4T_4 and T5T_5 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) R1(A) R2(B) W1(B) W2(A)R_1(A)\,R_2(B)\,W_1(B)\,W_2(A).
(b) R1(A) W1(A) R2(A) R1(B) W1(B) W2(B)R_1(A)\,W_1(A)\,R_2(A)\,R_1(B)\,W_1(B)\,W_2(B).
(c) R2(A) R1(B) W2(A) R3(A) W1(B) W3(B) R2(B)R_2(A)\,R_1(B)\,W_2(A)\,R_3(A)\,W_1(B)\,W_3(B)\,R_2(B).

Solution

Solution of Exercise 23.1.

(a) R1(A)R_1(A) before W2(A)W_2(A) gives T1→T2T_1 \to T_2; R2(B)R_2(B) before W1(B)W_1(B) gives T2→T1T_2 \to T_1. The graph has a cycle: not serialisable. (b) W1(A)W_1(A) before R2(A)R_2(A), and R1(B)R_1(B) and W1(B)W_1(B) before W2(B)W_2(B), all give T1→T2T_1 \to T_2, the only edge: serialisable, as T1,T2T_1, T_2. (c) W2(A)W_2(A) before R3(A)R_3(A) gives T2→T3T_2 \to T_3; R1(B)R_1(B) and W1(B)W_1(B) before W3(B)W_3(B) give T1→T3T_1 \to T_3; W1(B)W_1(B) before R2(B)R_2(B) gives T1→T2T_1 \to T_2; W3(B)W_3(B) before R2(B)R_2(B) gives T3→T2T_3 \to T_2. The cycle T2→T3→T2T_2 \to T_3 \to T_2 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, CiC_i being TiT_i’s commit? (a) R1(A) R2(A) W1(B) W2(C) C1 C2R_1(A)\,R_2(A)\,W_1(B)\,W_2(C)\,C_1\,C_2. (b) R1(A) W2(A) C1 C2R_1(A)\,W_2(A)\,C_1\,C_2. (c) W1(A) C1 R2(A) W2(A) C2W_1(A)\,C_1\,R_2(A)\,W_2(A)\,C_2. (d) the interleaved schedule of Output 23.1 followed by C1 C2C_1\,C_2. What does (d) show about the theorem of two-phase locking?

Solution

Solution of Exercise 23.2.

(a) Yes: both shared locks on AA coexist, and BB and CC are free. (b) No: W2(A)W_2(A) needs an exclusive lock on AA while T1T_1 holds a shared one until C1C_1; T2T_2 would wait. (c) Yes: T1T_1 releases AA at C1C_1. (d) No: R2(A)R_2(A) comes after W1(A)W_1(A) and before C1C_1, while T1T_1 holds an exclusive lock on AA. Yet (d) is conflict serialisable, as T1,T2T_1, T_2. 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, xx and yy being 10 at the start. (a) T1T_1 writes x=20x = 20; T2T_2 reads x=20x = 20; T1T_1 rolls back. (b) T1T_1 reads x=10x = 10; T2T_2 writes x=20x = 20 and commits; T1T_1 reads x=20x = 20. (c) T1T_1 counts the rows with copies > 0: 3; T2T_2 inserts such a row and commits; T1T_1 counts again: 4. (d) T1T_1 and T2T_2 each read x+y=20x + y = 20, 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: T2T_2 read a value that was never committed. (b) A non-repeatable read: the same item read twice in T1T_1 gives two values. (c) A phantom read: the set of rows satisfying the condition changed between two queries of T1T_1. (d) A write skew: each read the same two items and wrote a different one; together they leave x+y=0x + y = 0, 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 ee is left at 30 instead of 0. Page 2 was stolen at event 8 with T3T_3’s write e=30e = 30 (LSN 6). T3T_3 then rolled back: CLRs 11 (for ff) and 12 (for ee) are durable, but the end record 13 is not, and page 2 has not been written again. Analysis makes T3T_3 a loser whose last record is CLR 12, whose undo_next is empty: undo considers T3T_3 fully rolled back and does nothing. The shortcut skipped CLR 12, since T3T_3 did not commit, so nothing ever writes e=0e = 0. At crash 13, one record earlier, T3T_3’s last record is CLR 11, whose undo_next is 6, and undo writes e=0e = 0 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 tt in self.waits[t]; if one of them has a smaller number, tt is younger than it and dies, through abort, which releases its locks; otherwise tt 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 T1T_1 has written AA before T2T_2 starts, where T2T_2’s read of AA 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, W1(A)W_1(A) precedes W2(A)W_2(A), giving T1→T2T_1 \to T_2, and W2(B)W_2(B) precedes W1(B)W_1(B), giving T2→T1T_2 \to T_1: a cycle, so it is not conflict serialisable. Nobody reads, and T3T_3 writes AA and BB last; the serial schedule T1,T2,T3T_1, T_2, T_3 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 SS be conflict-equivalent to the serial S′S'. 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 xx come in the same order in SS and S′S'; in particular the last write to xx is the same. A read Rj(x)R_j(x) reads from the last write to xx before it. A write to xx by another transaction conflicts with Rj(x)R_j(x), so it is before Rj(x)R_j(x) in SS exactly when it is in S′S'; a write by TjT_j itself keeps its place relative to the read. The writes before Rj(x)R_j(x) are therefore the same set, in the same order, and the last of them is the same. SS and S′S' are thus view-equivalent, and SS is view serialisable.

Exercise 23.8 ★★

Two transactions each read then write the items x1,…,xkx_1, \ldots, x_k in this order. Count by hand their serialisable interleavings for k=1k = 1. 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 k≤4k \le 4.

Solution

Solution of Exercise 23.8.

For k=1k = 1 the six interleavings of R1W1R_1 W_1 and R2W2R_2 W_2 are R1W1R2W2R_1 W_1 R_2 W_2, R2W2R1W1R_2 W_2 R_1 W_1 (serial) and four others, such as R1R2W1W2R_1 R_2 W_1 W_2, in which R1R_1 precedes W2W_2 and R2R_2 precedes W1W_1: a cycle. Two are serialisable.

Facts used: Theorem 23.2. Conflicts occur only between the four operations on one item. If on item xix_i both operations of T1T_1 come before those of T2T_2, the conflicts on xix_i give the single edge T1→T2T_1 \to T_2. Otherwise the two pairs interleave; say T1T_1’s read comes first. Then an operation of T2T_2, hence R2(xi)R_2(x_i), which is T2T_2’s first on xix_i, comes before W1(xi)W_1(x_i), giving T2→T1T_2 \to T_1, while R1(xi)R_1(x_i) before W2(xi)W_2(x_i) gives T1→T2T_1 \to T_2: 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 k=1k = 1 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 TjT_j read an item xx last written by another transaction TiT_i. The read needs a shared lock on xx, granted only once TiT_i’s exclusive lock is released, at TiT_i’s commit or after its rollback. If TiT_i rolled back, its write is undone before the release, so TjT_j does not read it; hence TiT_i committed before TjT_j read xx. Every transaction thus reads only committed values. It follows that TjT_j 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 Ti→TjT_i \to T_j exists only when TiT_i 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 TT be the oldest of those not yet finished. TT never dies, since only a request to an older holder kills, and every older transaction has finished. When TT waits, it waits for younger holders; none of them ever waits for TT, 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 TT is queued for is thus released after finitely many steps and, TT being first in its queue among the transactions that keep their place, granted to TT. Then TT 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 LL be the durable log at the first crash and L′L' the log extended by an interrupted recovery: LL followed by CLRs c1,…,cmc_1, \ldots, c_m and end records, in the order undo wrote them. Recovery writes no commit record, so LL and L′L' have the same committed transactions. L′L' is itself a log the theorem applies to: each cic_i 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 L′L' 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 L′L', which are those of LL: 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 T1T_1 and T2T_2 be concurrent, both writing xx, and let T1T_1 commit first. Being concurrent, T1T_1 commits after T2T_2 starts, so when T2T_2 commits, xx has a version newer than T2T_2’s start: first committer wins aborts T2T_2. 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 Ti→TjT_i \to T_j between committed transactions when TjT_j reads or overwrites a version TiT_i wrote, or when TiT_i reads a version older than one TjT_j 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, TiT_i committed before TjT_j 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 TjT_j had committed before TiT_i started, TiT_i would have seen TjT_j’s version or a newer one. Take on the cycle the transaction TT that commits first, and its predecessors T′→TT' \to T and T′′→T′T'' \to T'. If the edge T′→TT' \to T were not an antidependency between concurrent transactions, T′T' would commit before TT starts, so before TT commits, against the choice of TT. So T′T' and TT are concurrent, and T′T' starts before TT commits. If the edge T′′→T′T'' \to T' were not an antidependency between concurrent transactions, T′′T'' would commit before T′T' starts, hence before TT commits, again against the choice of TT (if the cycle has length 2, T′′=TT'' = T, and TT would commit before T′T' starts, against their concurrency). So T′T' has an antidependency in, from T′′T'', and one out, to TT, 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
Listing 23.8. One interleaving under snapshot isolation; with 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
Output 23.8. Every interleaving of the two transactions under four protocols: how often nobody is left on call, and how often a transaction is aborted.

Part I — The invariant.

  1. Write the two transactions as schedules of reads and writes, T1T_1 for Alice and T2T_2 for Bob, the write being conditional.
  2. Show that each transaction alone keeps the rule.
  3. Show that both serial orders keep it, and say what each doctor finds in each.
  4. How many interleavings of the two transactions are there, counted as orders of their eight steps?
  5. How many of them are serial?
  6. Draw the precedence graph of the interleaving R1(A) R2(A) R1(B) R2(B) W1(A) W2(B)R_1(A)\,R_2(A)\,R_1(B)\,R_2(B)\,W_1(A)\,W_2(B). Is it serialisable?

Part II — Every interleaving.

  1. Under snapshot isolation, in which interleavings does each doctor see both on call?
  2. Why does first committer wins never fire here?
  3. How many interleavings break the rule under snapshot isolation, according to Output 23.8? Explain the number.
  4. Under strict two-phase locking, why does no interleaving break the rule?
  5. In which interleavings does a deadlock occur, and how many are there?
  6. Why do the other interleavings run without a deadlock?

Part III — The anomaly.

  1. Name the anomaly, and give the two read–write antidependencies of a broken night.
  2. Why does the dirty-read, non-repeatable-read and phantom check of an isolation level not see it?
  3. Would SQLite in WAL mode allow it, with each transaction started by a plain BEGIN? With BEGIN IMMEDIATE?
  4. How would a trigger like Listing 23.5 fare against this anomaly under snapshot isolation?
  5. Suppose the rule were checked by a query count(*) WHERE on_call and a third doctor could be inserted. Which anomaly would a lock on the two existing rows miss?
  6. Which lock would stop it?

Part IV — The fixes.

  1. Materialise the conflict: both transactions also write one shared row of the rota. Why does snapshot isolation now abort 68 interleavings and break none?
  2. Serialisable snapshot isolation aborts the same 68 without the extra row. Which transaction does mvcc.py abort, and why?
  3. Compare with two-phase locking: 48 aborts. Why fewer?
  4. Under wait–die, exercise 23.6 counts 52. Why more than 48?
  5. Which fix would you choose for the clinic, which runs this transaction twice a night?
  6. 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. T1=R1(A) R1(B) W1(A) C1T_1 = R_1(A)\,R_1(B)\,W_1(A)\,C_1 and T2=R2(A) R2(B) W2(B) C2T_2 = R_2(A)\,R_2(B)\,W_2(B)\,C_2, 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 T1,T2T_1, T_2, Alice sees both on and goes off; Bob then sees Alice off and stays on. The order T2,T1T_2, T_1 is the mirror image. Exactly one doctor stays on call either way.

4. (84)=70\binom{8}{4} = 70: the choice of the four positions of T1T_1’s steps among eight.

5. Two: all of T1T_1 then all of T2T_2, and the reverse.

6. R2(A)R_2(A) before W1(A)W_1(A) gives T2→T1T_2 \to T_1; R1(B)R_1(B) before W2(B)W_2(B) gives T1→T2T_1 \to T_2. A cycle: not serialisable.

7. Under snapshot isolation a transaction sees the other’s write only if the other committed before it started. T2T_2 thus sees Alice off only when all of T1T_1 comes before T2T_2’s first step, the serial order T1,T2T_1, T_2; and symmetrically. In the 68 other interleavings both doctors see both on call.

8. First committer wins compares only the items written by both. T1T_1 writes AA and T2T_2 writes BB: 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 T2T_2’s read of AA comes before T1T_1’s write of AA, and T1T_1’s read of BB before T2T_2’s write of BB: then T1T_1 waits for T2T_2’s shared lock on AA and T2T_2 for T1T_1’s shared lock on BB. 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 T1T_1 writes AA before T2T_2 has read it, T2T_2’s first read waits for T1T_1’s commit, and the run is in effect the serial order T1,T2T_1, T_2; if T2T_2 writes BB before T1T_1 reads it, T1T_1 waits for T2T_2, and it is the order T2,T1T_2, T_1.

13. A write skew. T1T_1 read BB, which T2T_2 wrote, and T2T_2 read AA, which T1T_1 wrote: the antidependencies T1→T2T_1 \to T_2 and T2→T1T_2 \to T_1, 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 T1T_1 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 T1T_1 reads AA and BB and writes AA before T2T_2 starts, T2T_2’s read of AA 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

Ver todos os 1050 termos do glossário