Algorithm Search⌘K

Algorithmadvanced

Tree locking protocol

Also called Silberschatz-Kedem tree protocol.

A protocol for items arranged in a tree that locks a node only while holding its parent and allows early release, yet stays serializable.

Time
O(1) expected per-requestO(m h) expected per-transaction
Space
O(k m h) extra
Where
h = the height of the tree; k = the number of active transactions; m = the number of accesses of one transaction
Properties
deterministiconline

The tree locking protocol, due to Silberschatz and Kedem (1980), is a locking protocol for data items that form a rooted tree, such as the nodes of an index. A transaction may put its first lock on any node. After that, it may lock a node only while it holds the lock on the parent of that node, and it may never lock a node again after it unlocked it. It may unlock any node at any time. These rules alone make every schedule conflict serializable and free of deadlocks, although a transaction can unlock a node and lock another one later, which two-phase locking forbids. The price is that a transaction must lock every node on the path to the items that it wants, and that the schedules need not be recoverable.

In plain words

Think of a cave system where the tunnels branch like a tree, and only one person fits in a section at a time. You may start in any section. To go deeper, you must still stand in the section you came from while you step into the next one; then you may leave the one behind you. You may not go back to a section you left.

Two people who meet in the tunnels always meet in the same order: whoever went first through the highest shared section is first everywhere below it. Nobody can pass, so the visits are as if one person went through after the other. And nobody gets stuck in a circle of people who each wait for the next one.

The problem

The input is a set of transactions that read and write the nodes of a rooted tree, given by the parent of each node. The actions of the transactions arrive interleaved, and a scheduler with locks must make the output schedule conflict serializable. With two-phase locking, a transaction that walks down the tree must keep every lock until it has all of them, so it keeps the root locked for its whole growing phase, and nobody else can enter the tree. Two-phase locking can also deadlock. The goal is a protocol that uses the shape of the tree to release locks early, without losing serializability.

In the model here, every lock is exclusive: a transaction locks a node before it reads or writes it, whatever the action. A transaction that waits keeps its locks and takes no other step.

The algorithm

  1. LOCK(T, x)
  2. 1if T has locked x before then reject ▷ no lock again
  3. 2if T holds some lock and does not hold parent(x) then reject
  4. 3if another transaction holds x then T waits; try again later
  5. 4grant the lock on x to T; record x as locked by T
  6. UNLOCK(T, x)
  7. 5T must hold x; release it ▷ at any time
  8. PLAN(T, accesses) ▷ one way to follow the rules
  9. 6t ← the lowest common ancestor of the accessed nodes; lock t first
  10. 7before each access to v, lock the nodes on the path from t to v that are not locked yet, from the top down
  11. 8after each lock and each access, unlock each held node that has no later access
  12. and no child on a planned path that is still to be locked

Lines L1 to L5 are the protocol. A transaction reads or writes a node only while it holds the lock on it. Lines L6 to L8 are a planner of this page that turns a list of accesses into lock and unlock steps that follow the rules and release each lock as early as possible. Other plans are legal too, for example one that keeps every lock until the commit.

Example

The tree has the root aa with children bb and cc; bb has the children dd and ee, and cc has ff and gg. Let T1=w1(d) w1(e) c1T_1 = w_1(d)\, w_1(e)\, c_1 and T2=r2(b) r2(d) c2T_2 = r_2(b)\, r_2(d)\, c_2. Both start at bb, the lowest common ancestor of the nodes they use.

step event locks held after the step
1 T1T_1 locks bb, then dd 1: bb, dd
2 w1(d)w_1(d); T1T_1 unlocks dd, which it needs no more 1: bb
3 T2T_2 asks for bb and waits 1: bb
4 T1T_1 locks ee, then unlocks bb: it has no access to bb, and both its children on the paths are locked 1: ee
5 T2T_2 locks bb; r2(b)r_2(b); it locks dd and unlocks bb 1: ee; 2: dd
6 r2(d)r_2(d); T2T_2 unlocks dd; c2c_2 1: ee
7 w1(e)w_1(e); T1T_1 unlocks ee; c1c_1

The output is w1(d) r2(b) r2(d) c2 w1(e) c1w_1(d)\, r_2(b)\, r_2(d)\, c_2\, w_1(e)\, c_1. It is conflict equivalent to T1 T2T_1\, T_2. T1T_1 is not two-phase, since it unlocked dd before it locked ee. The schedule is also not recoverable: T2T_2 read dd from T1T_1 and committed first.

