Algorithm Search⌘K

Algorithmcore

Conservative two-phase locking

Also called static 2PL, conservative 2PL.

Two-phase locking in which a transaction declares its read and write sets and gets all its locks at once before its first action. A waiting transaction holds nothing, so there is no deadlock.

Time
O(w s k) expected per-admission-pass
Space
O(k s) extra
Where
k = the number of active transactions; s = the number of items that one transaction declares; w = the number of waiting transactions
Properties
deterministiconline

Conservative two-phase locking, also called static 2PL, is a form of two-phase locking in which each transaction declares, when it begins, the items it will read and the items it will write. The scheduler then grants all its locks in one step, or none of them. A transaction that cannot get all its locks waits and holds nothing. So no transaction ever waits while it holds a lock, one of the four Coffman conditions never holds, and there are no deadlocks. Every transaction takes its last lock before its first action, so it is two-phase, and the schedule is conflict serializable in the order in which the transactions got their locks. The price is that the read and write sets must be known in advance, and that locks are held from the start.

In plain words

Think of a kitchen where each cook must say, before starting a dish, which pots and knives the dish needs. The cook gets all of them at once, or waits with empty hands until all of them are free. A cook never holds one pot while waiting for another, so two cooks can never each hold what the other one wants.

A cook who waits keeps a place in a line. A new cook who wants one of the same tools may not take it first, so nobody waits forever. Because each cook has every tool before the first step, the kitchen works as if the cooks had cooked one after the other, in the order in which they got their tools.

The problem

The input is a set of transactions, each given as a program of reads ri(x)r_i(x) and writes wi(x)w_i(x) followed by a commit cic_i or an abort aia_i. The actions arrive interleaved, and the scheduler decides when each transaction may start. The scheduler must make the committed projection of the output schedule conflict serializable, and it should avoid deadlocks, so that it never has to abort a transaction to break one.

Here the scheduler knows the whole read set and write set of a transaction when the transaction begins. This is the main assumption of the method, and it is what basic two-phase locking does not need. The model is one site with a lock table in main memory, with S (shared) and X (exclusive) locks: two locks of different transactions on the same item conflict unless both are S.

The algorithm

  1. BEGIN(T, program)
  2. 1L(T) ← {(x, X) : T writes x} ∪ {(x, S) : T reads x and does not write it}
  3. 2append T to the wait list W
  4. 3ADMIT()
  5. ADMIT() ▷ after each begin and each release
  6. 4for each T in W, in order of arrival do
  7. 5if each (x, m) in L(T) conflicts with no lock that another transaction holds,
  8. and with no lock that a transaction before T in W wants then
  9. 6remove T from W; grant all of L(T) to T ▷ the lock point of T
  10. else remember the locks of T as wanted
  11. ACCESS(T, p(x)) ▷ p is r or w
  12. 7check that T holds a lock on x that covers p, then run p(x)
  13. 8if not strict and T has no later access to x then release x; ADMIT()
  14. END(T) ▷ c or a
  15. 9release all locks of T; ADMIT()

The scheduler runs actions of admitted transactions only. A transaction that reads and writes the same item gets X at once, so there are no lock conversions. The test of line L5 against the earlier waiters is a choice of this page that keeps the wait list fair: a new transaction can pass a waiter only when the two do not conflict. Without it, a stream of readers could keep a writer waiting forever.

The flag strict selects one of two release rules. With strict = true, every lock is held until commit or abort (line L9), which is conservative strict 2PL. With strict = false, a lock is released after the last access of the transaction to the item (line L8). The transaction is still two-phase, because its lock point came before its first action.

Example

Admission in order. Let T1=r1(x) c1T_1 = r_1(x)\, c_1, T2=r2(y) w2(x) c2T_2 = r_2(y)\, w_2(x)\, c_2, T3=r3(x) c3T_3 = r_3(x)\, c_3 and T4=w4(z) c4T_4 = w_4(z)\, c_4 begin in this order.

step event locks held wait list
1 T1T_1 begins and gets S on xx 1: S xx
2 T2T_2 begins; X on xx conflicts with T1T_1, so it gets nothing 1: S xx 2
3 T3T_3 begins; S on xx fits T1T_1 but conflicts with the wanted X of T2T_2 1: S xx 2, 3
4 T4T_4 begins and gets X on zz; it conflicts with nobody 1: S xx; 4: X zz 2, 3
5 T1T_1 ends; T2T_2 gets S on yy and X on xx 2: S yy, X xx; 4: X zz 3
6 T2T_2 ends; T3T_3 gets S on xx 3: S xx; 4: X zz

At step 2, T2T_2 does not take S on yy while it waits for xx. After step 4 the wait-for graph has the edges 2→12 \to 1 (a held lock) and 3→23 \to 2 (an earlier waiter). The lock points are in the order T1,T4,T2,T3T_1, T_4, T_2, T_3.

The deadlock of basic 2PL. Let T1=r1(x) w1(y) c1T_1 = r_1(x)\, w_1(y)\, c_1 and T2=r2(y) w2(x) c2T_2 = r_2(y)\, w_2(x)\, c_2, with the actions offered in the order 1,2,1,2,1,21, 2, 1, 2, 1, 2. Under basic 2PL, T1T_1 locks xx, T2T_2 locks yy, and each then waits for the other: a deadlock. Under conservative 2PL, T1T_1 gets S on xx and X on yy at once. T2T_2 needs X on xx and S on yy, so it waits with nothing. The output is r1(x) w1(y) c1 r2(y) w2(x) c2r_1(x)\, w_1(y)\, c_1\, r_2(y)\, w_2(x)\, c_2, a serial schedule.

