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
- Model
- Word RAM
- Properties
- deterministiconline
- Evidence
- Proof sketchCode in 1 languages
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
LOCK(T, x)- 1
if T has locked x before then reject ▷ no lock again - 2
if T holds some lock and does not hold parent(x) then reject - 3
if another transaction holds x then T waits; try again later - 4
grant the lock on x to T; record x as locked by T UNLOCK(T, x)- 5
T must hold x; release it ▷ at any time PLAN(T, accesses) ▷ one way to follow the rules- 6
t ← the lowest common ancestor of the accessed nodes; lock t first - 7
before each access to v, lock the nodes on the path from t to v that are not locked yet, from the top down - 8
after each lock and each access, unlock each held node that has no later access 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 with children and ; has the children and , and has and . Let and . Both start at , the lowest common ancestor of the nodes they use.
| step | event | locks held after the step |
|---|---|---|
| 1 | locks , then | 1: , |
| 2 | ; unlocks , which it needs no more | 1: |
| 3 | asks for and waits | 1: |
| 4 | locks , then unlocks : it has no access to , and both its children on the paths are locked | 1: |
| 5 | locks ; ; it locks and unlocks | 1: ; 2: |
| 6 | ; unlocks ; | 1: |
| 7 | ; unlocks ; |
The output is . It is conflict equivalent to . is not two-phase, since it unlocked before it locked . The schedule is also not recoverable: read from and committed first.
A transaction would lock only , its first lock, and run at any moment, since no other transaction uses , or . If were instead, the opposite order of , then two-phase locking could deadlock on and . Here both transactions must lock first, and the second one waits there without any lock.
Correctness
The proofs are on the proof page. Let mean that and lock a common node and 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 through , while it holds the root. So their order on , and on all of the subtree of , 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 . The conflict graph has no cycle, and by the serializability theorem the schedule is conflict serializable.
- No deadlock. If waited in a cycle, each for a node that holds, then the history can be extended legally so that each gets after . This gives a cycle of , 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 is a finite sequence of events and on the nodes, and holds from its lock of to its unlock of , or to the end of . The history is legal if:
- (A1) each transaction locks each node at most once (line L1);
- (A2) each lock by , other than the first lock of , is of a node whose parent 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 be the set of nodes that locks in , and the node of its first lock. Define the relation by when , both lock some node , and locks before does.
Lemma 1 (the locked nodes form a subtree). In a legal history, every node of other than has its parent in , locked earlier. So every node of is a descendant of (or itself), and the path from to it lies in , locked from the top down.
Proof. By (A2), when locks it holds the parent of , which it locked earlier. Follow parents from : the lock times go down strictly, so the walk stops, and it can stop only at .
Theorem 1 (the lock order has no cycle). For every legal history , the relation has no cycle.
Proof. By induction on the number of nodes of the tree.
Base. If the tree is one node , then each transaction locks only , at most once, and means that the lock of by comes first. This is a strict total order on the transactions that lock , so it has no cycle.
Step. Let be the root, its children and their subtrees, each with fewer nodes than the tree. Let be the set of transactions that lock . The root has no parent, so by (A2) a lock of is the first lock of its transaction, and for each . Number as in the order of their locks of . By (A1) and (A3), the times in which they hold are disjoint intervals, in the same order.
Let be restricted to the events on the nodes of . It is a legal history on the tree . (A1) and (A3) carry over. For (A2), let lock in , not as its first lock in . If , the lock is not the first lock of in either, so holds the parent of , which is in . The case does not happen: by Lemma 1 the earlier node that locked has the path from to in , locked from the top down. If , the path goes through , so was locked before . If , then is in and is a descendant of , so , which is the first lock of . Both contradict the choice of . The relation is restricted to pairs that both lock a node of , with the order on that node. So is the union of the pairs for , which come from , and of the relations . By induction, no has a cycle.
Claim A. If and both lock , then locks first exactly when . Indeed, locks while it holds (A2), so inside its interval on , and the same holds for . The intervals are disjoint and in the order of the indices.
Claim B. If are joined by a path with , all of its edges in the same , then . Indeed, and lock nodes of , so by Lemma 1, with , both lock . If , then locks first by Claim A, so , and with the path this is a cycle of , which cannot be.
Now let be a cycle of . A transaction does not lock , so by Lemma 1 all of lies in the subtree of , inside one . An edge between two transactions outside comes from a common node, which is not , so the two lie in the same , and the edge is in .
- If has no member of , all its members lie in one , and is a cycle of . This cannot be.
- Otherwise cut at its members of into segments from to whose inner members are not in . A segment of one edge comes from a node that is , so , or that is in some , so by Claim B. A segment with inner members has all of them in one , and its first and last edges come from nodes in that too, so it is a path in . If (the only member of on ), this path is a cycle of , which cannot be; else by Claim B. So the index goes up strictly along every segment, and it cannot come back to its start.
Corollary 1 (serializability). Under the protocol, every schedule, and every prefix of one, is conflict serializable, and every topological order of is an equivalent serial order.
Proof. A transaction reads or writes a node only while it holds the lock on it. If comes before a conflicting , then holds at and at . By (A3) the two intervals are disjoint, so the one of comes first, and . So every edge of the conflict graph is in , 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.
Theorem 2 (no deadlock). In every state that the protocol reaches, the wait-for graph has no cycle.
Proof. Let , , be a cycle: each waits for the node , which holds (indices mod ). Each holds a lock, since waits for it, so its request is not its first lock. The request passed lines L1 and L2, so never locked , and it holds , the parent of . A waiting transaction takes no step, so it still holds . Let be the history so far. Extend it as follows.
- Each unlocks every node that it holds except . Now is held only if , by .
- It is not true that for all , since then for all , and the sum around the cycle gives . Choose with , so is free.
- For (going back around the cycle, turns): locks , then unlocks and . At the turn of with , the node is free, because , the only possible holder, had its turn before and unlocked .
Every lock of the extension is legal: holds , has never locked , and is free. So the extended history is legal. In , locked in , before locks it in the extension, so for every . This is a cycle of , which contradicts Theorem 1.
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 be the union of the paths from the top node (line L6, the lowest common ancestor of the accessed nodes) to each accessed node. The planner locks only nodes of , each at most once, and always the whole path from to the next accessed node, from the top down (line L7). So the locked nodes are closed under parents inside , and on a path the nodes that are still to be locked come after the ones that are locked. When it locks , the parent of is in and was locked. It was not unlocked, because line L8 unlocks a node only when every child of it in is locked, and was not. The first lock is . 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 are locked, since every node of lies on the path to an accessed node and all of them were locked. So line L8 unlocks all of them.
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 , which is conflict serializable but not recoverable. The protocol is also not two-phase: in the same example unlocks before it locks .
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 ; and Corollary 1 with the helper dbsched, against the serial schedule in a topological order of , 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 and 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 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 accesses in a tree of height locks at most the nodes of paths, so locks, each 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 for 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, comes from the tree protocol ( holds , and and start at and ), but not from two-phase locking, since would have to hold from before until . In the other direction, comes from two-phase locking, but not from the tree protocol, since must lock 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 above and : and both hold shared, writes before does, and writes before 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.
# 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag AV253P Edit this page History Report an error Markdown