A transaction T3=r3(f) c3T_3 = r_3(f)\, c_3 would lock only ff, its first lock, and run at any moment, since no other transaction uses cc, ff or gg. If T2T_2 were w2(e) w2(d) c2w_2(e)\, w_2(d)\, c_2 instead, the opposite order of T1T_1, then two-phase locking could deadlock on dd and ee. Here both transactions must lock bb first, and the second one waits there without any lock.

Correctness

The proofs are on the proof page. Let TρUT \mathrel{\rho} U mean that TT and UU lock a common node and TT locks it first.

  • The lock order has no cycle. The proof is by induction on the size of the tree. The transactions that lock the root take it one after the other, and each of them reaches the subtree of a child cc through cc, while it holds the root. So their order on cc, and on all of the subtree of cc, is their order on the root. A transaction that does not lock the root stays inside one subtree, where the induction applies.
  • Serializability. Every access is made under an exclusive lock, so every edge of the conflict graph is an edge of ρ\rho. The conflict graph has no cycle, and by the serializability theorem the schedule is conflict serializable.
  • No deadlock. If T1,…,TkT_1, \dots, T_k waited in a cycle, each TiT_i for a node xix_i that Ti+1T_{i+1} holds, then the history can be extended legally so that each TiT_i gets xix_i after Ti+1T_{i+1}. This gives a cycle of ρ\rho, which cannot be.
Proof: The tree locking protocol gives conflict serializable schedules and has no deadlocksfull

Setting. The items are the nodes of a finite rooted tree. A history HH is a finite sequence of events lock(T,x)\mathrm{lock}(T, x) and unlock(T,x)\mathrm{unlock}(T, x) on the nodes, and TT holds xx from its lock of xx to its unlock of xx, or to the end of HH. The history is legal if:

  • (A1) each transaction locks each node at most once (line L1);
  • (A2) each lock by TT, other than the first lock of TT, is of a node whose parent TT holds at that moment (line L2);
  • (A3) no two transactions hold the same node at the same moment (lines L3 and L4), and a transaction unlocks only a node that it holds (line L5).

Let NTN_T be the set of nodes that TT locks in HH, and F(T)F(T) the node of its first lock. Define the relation ρH\rho_H by TρHUT \mathrel{\rho_H} U when T≠UT \ne U, both lock some node xx, and TT locks xx before UU does.

Lemma 1 (the locked nodes form a subtree). In a legal history, every node of NTN_T other than F(T)F(T) has its parent in NTN_T, locked earlier. So every node of NTN_T is a descendant of F(T)F(T) (or F(T)F(T) itself), and the path from F(T)F(T) to it lies in NTN_T, locked from the top down.

Proof. By (A2), when TT locks x≠F(T)x \ne F(T) it holds the parent of xx, which it locked earlier. Follow parents from xx: the lock times go down strictly, so the walk stops, and it can stop only at F(T)F(T). □\square

Theorem 1 (the lock order has no cycle). For every legal history HH, the relation ρH\rho_H has no cycle.

Proof. By induction on the number of nodes of the tree.

Base. If the tree is one node rr, then each transaction locks only rr, at most once, and TρHUT \mathrel{\rho_H} U means that the lock of rr by TT comes first. This is a strict total order on the transactions that lock rr, so it has no cycle.

Step. Let rr be the root, c1,…,ckc_1, \dots, c_k its children and S1,…,SkS_1, \dots, S_k their subtrees, each with fewer nodes than the tree. Let RR be the set of transactions that lock rr. The root has no parent, so by (A2) a lock of rr is the first lock of its transaction, and F(T)=rF(T) = r for each T∈RT \in R. Number RR as R1,…,RmR_1, \dots, R_m in the order of their locks of rr. By (A1) and (A3), the times in which they hold rr are disjoint intervals, in the same order.