Early release. Let T1=w1(x) r1(y) c1T_1 = w_1(x)\, r_1(y)\, c_1 and T2=r2(x) c2T_2 = r_2(x)\, c_2, offered in the order 1,2,2,1,11, 2, 2, 1, 1. With strict = false, T1T_1 releases xx right after w1(x)w_1(x), since it does not touch xx again. T2T_2 is admitted, and the output is w1(x) r2(x) c2 r1(y) c1w_1(x)\, r_2(x)\, c_2\, r_1(y)\, c_1. It is conflict serializable, but not recoverable: T2T_2 read from T1T_1 and committed first. With strict = true, T2T_2 waits until c1c_1, and the output is w1(x) r1(y) c1 r2(x) c2w_1(x)\, r_1(y)\, c_1\, r_2(x)\, c_2.

Correctness

There are four claims. The proofs are on the proof page.

  • Serializability. Each transaction gets all its locks before its first action and releases none before then, so every transaction is two-phase, and its lock point is the moment of line L6. By the two-phase locking theorem, the committed projection is conflict equivalent to the serial schedule in the order of the lock points, which is the order of admission.
  • No deadlock. A waiting transaction holds no lock. An edge T→UT \to U of the wait-for graph goes from a waiter to a holder, or from a waiter to an earlier waiter. A holder has no edge out of it, because it does not wait, and the edges between waiters go back in the order of arrival. So the graph has no cycle.
  • No starvation. The first waiter conflicts with no earlier waiter, so it waits only for holders. A new transaction that conflicts with it is not admitted before it. The holders never wait, so if every admitted transaction ends, the first waiter is admitted. By induction along the wait list, every transaction is admitted.
  • Strictness. With strict = true, every X lock is held until the end of its transaction, so the output schedule is strict.
Proof: Conservative 2PL gives conflict serializable schedules in admission order, never deadlocks and never starvesfull

Two lock modes of different transactions conflict unless both are S. For a transaction TT, L(T)L(T) is its declared lock set from line L1: X on each item it writes and S on each item it only reads. So the lock of TT on xx covers every action of TT on xx. A transaction is admitted at line L6, and the moment of line L6 is its lock point LP(T)\mathrm{LP}(T). A transaction is waiting while it is in the list WW. The scheduler runs the actions of admitted transactions only, and line L7 rejects an action that its locks do not cover.

Lemma 1 (safety). At every moment, two different transactions never hold conflicting locks on the same item.

Proof. Locks are granted only at line L6, and only when no lock of L(T)L(T) conflicts with a lock held by another transaction. Other steps only release locks. So by induction over the steps, the claim holds after each step. □\square

Lemma 2 (two-phase). Each transaction gets all its locks at its lock point and gets no lock after it. Each lock covers its actions, from before the first action on the item to after the last one.

Proof. Line L6 grants all of L(T)L(T) in one step, and no other line grants a lock. An action of TT runs only after admission. A lock on xx is released at line L8 only after the last access of TT to xx, or at line L9 at the end of TT. □\square

Theorem 1 (serializability). The committed projection of every output schedule is conflict equivalent to the serial schedule of its committed transactions in the order of their lock points.

Proof. Let pi(x)p_i(x) come before qj(x)q_j(x) in the schedule, i≠ji \ne j, with at least one of them a write. Their locks on xx conflict, because at least one is X, and each lock is held while its action runs (Lemma 2). By Lemma 1 they are not held at the same time, so TiT_i released its lock on xx before TjT_j got its lock on xx. By Lemma 2, LP(Ti)\mathrm{LP}(T_i) is not later than the moment when TiT_i got its lock on xx, which is before the release, and TjT_j got its lock on xx at LP(Tj)\mathrm{LP}(T_j). So LP(Ti)<LP(Tj)\mathrm{LP}(T_i) < \mathrm{LP}(T_j). Every pair of conflicting actions of committed transactions is therefore in lock-point order. The serial schedule in lock-point order has the same actions, and it puts every such pair in the same order, so the two are conflict equivalent. This is the argument of the two-phase locking theorem, for a schedule in which every transaction is two-phase. □\square

The wait-for graph. The edges are T→UT \to U for T∈WT \in W and either UU holds a lock that conflicts with a lock in L(T)L(T), or UU is before TT in WW and wants a lock that conflicts with a lock in L(T)L(T).

Lemma 3. A transaction in WW holds no lock.

Proof. A transaction joins WW at line L2, before it gets any lock, and it gets locks only at line L6, where it leaves WW. □\square

Theorem 2 (no deadlock). The wait-for graph never has a cycle.

Proof. Let T→UT \to U be an edge. If UU holds a lock, then by Lemma 3, U∉WU \notin W, and UU has no edge out of it. Otherwise UU is before TT in WW. So along any path, the nodes in WW come strictly earlier in WW at each step, and the path can end at a holder, after which it stops. A cycle would need a node in WW to come before itself. □\square

Lemma 4. After each call of ADMIT, if WW is not empty, the first transaction in WW conflicts with a lock held by another transaction.

Proof. In the pass of ADMIT, the set of locks wanted by earlier waiters is empty when the pass reaches the first transaction that it does not admit. That transaction stays in WW only because a lock of L(T)L(T) conflicts with a held lock. The transactions before it in the pass were admitted, so it is the first in WW after the pass. □\square

Theorem 3 (progress). If every admitted transaction runs its remaining actions whenever the arrival order offers them, then every transaction is admitted and ends.

Proof. An admitted transaction never waits again: line L7 needs no new lock, and lines L8 and L9 only release. So an admitted transaction ends after its remaining actions are offered, which happens because the arrival order offers each action and the driver runs the first transaction that does not wait.

Now let TT be the first transaction in WW. While TT is first, no transaction UU that conflicts with TT is admitted. Such a UU is either already in WW behind TT or comes later, and in each pass of ADMIT the pass reaches TT first and, because TT stays in WW, adds the locks of TT to the wanted locks; then UU fails the test of line L5. So the set of holders whose locks conflict with L(T)L(T) only shrinks while TT is first. Each of them is admitted and ends, by the first paragraph. Its release at line L8 or L9 calls ADMIT, and after the last such release, TT conflicts with no held lock and has no earlier waiter, so the pass admits it. The next transaction in WW is then first, and the same argument applies. By induction along WW, every transaction is admitted.