Let HiH_i be HH restricted to the events on the nodes of SiS_i. It is a legal history on the tree SiS_i. (A1) and (A3) carry over. For (A2), let TT lock xx in HiH_i, not as its first lock in HiH_i. If x≠cix \ne c_i, the lock is not the first lock of TT in HH either, so TT holds the parent of xx, which is in SiS_i. The case x=cix = c_i does not happen: by Lemma 1 the earlier node y∈Siy \in S_i that TT locked has the path from F(T)F(T) to yy in NTN_T, locked from the top down. If F(T)=rF(T) = r, the path goes through cic_i, so cic_i was locked before yy. If F(T)≠rF(T) \ne r, then F(T)F(T) is in SiS_i and cic_i is a descendant of F(T)F(T), so F(T)=ciF(T) = c_i, which is the first lock of TT. Both contradict the choice of yy. The relation ρHi\rho_{H_i} is ρH\rho_H restricted to pairs that both lock a node of SiS_i, with the order on that node. So ρH\rho_H is the union of the pairs RaρHRbR_a \mathrel{\rho_H} R_b for a<ba < b, which come from rr, and of the relations ρH1,…,ρHk\rho_{H_1}, \dots, \rho_{H_k}. By induction, no ρHi\rho_{H_i} has a cycle.

Claim A. If RaR_a and RbR_b both lock cic_i, then RaR_a locks cic_i first exactly when a<ba < b. Indeed, RaR_a locks cic_i while it holds rr (A2), so inside its interval on rr, and the same holds for RbR_b. The intervals are disjoint and in the order of the indices.

Claim B. If Ra≠RbR_a \ne R_b are joined by a path Ra=U0ρHiU1ρHi⋯ρHiUj=RbR_a = U_0 \mathrel{\rho_{H_i}} U_1 \mathrel{\rho_{H_i}} \cdots \mathrel{\rho_{H_i}} U_j = R_b with j≥1j \ge 1, all of its edges in the same ρHi\rho_{H_i}, then a<ba < b. Indeed, RaR_a and RbR_b lock nodes of SiS_i, so by Lemma 1, with F=rF = r, both lock cic_i. If b<ab < a, then RbR_b locks cic_i first by Claim A, so RbρHiRaR_b \mathrel{\rho_{H_i}} R_a, and with the path this is a cycle of ρHi\rho_{H_i}, which cannot be.

Now let CC be a cycle of ρH\rho_H. A transaction T∉RT \notin R does not lock rr, so by Lemma 1 all of NTN_T lies in the subtree of F(T)F(T), inside one SiS_i. An edge between two transactions outside RR comes from a common node, which is not rr, so the two lie in the same SiS_i, and the edge is in ρHi\rho_{H_i}.

  • If CC has no member of RR, all its members lie in one SiS_i, and CC is a cycle of ρHi\rho_{H_i}. This cannot be.
  • Otherwise cut CC at its members of RR into segments from RaR_a to RbR_b whose inner members are not in RR. A segment of one edge comes from a node that is rr, so a<ba < b, or that is in some SiS_i, so a<ba < b by Claim B. A segment with inner members has all of them in one SiS_i, and its first and last edges come from nodes in that SiS_i too, so it is a path in ρHi\rho_{H_i}. If a=ba = b (the only member of RR on CC), this path is a cycle of ρHi\rho_{H_i}, which cannot be; else a<ba < b by Claim B. So the index goes up strictly along every segment, and it cannot come back to its start. □\square

Corollary 1 (serializability). Under the protocol, every schedule, and every prefix of one, is conflict serializable, and every topological order of ρH\rho_H is an equivalent serial order.

Proof. A transaction reads or writes a node only while it holds the lock on it. If pi(x)p_i(x) comes before a conflicting qj(x)q_j(x), then TiT_i holds xx at pi(x)p_i(x) and TjT_j at qj(x)q_j(x). By (A3) the two intervals are disjoint, so the one of TiT_i comes first, and TiρHTjT_i \mathrel{\rho_H} T_j. So every edge of the conflict graph is in ρH\rho_H, the conflict graph has no cycle by Theorem 1, and the serializability theorem gives the claim. The committed projection has a subgraph of this conflict graph. □\square

Theorem 2 (no deadlock). In every state that the protocol reaches, the wait-for graph has no cycle.