In particular, the driver never reaches a state in which every unfinished transaction waits: by Lemma 4, if WW is not empty then some transaction holds a lock, and that transaction is admitted and has an action left. □\square

Theorem 4 (strictness). With strict = true, every output schedule is strict: if wj(x)w_j(x) comes before oi(x)o_i(x) with i≠ji \ne j, then TjT_j ended before oi(x)o_i(x).

Proof. TjT_j holds X on xx from before wj(x)w_j(x) until line L9 at its end, and oi(x)o_i(x) needs a lock on xx that conflicts with X. By Lemma 1, TiT_i gets that lock only after the release at the end of TjT_j, so oi(x)o_i(x) comes after the end of TjT_j. □\square

With strict = false, Theorem 4 fails: the page gives w1(x) r2(x) c2 r1(y) c1w_1(x)\, r_2(x)\, c_2\, r_1(y)\, c_1, which is not even recoverable. Theorems 1 to 3 do not use the release rule, so they hold for both settings.

The tests check Lemma 1, Lemma 3 and Theorem 2 after every step, and Theorems 1, 3 and 4 on every output, on all interleavings of four sets of two or three short transactions and on 50 random interleavings of four or six. Theorem 1 is checked with the helper dbsched, by conflict equivalence of the committed projection with the serial schedule in lock-point order, which is the definition and does not use a conflict graph.

Complexity

  • Admission. One pass of ADMIT looks at each of the ww waiters and each of its ss declared locks. In the code, each lock is compared with the holders of its item, up to kk of them, so a pass costs O(wsk)O(w s k) expected time. With a count of the holders of each mode in each entry of the lock table, as in a real lock manager, each test costs O(1)O(1) and a pass costs O(ws)O(w s).
  • Access. A read or write costs O(1)O(1) expected time for the check of line L7.
  • Space. The declared lock sets of the active transactions take O(ks)O(k s).
  • Concurrency. A transaction holds each lock from before its first action to its end (strict) or to its last access to the item. Basic 2PL takes each lock just before the first access to its item, so it holds locks for a shorter time, and conservative 2PL allows less concurrency. On the other side, it never wastes work on deadlock victims.

Properties

  • Output class. Conflict serializable, in the order of admission. With strict = true, also strict, so recoverable and free of cascading aborts.
  • Deadlock free and starvation free. Shown above; no wait-for graph is needed, and no transaction is aborted by the scheduler.
  • Needs knowledge in advance. The read and write sets must be known when the transaction begins.
  • Admits fewer schedules than basic 2PL. Every schedule of conservative 2PL is a schedule of basic 2PL, since a transaction may always take its locks early. The converse is false: in the deadlock example, basic 2PL can also produce the serial output, but it lets r1(x) r2(y)r_1(x)\, r_2(y) run concurrently first, which conservative 2PL never does.

Variants and improvements

  • Conservative strict 2PL. The form with strict = true. It is deadlock free and gives strict schedules.
  • Ordered locking. Instead of all locks at once, a transaction takes its locks one at a time in a fixed global order of the items (lock ordering). It also needs the lock set in advance and also prevents deadlock, because a cycle of waits would need an item order with a cycle. A transaction then waits while it holds locks, but it holds them for less time.
  • Deterministic databases. Calvin orders the transactions first and then gives each one its full lock set in that order. A transaction whose read set depends on the data first runs a reconnaissance step to find its set, and it restarts if the set changed.
  • Wait-free alternatives. Wait-die and wound-wait also prevent deadlocks, without the read and write sets, but they abort transactions instead.

When to use it

Use conservative 2PL when the read and write sets are known when a transaction starts: stored procedures with fixed keys, batch jobs, and systems that order transactions in advance. It suits workloads in which a deadlock abort would be expensive, for example long transactions, or systems that cannot restart a transaction. Do not use it for interactive transactions whose next read depends on what they have read, or for queries whose sets come from a scan of an index: the scheduler would have to lock a superset, for example the whole table.

Pitfalls

  • An undeclared access. A transaction that touches an item it did not declare, or writes an item it declared only for reading, breaks the method. Line L7 must reject the access; an upgrade at that point could wait while holding locks and bring deadlocks back.
  • A superset of the real set. If the sets are not known exactly, the transaction must declare a superset. This is safe but holds more locks for longer.
  • Starvation without the FIFO test. If line L5 compares only with the holders, a transaction that needs many items can wait forever while smaller transactions keep one of its items busy.
  • Early release and recovery. With strict = false the schedules are serializable but may not be recoverable, as in the example. Use strict = true when transactions can abort.
  • All or nothing must be atomic. The test of line L5 and the grant of line L6 must be one step of the lock manager. If another transaction can take a lock between the test and the grant, a transaction ends up holding a part of its set while it waits.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

conservative_two_phase_locking.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conservative-two-phase-locking/. The authors are listed in prov/CS6AB2.jsonl.

"""Conservative (static) two-phase locking.

A transaction declares its read set and write set when it begins. The
scheduler grants all its locks at once, or none: X on each item it writes and
S on each item it only reads. A transaction that cannot get all its locks
waits in a FIFO list and holds nothing. A waiting transaction is admitted
when its locks are compatible with the locks held by others and with the
locks wanted by every earlier waiter, so it never passes an earlier waiter
that it conflicts with.

With strict=True every lock is held to the end of the transaction. With
strict=False a lock is released after the last access of the transaction to
the item; the transaction is still two-phase, because it took all its locks
before its first action.

Actions are tuples (kind, txn, item) with kind in "r", "w", "c", "a", as in
the helper dbsched.
"""

S, X = "S", "X"


def conflict(a, b):
    """Two lock modes of different transactions conflict unless both are S."""
    return a == X or b == X


def lock_set(program):
    """The locks a program needs: X on each written item, S on each item it only reads."""
    need = {}
    for kind, _, item in program:
        if kind == "w":
            need[item] = X
        elif kind == "r":
            need.setdefault(item, S)
    return need