Proof. Let T1,…,TkT_1, \dots, T_k, k≥2k \ge 2, be a cycle: each TiT_i waits for the node xix_i, which Ti+1T_{i+1} holds (indices mod kk). Each TiT_i holds a lock, since Ti−1T_{i-1} waits for it, so its request is not its first lock. The request passed lines L1 and L2, so TiT_i never locked xix_i, and it holds pip_i, the parent of xix_i. A waiting transaction takes no step, so it still holds pip_i. Let HH be the history so far. Extend it as follows.

  1. Each TiT_i unlocks every node that it holds except pip_i. Now xix_i is held only if xi=pi+1x_i = p_{i+1}, by Ti+1T_{i+1}.
  2. It is not true that xi=pi+1x_i = p_{i+1} for all ii, since then depth(xi+1)=depth(xi)+1\mathrm{depth}(x_{i+1}) = \mathrm{depth}(x_i) + 1 for all ii, and the sum around the cycle gives k=0k = 0. Choose jj with xj≠pj+1x_j \ne p_{j+1}, so xjx_j is free.
  3. For i=j,j−1,…,j+1i = j, j-1, \dots, j+1 (going back around the cycle, kk turns): TiT_i locks xix_i, then unlocks xix_i and pip_i. At the turn of TiT_i with i≠ji \ne j, the node xix_i is free, because Ti+1T_{i+1}, the only possible holder, had its turn before and unlocked pi+1p_{i+1}.