class ConservativeScheduler:
    def __init__(self, strict=True):
        self.strict = strict
        self.locks = {}  # item -> {txn: mode}
        self.wait = []  # waiting txns, in order of arrival
        self.need = {}  # txn -> {item: mode}, the declared lock set
        self.left = {}  # txn -> {item: accesses still to come}
        self.held = {}  # txn -> set of items it holds
        self.lock_points = []  # txns in the order of their lock points

    def begin(self, txn, program):
        """Declare the program of txn and ask for all its locks.
        Return True if txn holds them now, False if it waits."""
        self.need[txn] = lock_set(program)  # @line L1
        self.left[txn] = {}
        for kind, _, item in program:
            if kind in "rw":
                self.left[txn][item] = self.left[txn].get(item, 0) + 1
        self.wait.append(txn)  # @line L2
        self._admit()  # @line L3
        return txn not in self.wait

    def _fits(self, txn, wanted):
        for item, mode in self.need[txn].items():
            for u, m in self.locks.get(item, {}).items():
                if u != txn and conflict(m, mode):
                    return False
            if item in wanted and conflict(wanted[item], mode):
                return False
        return True

    def _admit(self):
        """Admit waiting transactions in order of arrival while they fit."""
        admitted = []
        wanted = {}  # item -> strongest mode wanted by an earlier waiter
        for txn in list(self.wait):  # @line L4
            if self._fits(txn, wanted):  # @line L5
                self.wait.remove(txn)  # @line L6
                for item, mode in self.need[txn].items():
                    self.locks.setdefault(item, {})[txn] = mode
                self.held[txn] = set(self.need[txn])
                self.lock_points.append(txn)
                admitted.append(txn)
            else:
                for item, mode in self.need[txn].items():
                    if wanted.get(item) != X:
                        wanted[item] = mode
        return admitted

    def _release(self, txn, item):
        del self.locks[item][txn]
        if not self.locks[item]:
            del self.locks[item]
        self.held[txn].discard(item)

    def access(self, txn, kind, item):
        """Run r or w of txn on item. Return the transactions admitted as a result."""
        mode = self.locks.get(item, {}).get(txn)
        if mode is None or (kind == "w" and mode != X):  # @line L7
            raise ValueError("%r has no %s lock on %r" % (txn, kind, item))
        self.left[txn][item] -= 1
        if not self.strict and self.left[txn][item] == 0:  # @line L8
            self._release(txn, item)
            return self._admit()
        return []

    def end(self, txn):
        """Commit or abort txn: release all its locks. Return the admitted transactions."""
        for item in sorted(self.held.get(txn, ()), key=repr):  # @line L9
            self._release(txn, item)
        self.held.pop(txn, None)
        self.need.pop(txn, None)
        self.left.pop(txn, None)
        return self._admit()

    def waits_for(self):
        """Edges (T, U): T waits and U holds a conflicting lock, or U is an
        earlier waiter that wants a conflicting lock."""
        edges = set()
        for k, txn in enumerate(self.wait):
            for item, mode in self.need[txn].items():
                for u, m in self.locks.get(item, {}).items():
                    if conflict(m, mode):
                        edges.add((txn, u))
                for u in self.wait[:k]:
                    m = self.need[u].get(item)
                    if m is not None and conflict(m, mode):
                        edges.add((txn, u))
        return edges


def run(programs, arrival, strict=True, check=None):
    """Run the programs (sequences of actions, one transaction each) under
    conservative 2PL. arrival lists the transaction of each action in the
    order the actions are offered; a waiting transaction keeps its place and
    the first transaction that does not wait goes next. check(scheduler) is
    called after each step. Return the output schedule and the order of the
    lock points."""
    progs = {p[0][1]: tuple(p) for p in programs}
    sched = ConservativeScheduler(strict)
    pos = {t: 0 for t in progs}
    out, pending = [], list(arrival)
    while pending:
        k = next((k for k, t in enumerate(pending) if t not in sched.wait), None)
        if k is None:
            raise RuntimeError("every transaction waits")
        t = pending[k]
        if pos[t] == 0 and t not in sched.held:
            if not sched.begin(t, progs[t]):
                if check:
                    check(sched)
                continue
        act = progs[t][pos[t]]
        if act[0] in "rw":
            sched.access(t, act[0], act[2])
        else:
            sched.end(t)
        out.append(act)
        pos[t] += 1
        pending.pop(k)
        if check:
            check(sched)
    return tuple(out), tuple(sched.lock_points)
dbsched.py 431 lines
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Schedules of transactions, and their classes checked by definition.

This is the reference that the tests of the concurrency pages compare
against. Every class test here follows its definition directly. The
serializability tests try every serial order of the committed transactions;
there is no conflict graph and no cycle test here. Do not use it as a
scheduler.

Actions and schedules
    An action is a tuple (kind, txn, item). kind is "r" (read), "w" (write),
    "c" (commit) or "a" (abort). txn is a transaction id (an int after
    parse). item is a string for r and w, and None for c and a.
    A schedule is a tuple of actions. In a well-formed schedule each
    transaction has at most one c or a, and it is the last action of that
    transaction. A schedule may be a prefix: a transaction with no c or a
    is active.

    parse("r1(x) w2(x) c1 a2")    the schedule as a tuple of actions
    format(s)                     the inverse of parse (also format_schedule)
    validate(s)                   raise ValueError if s is not well formed
    transactions(s)               the ids in the order of their first action
    committed(s), aborted(s)      the ids with a c, or with an a, in s
    actions_of(s, t)              the actions of t, in order
    committed_projection(s)       the r, w and c actions of the committed
                                  transactions, in the order of s
    conflicts(p, q)               different transactions, the same item, and
                                  at least one write
    serial_schedule(s, order)     the actions of the transactions of order,
                                  one transaction after the other

Equivalence and serializability (on the committed projection)
    conflict_equivalent(s1, s2)   same actions, and every pair of conflicting
                                  actions in the same order
    reads_from(s)                 {read: write it reads from}, see below
    final_writes(s)               {item: the last write on the item}
    view_equivalent(s1, s2)       same actions, same reads_from and the same
                                  final_writes
    conflict_serializable_orders(s), view_serializable_orders(s)
                                  every serial order of the committed
                                  transactions that is equivalent, as tuples,
                                  in lexicographic order of the sorted ids
    is_conflict_serializable(s), is_view_serializable(s)
    These raise ValueError when s has more than MAX_BRUTE_FORCE committed
    transactions. is_view_serializable uses the plain definition (view
    equivalence of C(s) to a serial schedule), with no condition on prefixes.

Recovery classes (on the full schedule, with its aborts), as in Bernstein,
Hadzilacos and Goodman (1987), Section 1.2
    is_recoverable(s)             if T_i reads x from T_j (i != j) and c_i is
                                  in s, then c_j < c_i
    avoids_cascading_aborts(s)    if T_i reads x from T_j (i != j), then
                                  c_j < r_i(x)
    is_strict(s)                  if w_j(x) < o_i(x) (i != j, o in r and w),
                                  then a_j < o_i(x) or c_j < o_i(x)

Reads-from
    An action is named by its occurrence id (txn, kind, item, k): the k-th
    action of that kind on that item by that transaction, from 0. A read
    r_i(x) reads from w_j(x) when w_j(x) comes before r_i(x), a_j does not
    come before r_i(x), and every write w_k(x) between them has its a_k
    before r_i(x). If no write qualifies, the read reads the initial value,
    shown as None. The writer is a write occurrence, not only a transaction,
    so a read between two writes of the same transaction on the same item
    is told apart from a read after both.

Generators
    interleavings(txns)           every schedule that merges the sequences
                                  of txns and keeps the order inside each
    random_schedule(rng, txns)    one of them, chosen uniformly with the
                                  random.Random rng
    Each element of txns is a sequence of actions or a string for parse.