Every lock of the extension is legal: TiT_i holds pip_i, has never locked xix_i, and xix_i is free. So the extended history H′H' is legal. In H′H', Ti+1T_{i+1} locked xix_i in HH, before TiT_i locks it in the extension, so Ti+1ρH′TiT_{i+1} \mathrel{\rho_{H'}} T_i for every ii. This is a cycle of ρH′\rho_{H'}, which contradicts Theorem 1. □\square

A transaction that waits for its first lock holds nothing, so nobody waits for it, and it is on no cycle. So with no deadlock, the driver of the tests never has to abort a transaction.

Lemma 2 (the planner follows the protocol). The steps that plan builds satisfy (A1) and (A2), every access happens while the transaction holds its node, and no lock is left at the commit.

Proof. Let UU be the union of the paths from the top node tt (line L6, the lowest common ancestor of the accessed nodes) to each accessed node. The planner locks only nodes of UU, each at most once, and always the whole path from tt to the next accessed node, from the top down (line L7). So the locked nodes are closed under parents inside UU, and on a path the nodes that are still to be locked come after the ones that are locked. When it locks u≠tu \ne t, the parent of uu is in UU and was locked. It was not unlocked, because line L8 unlocks a node only when every child of it in UU is locked, and uu was not. The first lock is tt. A node that is accessed now or later is not unlocked, because line L8 checks the accesses from the current one on. After the last access, each held node has no later access and all its children in UU are locked, since every node of UU lies on the path to an accessed node and all of them were locked. So line L8 unlocks all of them. □\square

What the protocol does not give. A transaction can unlock a node that it wrote before it commits, so another transaction can read the value and commit first. The example of the page gives w1(d) r2(b) r2(d) c2 w1(e) c1w_1(d)\, r_2(b)\, r_2(d)\, c_2\, w_1(e)\, c_1, which is conflict serializable but not recoverable. The protocol is also not two-phase: in the same example T1T_1 unlocks dd before it locks ee.

The tests check Lemma 2 on fixed plans; the state checks (the locked nodes of each transaction form a subtree with one top, and a waiter holds the parent of the node it waits for) after every step; Theorem 1 on the lock log; the inclusion of the conflict graph in ρH\rho_H; and Corollary 1 with the helper dbsched, against the serial schedule in a topological order of ρH\rho_H, and by brute force for up to three transactions. They run all interleavings of two pairs of programs, 3000 random interleavings of two programs that write dd and ee in opposite orders, and 700 random interleavings of three or six transactions on a tree of 15 nodes. No run ever has a deadlock.

Complexity

  • Per request. A lock or unlock is O(1)O(1) expected time with hash tables: the test for the parent, the test for the holder, and the set of nodes that the transaction has locked.
  • Per transaction. A transaction with mm accesses in a tree of height hh locks at most the nodes of mm paths, so O(mh)O(m h) locks, each O(1)O(1) expected. The planner of the code is simple and takes more time than this, up to quadratic in the number of locks.
  • Space. The lock table has one holder per node, and each transaction records the nodes it locked, so O(kmh)O(k m h) for kk active transactions.
  • Concurrency. A transaction holds each node only while it needs it or while it still has to pass through it. The top of the tree is free again as soon as the transaction has gone below it, so many transactions can work in the tree at once, one behind the other.

Properties

  • Output class. Conflict serializable, but not always recoverable, since locks can be released before the commit.
  • Deadlock free. No wait-for graph and no deadlock victims are needed.
  • Not comparable with two-phase locking. A transaction can lock after it unlocked. On the tree of the example, w1(d) w2(d) w3(e) w1(e)w_1(d)\, w_2(d)\, w_3(e)\, w_1(e) comes from the tree protocol (T1T_1 holds bb, and T2T_2 and T3T_3 start at dd and ee), but not from two-phase locking, since T1T_1 would have to hold ee from before w2(d)w_2(d) until w1(e)w_1(e). In the other direction, w1(d) w2(b) w1(b)w_1(d)\, w_2(b)\, w_1(b) comes from two-phase locking, but not from the tree protocol, since T1T_1 must lock bb first and cannot lock it again.
  • Needs the tree. It works only when every transaction reaches the items through the tree, along parent links.

Variants and improvements

  • Locks to the commit. A transaction may keep all its locks until it commits. This is still legal, and the schedules become strict, but the early release, the main gain of the protocol, is lost.
  • Lock coupling in B-trees. Lock coupling, or crabbing, walks from the root of a B-tree to a leaf, and locks a child before it releases the parent. It uses the same rule for short page latches, not for transaction locks. The B-link tree adds right links so that a reader can hold one latch at a time.
  • Shared locks and graphs. Kedem and Silberschatz extended the protocol to directed acyclic graphs and to shared locks; these versions need more rules than the parent rule, as the pitfall below shows.
  • Locks of several sizes. Multiple granularity locking also uses a tree, but there a lock on a node covers the subtree, and it is used together with two-phase locking.

When to use it

Use it when the data is reached through a tree and transactions use small parts of it, so that early release of the upper nodes gives real concurrency: index structures, hierarchies of objects, and file systems. It also fits systems that cannot afford deadlock detection. Do not use it when transactions reach items directly, without the path from a common ancestor, or when they must abort often, since dirty reads then cause cascading aborts.

Pitfalls

  • Shared locks break the plain rules. If two transactions may hold a node at the same time in a shared mode and both go down from it, the order on the node no longer fixes the order below it. With aa above bb and cc: T1T_1 and T2T_2 both hold aa shared, T1T_1 writes bb before T2T_2 does, and T2T_2 writes cc before T1T_1 does. Both follow the parent rule, and the schedule is not serializable.
  • Recoverability. A transaction that reads a node after an early unlock reads uncommitted data. Hold the locks on written nodes until the commit, or delay the commit of the reader until the writer commits.
  • Choosing the first node. A transaction must start at a node above all the items that it will use. A transaction that discovers later that it needs an item outside the subtree of its first lock cannot get it, and must restart.
  • No lock again. A transaction that unlocks a node too early cannot come back to it, so the plan must know which nodes it will use again.

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.

dbsched.pyI0RawGitHub
# 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()
tree_locking_protocol.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tree-locking-protocol/. The authors are listed in prov/AV253P.jsonl.

"""The tree locking protocol of Silberschatz and Kedem, with exclusive locks.

The items are the nodes of a rooted tree. A transaction may lock any node
first. After that, it may lock a node only while it holds the parent of the
node. It may unlock a node at any time, but it may not lock a node again
after it unlocked it. It reads or writes a node only while it holds the lock
on the node. These rules make every schedule conflict serializable and free
of deadlocks, although the locking is not two-phase.
"""


class TreeLockManager:
    def __init__(self, parent):
        self.parent = dict(parent)  # node -> parent, None for the root
        self.holder = {}  # node -> txn that holds the lock
        self.locked = {}  # txn -> the nodes it has locked so far
        self.waiting = {}  # txn -> the node it waits for

    def lock(self, txn, node):
        """Ask for the lock on node. Return True if txn holds it now and
        False if it waits. Raise ValueError if the request breaks a rule."""
        done = self.locked.get(txn, set())
        if node in done:  # @line L1
            raise ValueError("%r may not lock %r again" % (txn, node))
        p = self.parent[node]
        if done and (p is None or self.holder.get(p) != txn):  # @line L2
            raise ValueError("%r must hold the parent of %r" % (txn, node))
        if node in self.holder:  # @line L3
            self.waiting[txn] = node
            return False
        self.holder[node] = txn  # @line L4
        self.locked.setdefault(txn, set()).add(node)
        self.waiting.pop(txn, None)
        return True

    def unlock(self, txn, node):
        if self.holder.get(node) != txn:  # @line L5
            raise ValueError("%r does not hold %r" % (txn, node))
        del self.holder[node]

    def held(self, txn):
        return {v for v, t in self.holder.items() if t == txn}

    def waits_for(self):
        """Edges (T, U): T waits for a node that U holds."""
        return {(t, self.holder[x]) for t, x in self.waiting.items() if x in self.holder}


def path(parent, v):
    """The nodes from the root down to v."""
    out = []
    while v is not None:
        out.append(v)
        v = parent[v]
    return out[::-1]


def lowest_common_ancestor(parent, nodes):
    paths = [path(parent, v) for v in nodes]
    k = 0
    while all(len(p) > k for p in paths) and len({p[k] for p in paths}) == 1:
        k += 1
    return paths[0][k - 1]


def plan(parent, txn, accesses):
    """Turn the accesses [(kind, node), ...] of txn, kind r or w, into steps
    ("lock", node), ("unlock", node), (kind, txn, node) and a final
    ("c", txn, None) that follow the protocol. The first lock is on the
    lowest common ancestor of the accessed nodes. Paths are locked top down
    just before they are needed, and a node is unlocked as soon as it has no
    later access and no child that is still to be locked."""
    top = lowest_common_ancestor(parent, [v for _, v in accesses])  # @line L6
    need = set()
    for _, v in accesses:
        p = path(parent, v)
        need.update(p[p.index(top):])
    children = {v: [c for c in need if parent[c] == v] for v in need}
    steps, held, locked = [], set(), set()

    def release_free(k):  # the accesses from index k on are still to come
        future = {v for _, v in accesses[k:]}
        for v in sorted(held, key=repr):
            if v not in future and all(c in locked for c in children[v]):  # @line L8
                steps.append(("unlock", v))
                held.discard(v)

    for k, (kind, v) in enumerate(accesses):
        p = path(parent, v)
        for u in p[p.index(top):]:
            if u not in locked:
                steps.append(("lock", u))  # @line L7
                locked.add(u)
                held.add(u)
                release_free(k)
        steps.append((kind, txn, v))
        release_free(k + 1)
    assert not held
    steps.append(("c", txn, None))
    return steps


def run(parent, plans, arrival, check=None):
    """Run the step lists of plans (txn -> steps). arrival lists the
    transaction of each step in the order the steps are offered; a waiting
    transaction keeps its place. check(manager) runs after each step. Return
    the schedule of reads, writes and commits, and the log of lock and unlock
    events. Raise RuntimeError if every transaction waits."""
    mgr = TreeLockManager(parent)
    pos = {t: 0 for t in plans}
    out, log, pending, blocked = [], [], list(arrival), set()
    while pending:
        k = next((k for k, t in enumerate(pending) if t not in blocked), None)
        if k is None:
            raise RuntimeError("deadlock: %r" % sorted(mgr.waits_for()))
        t = pending[k]
        step = plans[t][pos[t]]
        if step[0] == "lock":
            if not mgr.lock(t, step[1]):
                blocked.add(t)
                continue
            log.append(("lock", t, step[1]))
        elif step[0] == "unlock":
            mgr.unlock(t, step[1])
            log.append(("unlock", t, step[1]))
            blocked.clear()
        elif step[0] in "rw":
            if mgr.holder.get(step[2]) != t:
                raise RuntimeError("%r runs %r without the lock" % (t, step))
            out.append(step)
        else:
            out.append(step)
        pos[t] += 1
        pending.pop(k)
        if check:
            check(mgr)
    return tuple(out), log
test_tree_locking_protocol.py 180 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tree-locking-protocol/. The authors are listed in prov/AV253P.jsonl.

import random

import pytest

import dbsched
import tree_locking_protocol as tlp

#         a
#       /   \
#      b     c
#     / \   / \
#    d   e f   g
TREE = {"a": None, "b": "a", "c": "a", "d": "b", "e": "b", "f": "c", "g": "c"}


def test_rules_are_enforced() -> None:
    mgr = tlp.TreeLockManager(TREE)
    assert mgr.lock(1, "b")  # the first lock may be on any node
    with pytest.raises(ValueError):
        mgr.lock(1, "f")  # T1 does not hold c
    with pytest.raises(ValueError):
        mgr.lock(1, "a")  # the parent of b is above, not held
    assert mgr.lock(1, "d")
    mgr.unlock(1, "d")
    with pytest.raises(ValueError):
        mgr.lock(1, "d")  # no lock again after an unlock
    with pytest.raises(ValueError):
        mgr.unlock(1, "d")
    assert mgr.lock(2, "d") and not mgr.lock(3, "d")
    assert mgr.waits_for() == {(3, 2)}


def test_plan() -> None:
    assert tlp.plan(TREE, 1, [("w", "d"), ("w", "e")]) == [
        ("lock", "b"), ("lock", "d"), ("w", 1, "d"), ("unlock", "d"),
        ("lock", "e"), ("unlock", "b"), ("w", 1, "e"), ("unlock", "e"), ("c", 1, None)]
    assert tlp.plan(TREE, 2, [("r", "b"), ("r", "d")]) == [
        ("lock", "b"), ("r", 2, "b"), ("lock", "d"), ("unlock", "b"),
        ("r", 2, "d"), ("unlock", "d"), ("c", 2, None)]
    assert tlp.plan(TREE, 3, [("r", "f")])[0] == ("lock", "f")


def test_example() -> None:
    plans = {1: tlp.plan(TREE, 1, [("w", "d"), ("w", "e")]),
             2: tlp.plan(TREE, 2, [("r", "b"), ("r", "d")])}
    arrival = [1, 1, 1, 1, 2, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1]
    out, log = tlp.run(TREE, plans, arrival, check_state)
    assert dbsched.format(out) == "w1(d) r2(b) r2(d) c2 w1(e) c1"
    assert dbsched.conflict_serializable_orders(out) == [(1, 2)]
    assert not dbsched.is_recoverable(out)  # T2 read d from T1 and committed first
    assert ("unlock", 1, "d") in log and log.index(("unlock", 1, "d")) < log.index(("lock", 1, "e"))


def test_a_schedule_that_two_phase_locking_cannot_give() -> None:
    plans = {1: tlp.plan(TREE, 1, [("w", "d"), ("w", "e")]),
             2: tlp.plan(TREE, 2, [("w", "d")]),
             3: tlp.plan(TREE, 3, [("w", "e")])}
    arrival = [1, 1, 1, 1] + [2] * 4 + [3] * 4 + [1] * 5
    out, _ = tlp.run(TREE, plans, arrival, check_state)
    # Under 2PL, T1 would hold e from before w2(d) until w1(e), so w3(e) could not run.
    assert dbsched.format(out) == "w1(d) w2(d) c2 w3(e) c3 w1(e) c1"
    assert dbsched.conflict_serializable_orders(out) == [(3, 1, 2)]


def check_state(mgr):
    for t, done in mgr.locked.items():
        # The nodes that t has locked form a subtree: all but one have their parent in it.
        assert sum(1 for v in done if mgr.parent[v] not in done) == 1
        assert mgr.held(t) <= done
    for t, x in mgr.waiting.items():
        # A waiter holds the parent of the node it waits for, unless it holds nothing.
        assert mgr.holder.get(x) != t
        assert not mgr.locked.get(t) or mgr.holder.get(mgr.parent[x]) == t


def lock_order_edges(log):
    """(T, U) when T and U lock a common node and T locks it first."""
    first = {}
    for kind, t, v in log:
        if kind == "lock":
            first.setdefault(v, []).append(t)
    return {(ts[i], ts[j]) for ts in first.values()
            for i in range(len(ts)) for j in range(i + 1, len(ts))}


def topological_order(nodes, edges):
    indeg = {v: 0 for v in nodes}
    for _, b in edges:
        indeg[b] += 1
    ready = sorted(v for v in nodes if indeg[v] == 0)
    order = []
    while ready:
        v = ready.pop(0)
        order.append(v)
        for a, b in sorted(edges):
            if a == v:
                indeg[b] -= 1
                if indeg[b] == 0:
                    ready.append(b)
    return order if len(order) == len(nodes) else None


def check_output(out, log, plans, brute_force):
    rho = lock_order_edges(log)
    order = topological_order(sorted(plans), rho)
    assert order is not None  # Theorem 1: the lock order relation has no cycle
    for i in range(len(out)):
        for j in range(i + 1, len(out)):
            if dbsched.conflicts(out[i], out[j]):
                assert (out[i][1], out[j][1]) in rho
    assert dbsched.conflict_equivalent(out, dbsched.serial_schedule(out, order))
    if brute_force:
        assert tuple(order) in dbsched.conflict_serializable_orders(out)
    assert dbsched.committed(out) == set(plans)


def unlock_then_lock(log):
    """True if some transaction locks a node after it unlocked another one."""
    unlocked = set()
    for kind, t, _ in log:
        if kind == "unlock":
            unlocked.add(t)
        elif t in unlocked:
            return True
    return False


PAIRS = [
    {1: [("w", "d"), ("w", "e")], 2: [("r", "b"), ("r", "d")]},
    {1: [("w", "b"), ("w", "d")], 2: [("w", "d")]},
]


@pytest.mark.parametrize("programs", PAIRS)
def test_all_interleavings_of_two(programs) -> None:
    plans = {t: tlp.plan(TREE, t, acc) for t, acc in programs.items()}
    seqs = [[("r", t, "x")] * len(plans[t]) for t in sorted(plans)]
    orders = set()
    for arrival in dbsched.interleavings(seqs):
        out, log = tlp.run(TREE, plans, [a[1] for a in arrival], check_state)
        check_output(out, log, plans, brute_force=True)
        orders.add(tuple(topological_order(sorted(plans), lock_order_edges(log))))
    assert orders == {(1, 2), (2, 1)}


def test_opposite_orders_do_not_deadlock() -> None:
    # Under 2PL, w(d) w(e) against w(e) w(d) can deadlock. Here both start at b.
    plans = {1: tlp.plan(TREE, 1, [("w", "d"), ("w", "e")]),
             2: tlp.plan(TREE, 2, [("w", "e"), ("w", "d")])}
    seqs = [[("r", t, "x")] * len(plans[t]) for t in sorted(plans)]
    rng = random.Random(2)
    for _ in range(3000):
        arrival = [a[1] for a in dbsched.random_schedule(rng, seqs)]
        out, log = tlp.run(TREE, plans, arrival, check_state)
        check_output(out, log, plans, brute_force=True)


def heap_tree(n):
    return {"n%d" % i: ("n%d" % (i // 2) if i > 1 else None) for i in range(1, n + 1)}


def test_random_interleavings_of_up_to_six() -> None:
    rng = random.Random(7)
    tree = heap_tree(15)
    nodes = sorted(tree)
    early, unrecoverable = 0, 0
    for n in [3] * 400 + [6] * 300:
        programs = {t: [(rng.choice("rw"), rng.choice(nodes)) for _ in range(rng.randint(1, 3))]
                    for t in range(1, n + 1)}
        plans = {t: tlp.plan(tree, t, acc) for t, acc in programs.items()}
        arrival = [t for t in plans for _ in plans[t]]
        rng.shuffle(arrival)
        out, log = tlp.run(tree, plans, arrival, check_state)  # never a deadlock
        check_output(out, log, plans, brute_force=(n <= 3))
        early += unlock_then_lock(log)
        unrecoverable += not dbsched.is_recoverable(out)
    assert early > 0 and unrecoverable > 0  # not two-phase, and not recoverable

History

Bayer and Schkolnick (1977) studied lock coupling for concurrent operations on B-trees, where a process keeps the lock on a node until it holds the lock on the child. Silberschatz and Kedem (1980) stated the tree protocol for transactions on hierarchical databases and proved that it gives serializable schedules without deadlocks, although it is not two-phase. Kedem and Silberschatz then extended it to directed acyclic graphs and to shared locks, and Bernstein, Hadzilacos and Goodman (1987) present tree locking as the standard example of a protocol that is correct without the two-phase rule.

References

  1. Abraham Silberschatz and Zvi Kedem, Consistency in hierarchical database systems, Journal of the ACM 27(1), 1980, pages 72 to 80, the tree protocol with exclusive locks, and the proof that its schedules are serializable and free of deadlocks
  2. Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 3 (tree locking, as a locking protocol that is not two-phase)

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-request
  • a full proof of time.per-transaction
  • 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
  • at least three sources
  • a scene preset for the example