"""

import itertools
import re

MAX_BRUTE_FORCE = 6

READ, WRITE, COMMIT, ABORT = "r", "w", "c", "a"
_KINDS = (READ, WRITE, COMMIT, ABORT)
_TOKEN = re.compile(r"^([rwca])(\d+)(?:\(([A-Za-z_][A-Za-z0-9_]*)\))?$")


# ---------------------------------------------------------------- basics

def parse(text):
    """Parse "r1(x) w2(x) c1 a2" into a tuple of actions."""
    out = []
    for tok in text.split():
        m = _TOKEN.match(tok)
        if not m:
            raise ValueError("bad action %r" % tok)
        kind, txn, item = m.group(1), int(m.group(2)), m.group(3)
        if kind in (READ, WRITE) and item is None:
            raise ValueError("a read or write needs an item: %r" % tok)
        if kind in (COMMIT, ABORT) and item is not None:
            raise ValueError("a commit or abort has no item: %r" % tok)
        out.append((kind, txn, item))
    s = tuple(out)
    validate(s)
    return s


def format(schedule):
    """Write a schedule in the notation of parse."""
    parts = []
    for kind, txn, item in schedule:
        if item is None:
            parts.append("%s%s" % (kind, txn))
        else:
            parts.append("%s%s(%s)" % (kind, txn, item))
    return " ".join(parts)


format_schedule = format


def validate(schedule):
    """Raise ValueError unless each transaction ends at most once, at its end."""
    ended = set()
    for act in schedule:
        if len(act) != 3:
            raise ValueError("an action is (kind, txn, item): %r" % (act,))
        kind, txn, item = act
        if kind not in _KINDS:
            raise ValueError("bad kind %r" % (kind,))
        if (kind in (READ, WRITE)) != (item is not None):
            raise ValueError("item must be set exactly for r and w: %r" % (act,))
        if txn in ended:
            raise ValueError("action after the end of transaction %r" % (txn,))
        if kind in (COMMIT, ABORT):
            ended.add(txn)


def transactions(schedule):
    """The transaction ids in the order of their first action."""
    seen = []
    for _, txn, _ in schedule:
        if txn not in seen:
            seen.append(txn)
    return seen


def committed(schedule):
    """The set of ids that have a commit in the schedule."""
    return {txn for kind, txn, _ in schedule if kind == COMMIT}


def aborted(schedule):
    """The set of ids that have an abort in the schedule."""
    return {txn for kind, txn, _ in schedule if kind == ABORT}


def actions_of(schedule, txn):
    """The actions of one transaction, in order."""
    return tuple(a for a in schedule if a[1] == txn)


def committed_projection(schedule):
    """The actions of the committed transactions, in the order of the schedule."""
    validate(schedule)
    keep = committed(schedule)
    return tuple(a for a in schedule if a[1] in keep)


def conflicts(p, q):
    """True when p and q are reads or writes of different transactions on the
    same item, and at least one of them is a write."""
    return (p[0] in (READ, WRITE) and q[0] in (READ, WRITE)
            and p[1] != q[1] and p[2] == q[2]
            and (p[0] == WRITE or q[0] == WRITE))


def serial_schedule(schedule, order):
    """The serial schedule that runs the transactions of order one by one."""
    out = []
    for txn in order:
        out.extend(actions_of(schedule, txn))
    return tuple(out)


def _occurrences(schedule):
    """The occurrence id (txn, kind, item, k) of each action, by position."""
    count = {}
    ids = []
    for kind, txn, item in schedule:
        key = (txn, kind, item)
        k = count.get(key, 0)
        count[key] = k + 1
        ids.append((txn, kind, item, k))
    return ids


# ---------------------------------------------------------- equivalence

def _same_actions(s1, s2):
    return sorted(_occurrences(s1), key=repr) == sorted(_occurrences(s2), key=repr)


def _conflict_pairs(schedule):
    ids = _occurrences(schedule)
    pairs = set()
    for i in range(len(schedule)):
        for j in range(i + 1, len(schedule)):
            if conflicts(schedule[i], schedule[j]):
                pairs.add((ids[i], ids[j]))
    return pairs


def conflict_equivalent(s1, s2):
    """Same actions, and every pair of conflicting actions in the same order."""
    return _same_actions(s1, s2) and _conflict_pairs(s1) == _conflict_pairs(s2)


def reads_from(schedule):
    """Map the occurrence id of each read to the write occurrence it reads
    from, or to None for the initial value (see the module notes)."""
    ids = _occurrences(schedule)
    result = {}
    for q, (kind, txn, item) in enumerate(schedule):
        if kind != READ:
            continue
        ended_abort = {t for k, t, _ in schedule[:q] if k == ABORT}
        source = None
        for p in range(q - 1, -1, -1):
            pk, pt, pi = schedule[p]
            if pk == WRITE and pi == item and pt not in ended_abort:
                source = ids[p]
                break
        result[ids[q]] = source
    return result


def final_writes(schedule):
    """Map each written item to the occurrence id of its last write that is
    not followed by an abort of its transaction."""
    ids = _occurrences(schedule)
    gone = aborted(schedule)
    result = {}
    for p, (kind, txn, item) in enumerate(schedule):
        if kind == WRITE and txn not in gone:
            result[item] = ids[p]
    return result


def view_equivalent(s1, s2):
    """Same actions, the same reads-from map and the same final writes."""
    return (_same_actions(s1, s2) and reads_from(s1) == reads_from(s2)
            and final_writes(s1) == final_writes(s2))


# ------------------------------------------------------- serializability

def _orders(schedule, equivalent):
    cp = committed_projection(schedule)
    txns = sorted(committed(cp), key=repr)
    if len(txns) > MAX_BRUTE_FORCE:
        raise ValueError("brute force over %d committed transactions; at most %d"
                         % (len(txns), MAX_BRUTE_FORCE))
    return [order for order in itertools.permutations(txns)
            if equivalent(cp, serial_schedule(cp, order))]


def conflict_serializable_orders(schedule):
    """Every serial order of the committed transactions that is conflict
    equivalent to the committed projection."""
    return _orders(schedule, conflict_equivalent)


def view_serializable_orders(schedule):
    """Every serial order of the committed transactions that is view
    equivalent to the committed projection."""
    return _orders(schedule, view_equivalent)


def is_conflict_serializable(schedule):
    return bool(conflict_serializable_orders(schedule))


def is_view_serializable(schedule):
    return bool(view_serializable_orders(schedule))


# -------------------------------------------------------- recovery classes

def _position_of_end(schedule, kind):
    return {txn: p for p, (k, txn, _) in enumerate(schedule) if k == kind}


def _foreign_reads(schedule):
    """(position of the read, reader, writer txn) for each read from another
    transaction."""
    validate(schedule)
    ids = _occurrences(schedule)
    rf = reads_from(schedule)
    out = []
    for q, (kind, txn, _) in enumerate(schedule):
        if kind == READ:
            src = rf[ids[q]]
            if src is not None and src[0] != txn:
                out.append((q, txn, src[0]))
    return out


def is_recoverable(schedule):
    """If T_i reads from T_j (i != j) and c_i is in the schedule, then c_j < c_i."""
    commit_at = _position_of_end(schedule, COMMIT)
    for _, reader, writer in _foreign_reads(schedule):
        if reader in commit_at:
            if writer not in commit_at or commit_at[writer] > commit_at[reader]:
                return False
    return True


def avoids_cascading_aborts(schedule):
    """If T_i reads x from T_j (i != j), then c_j comes before the read."""
    commit_at = _position_of_end(schedule, COMMIT)
    for q, _, writer in _foreign_reads(schedule):
        if writer not in commit_at or commit_at[writer] > q:
            return False
    return True


def is_strict(schedule):
    """If w_j(x) < o_i(x) with i != j, then T_j ended (c_j or a_j) before o_i(x)."""
    validate(schedule)
    end_at = _position_of_end(schedule, COMMIT)
    end_at.update(_position_of_end(schedule, ABORT))
    for q, (kind, txn, item) in enumerate(schedule):
        if kind not in (READ, WRITE):
            continue
        for p in range(q):
            pk, pt, pi = schedule[p]
            if pk == WRITE and pi == item and pt != txn:
                if pt not in end_at or end_at[pt] > q:
                    return False
    return True


# ------------------------------------------------------------- generators

def _as_actions(txn):
    return parse(txn) if isinstance(txn, str) else tuple(txn)


def interleavings(txns):
    """Yield every interleaving of the sequences, keeping each one in order."""
    seqs = [_as_actions(t) for t in txns]
    pos = [0] * len(seqs)
    total = sum(len(s) for s in seqs)
    current = []

    def rec():
        if len(current) == total:
            yield tuple(current)
            return
        for i, seq in enumerate(seqs):
            if pos[i] < len(seq):
                current.append(seq[pos[i]])
                pos[i] += 1
                yield from rec()
                pos[i] -= 1
                current.pop()

    yield from rec()


def random_schedule(rng, txns):
    """One interleaving, uniform over all interleavings: the next action comes
    from a sequence with probability proportional to its remaining length."""
    seqs = [_as_actions(t) for t in txns]
    pos = [0] * len(seqs)
    left = sum(len(s) for s in seqs)
    out = []
    while left:
        r = rng.randrange(left)
        for i, seq in enumerate(seqs):
            rest = len(seq) - pos[i]
            if r < rest:
                out.append(seq[pos[i]])
                pos[i] += 1
                break
            r -= rest
        left -= 1
    return tuple(out)


# -------------------------------------------------------------- self-test

def _self_test():
    # A CSR schedule, equivalent to T1 T2 only.
    s = parse("r1(x) w1(x) r2(x) r1(y) w2(x) w1(y) c1 c2")
    assert format(s) == "r1(x) w1(x) r2(x) r1(y) w2(x) w1(y) c1 c2"
    assert conflict_serializable_orders(s) == [(1, 2)]
    assert is_view_serializable(s)
    # The lost update: neither CSR nor VSR.
    s = parse("r1(x) r2(x) w1(x) w2(x) c1 c2")
    assert not is_conflict_serializable(s) and not is_view_serializable(s)
    # Blind writes: VSR (as T1 T2 T3) but not CSR.
    s = parse("r1(x) w2(x) w1(x) w3(x) c1 c2 c3")
    assert not is_conflict_serializable(s)
    assert view_serializable_orders(s) == [(1, 2, 3)]
    # Not recoverable: T2 reads x from T1 and commits first.
    s = parse("w1(x) r2(x) c2 c1")
    assert not is_recoverable(s)
    # Recoverable but not ACA; ACA but not strict; strict.
    s = parse("w1(x) r2(x) c1 c2")
    assert is_recoverable(s) and not avoids_cascading_aborts(s)
    s = parse("w1(x) w2(x) c1 c2")
    assert avoids_cascading_aborts(s) and not is_strict(s)
    s = parse("w1(x) c1 r2(x) w2(x) c2")
    assert is_strict(s)
    # A read after an aborted write reads the initial value.
    s = parse("w1(x) a1 r2(x) c2")
    assert reads_from(s) == {(2, "r", "x", 0): None} and is_strict(s)
    # Committed projection, interleavings and random schedules.
    assert committed_projection(parse("r1(x) w2(x) a2 c1")) == parse("r1(x) c1")
    allx = list(interleavings(["r1(x) w1(x)", "r2(x) c2"]))
    assert len(allx) == 6 and len(set(allx)) == 6
    import random
    rng = random.Random(1)
    t = [parse("r1(x) w1(y) c1"), parse("w2(x) c2"), parse("r3(y) c3")]
    for _ in range(50):
        assert random_schedule(rng, t) in set(interleavings(t))
    return True


if __name__ == "__main__":
    _self_test()
test_conservative_two_phase_locking.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conservative-two-phase-locking/. The authors are listed in prov/CS6AB2.jsonl.

import itertools
import random

import pytest

import conservative_two_phase_locking as c2pl
import dbsched


# Tests of the shared helper dbsched.py.


def test_helper_self_test() -> None:
    assert dbsched._self_test()


def test_helper_parse_format_round_trip() -> None:
    text = "r1(x) w2(y) a2 w1(x) c1"
    s = dbsched.parse(text)
    assert s == (("r", 1, "x"), ("w", 2, "y"), ("a", 2, None), ("w", 1, "x"), ("c", 1, None))
    assert dbsched.format(s) == text
    for bad in ("r1", "c1(x)", "q1(x)", "c1 r1(x)", "c1 a1"):
        with pytest.raises(ValueError):
            dbsched.parse(bad)


def test_helper_conflicts() -> None:
    assert dbsched.conflicts(("r", 1, "x"), ("w", 2, "x"))
    assert dbsched.conflicts(("w", 1, "x"), ("w", 2, "x"))
    assert not dbsched.conflicts(("r", 1, "x"), ("r", 2, "x"))
    assert not dbsched.conflicts(("w", 1, "x"), ("w", 1, "x"))
    assert not dbsched.conflicts(("w", 1, "x"), ("w", 2, "y"))
    assert not dbsched.conflicts(("c", 1, None), ("w", 2, "x"))


def test_helper_standard_examples() -> None:
    # Two serial orders when T3 is independent of T2 and T1 is after T2.
    s = dbsched.parse("r1(x) r2(y) r3(z) w1(y) c1 c2 c3")
    assert dbsched.conflict_serializable_orders(s) == [(2, 1, 3), (2, 3, 1), (3, 2, 1)]
    # A read between two writes of the same transaction is not serializable.
    s = dbsched.parse("w1(x) r2(x) w1(x) c1 c2")
    assert not dbsched.is_view_serializable(s)
    # Aborted transactions drop out of the committed projection.
    s = dbsched.parse("r1(x) r2(x) w1(x) w2(x) a2 c1")
    assert dbsched.is_conflict_serializable(s)
    assert not dbsched.is_recoverable(dbsched.parse("w1(x) r2(x) c2 a1"))


def _graph_orders(s):
    """Independent oracle: the topological orders of the conflict graph."""
    cp = dbsched.committed_projection(s)
    txns = sorted(dbsched.committed(cp))
    edges = {(p[1], q[1]) for i, p in enumerate(cp) for q in cp[i + 1:] if dbsched.conflicts(p, q)}
    return [o for o in itertools.permutations(txns) if all(o.index(a) < o.index(b) for a, b in edges)]


def test_helper_classes_on_all_interleavings() -> None:
    txns = ["r1(x) w1(y) c1", "r2(y) w2(x) c2", "w3(x) a3"]
    seen = set()
    for s in dbsched.interleavings(txns):
        seen.add(s)
        st = dbsched.is_strict(s)
        aca = dbsched.avoids_cascading_aborts(s)
        rc = dbsched.is_recoverable(s)
        assert (not st or aca) and (not aca or rc)
        csr = dbsched.is_conflict_serializable(s)
        assert not csr or dbsched.is_view_serializable(s)
        assert dbsched.conflict_serializable_orders(s) == _graph_orders(s)
    assert len(seen) == 560  # 8! / (3! 3! 2!)


def test_helper_random_schedule_is_uniform_enough() -> None:
    rng = random.Random(7)
    txns = ["r1(x) w1(x)", "w2(x) c2"]
    counts = {}
    for _ in range(3000):
        s = dbsched.random_schedule(rng, txns)
        counts[s] = counts.get(s, 0) + 1
    assert set(counts) == set(dbsched.interleavings(txns))
    assert min(counts.values()) > 400  # 6 interleavings, 500 expected each


def test_helper_limit() -> None:
    s = dbsched.parse(" ".join("w%d(x) c%d" % (i, i) for i in range(1, 8)))
    with pytest.raises(ValueError):
        dbsched.is_conflict_serializable(s)


# Tests of conservative two-phase locking.


def _acyclic(edges):
    succ = {}
    for a, b in edges:
        succ.setdefault(a, set()).add(b)
    state = {}

    def visit(v):
        state[v] = 1
        for w in succ.get(v, ()):
            if state.get(w) == 1 or (w not in state and not visit(w)):
                return False
        state[v] = 2
        return True

    return all(v in state or visit(v) for v in list(succ))


def _check_state(sched):
    # Safety: conflicting locks of different transactions are never held together.
    for item, holders in sched.locks.items():
        modes = list(holders.values())
        assert all(not c2pl.conflict(a, b) for i, a in enumerate(modes) for b in modes[i + 1:]), item
    # A waiting transaction holds nothing, so the wait-for graph has no cycle.
    for t in sched.wait:
        assert not sched.held.get(t)
    edges = sched.waits_for()
    assert _acyclic(edges)
    assert all(u not in sched.wait or sched.wait.index(u) < sched.wait.index(t) for t, u in edges)


def _run(txns, arrival, strict=True):
    progs = [dbsched.parse(t) for t in txns]
    out, lps = c2pl.run(progs, arrival, strict, _check_state)
    assert sorted(dbsched.transactions(out)) == sorted(p[0][1] for p in progs)
    assert len(out) == sum(len(p) for p in progs)  # every transaction finishes
    return out, lps


def _lock_point_order_is_serial(out, lps):
    done = dbsched.committed(out)
    order = tuple(t for t in lps if t in done)
    cp = dbsched.committed_projection(out)
    assert dbsched.conflict_equivalent(cp, dbsched.serial_schedule(cp, order))


def test_the_deadlock_of_basic_2pl_does_not_happen() -> None:
    # Under basic 2PL this arrival order deadlocks (see the two-phase-locking page).
    txns = ["r1(x) w1(y) c1", "r2(y) w2(x) c2"]
    out, lps = _run(txns, [1, 2, 1, 2, 1, 2])
    assert dbsched.format(out) == "r1(x) w1(y) c1 r2(y) w2(x) c2"
    assert lps == (1, 2)


def test_all_or_nothing_and_fifo() -> None:
    sched = c2pl.ConservativeScheduler()
    assert sched.begin(1, dbsched.parse("r1(x) c1"))
    assert not sched.begin(2, dbsched.parse("r2(y) w2(x) c2"))
    assert sched.held.get(2) is None and "y" not in sched.locks  # nothing is held
    # S on x fits the holder T1, but T3 must not pass the earlier waiter T2.
    assert not sched.begin(3, dbsched.parse("r3(x) c3"))
    assert sched.waits_for() == {(2, 1), (3, 2)}
    # T4 conflicts with nobody and is admitted at once.
    assert sched.begin(4, dbsched.parse("w4(z) c4"))
    assert sched.end(1) == [2]
    assert sched.end(2) == [3]
    assert sched.lock_points == [1, 4, 2, 3]
    with pytest.raises(ValueError):
        sched.access(4, "r", "x")


SETS = [
    ["r1(x) w1(y) c1", "r2(y) w2(x) c2"],
    ["r1(x) w1(x) c1", "r2(x) w2(x) c2", "r3(y) c3"],
    ["r1(x) w1(y) c1", "r2(y) w2(z) c2", "r3(z) w3(x) c3"],
    ["w1(x) r1(y) c1", "r2(x) c2", "w3(y) a3"],
]


@pytest.mark.parametrize("txns", SETS)
def test_strict_on_all_interleavings(txns) -> None:
    for s in dbsched.interleavings(txns):
        out, lps = _run(txns, [a[1] for a in s], strict=True)
        _lock_point_order_is_serial(out, lps)
        assert dbsched.is_strict(out)


@pytest.mark.parametrize("txns", SETS)
def test_early_release_on_all_interleavings(txns) -> None:
    for s in dbsched.interleavings(txns):
        out, lps = _run(txns, [a[1] for a in s], strict=False)
        _lock_point_order_is_serial(out, lps)


def test_early_release_can_give_a_schedule_that_is_not_recoverable() -> None:
    txns = ["w1(x) r1(y) c1", "r2(x) c2"]
    out, _ = _run(txns, [1, 2, 2, 1, 1], strict=False)
    assert dbsched.format(out) == "w1(x) r2(x) c2 r1(y) c1"
    assert dbsched.is_conflict_serializable(out) and not dbsched.is_recoverable(out)
    out, _ = _run(txns, [1, 2, 2, 1, 1], strict=True)
    assert dbsched.format(out) == "w1(x) r1(y) c1 r2(x) c2"


def test_random_interleavings_of_up_to_six() -> None:
    rng = random.Random(5)
    for n in [4] * 30 + [6] * 20:
        txns = []
        for t in range(1, n + 1):
            acts = ["%s%d(%s)" % (rng.choice("rw"), t, rng.choice("xyzu")) for _ in range(rng.randint(1, 3))]
            txns.append(" ".join(acts + ["c%d" % t]))
        arrival = [a[1] for a in dbsched.random_schedule(rng, txns)]
        for strict in (True, False):
            out, lps = _run(txns, arrival, strict)
            _lock_point_order_is_serial(out, lps)
            if strict:
                assert dbsched.is_strict(out)

History

Havender (1968) proposed, for the OS/360 operating system, that a task should request all its resources together to prevent deadlock. In databases the same rule, with read and write sets declared in advance, became the static or conservative form of two-phase locking. Bernstein, Hadzilacos and Goodman (1987) present it as conservative 2PL beside basic and strict 2PL, and Weikum and Vossen (2001) list it among the variants of 2PL. Deterministic database systems such as Calvin (2012) use the same idea of taking the full lock set of a transaction in a fixed order.

References

  1. Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 3 (conservative 2PL with predeclared read and write sets, and strict 2PL)
  2. Gerhard Weikum and Gottfried Vossen, Transactional Information Systems, Morgan Kaufmann, 2001, Chapter 4 (variants of two-phase locking, among them conservative 2PL)
  3. J. W. Havender, Avoiding deadlock in multitasking systems, IBM Systems Journal 7(2), 1968, pages 74 to 84, the rule that a task requests all its resources together, which prevents deadlock

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per-admission-pass
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example