Algorithmadvanced
Key-range locking
Also called next-key locking, ARIES/KVL.
Locking for ordered indexes where a lock on a key also covers the gap below it, so range scans see no phantom inserts. Next-key locking is the usual form.
- Time
- O(log n + k) expected per-point-operationO(log n + (r + 1) k) expected per-scan
- Space
- O(l) extra
- Where
- k = the number of active transactions; l = the number of locks that are held; n = the number of keys in the index; r = the number of keys that a scan returns
- Model
- Word RAM
- Properties
- deterministiconline
- Evidence
- Proof sketchCode in 1 languages
Key-range locking protects the gaps between the keys of an ordered index, not only the keys. Without it, strict two-phase locking on the rows that a scan returns cannot stop the phantom problem: another transaction inserts a new key into the range, and a second scan sees it. In next-key locking, the usual form, a lock on a key that exists covers the key and the gap below it, down to the previous key, and a special key EOF covers the gap after the last key. A scan locks every key that it returns and also the next key after the range, and an insert must first test a lock on the next key above the new key, so it waits while somebody has read that gap. Mohan's ARIES/KVL (1990) is a well-known form for B-tree indexes. With locks held to the end, next-key locking gives serializable schedules, phantoms included, at the cost of one more lock per scan and per insert.
In plain words
Think of a row of numbered seats in a theatre, where some seats are taken. You want to know who sits between seats 3 and 6, and you want nobody to sit down there until you leave. Putting your hand on each taken seat in that part is not enough: a new person could sit in an empty seat between them.
So each taken seat also guards the empty seats just before it. You put your hand on every taken seat in your part and on the first taken seat after it. Somebody who wants to sit in an empty seat must first touch the next taken seat to the right. If your hand is on it, they wait. At the end of the row, a sign marked "end" plays the part of the next seat.
The problem
The input is a set of transactions that run operations on an index over an ordered set of keys: a range scan that returns the keys in , a point lookup, an insert and a delete. A transaction sees the index through these operations only, and the schedule must be serializable with respect to their results: each committed transaction must get the same answers as in some serial run. Locks on the keys that exist do not give this, because the answer of a scan, or of a lookup that finds nothing, depends on keys that do not exist yet. Predicate locking solves the problem in general, but testing whether two predicates overlap is expensive. In an ordered index, a range of key values is a predicate that is easy to cover with locks on keys that exist.
The model here is one index in main memory, a lock table with S and X locks, and locks held to the end of the transaction, as in strict two-phase locking. Each operation runs as one step once it has its locks; in a real B-tree a short latch on the page plays this part.
The algorithm
NEXT(k)- 1
return the smallest key in the index above k, or EOF if there is none SCAN(T, lo, hi)- 2
S-lock each key v of the index with lo ≤ v ≤ hi, and S-lock NEXT(hi) - 3
return the keys v of the index with lo ≤ v ≤ hi FETCH(T, k)- 4
if k is in the index then S-lock k else S-lock NEXT(k); return whether k is in the index INSERT(T, k)- 5
if k is in the index then S-lock k; return false ▷ a duplicate key - 6
test an instant X lock on NEXT(k) ▷ nobody else holds a lock on the gap - 7
X-lock k; insert k; return true DELETE(T, k)- 8
if k is not in the index then S-lock NEXT(k); return false - 9
X-lock k and NEXT(k); delete k; return true END(T)- 10
on abort, undo the inserts and deletes of T in reverse order; release all locks of T
Every lock may have to wait. After a wait, the operation computes its locks again, since the next key may have changed; locks that it got before the wait stay. Except for the instant lock of line L6, every lock is held until line L10. The instant lock is granted only when no other transaction holds any lock on the next key, and it is released at once. If the transaction already holds the next key, it keeps its lock.
The lock on in a delete keeps the gap closed after the key is gone: the deleted key leaves a larger gap, which the next key now covers, and nobody may insert into it or read it until the deleting transaction ends. The X lock on the deleted key keeps readers of the key itself away.
Example
A phantom that waits. The index holds the keys 2, 5 and 7. scans twice, and inserts 4.
| step | event | locks after the step |
|---|---|---|
| 1 | scans : it S-locks 5, and NEXT(6) = 7; the result is (5) | 1: S 5, S 7 |
| 2 | inserts 4: the instant X lock on NEXT(4) = 5 conflicts with , so waits | 1: S 5, S 7 |
| 3 | scans again; the result is (5) again; | |
| 4 | gets the instant lock on 5, X-locks 4, and inserts it; |
If the scan locked only the key 5 that it returned, then the insert of 4 would need only its own X lock on 4. It would run at step 2, and the second scan would return (4, 5): a phantom. The schedule would not be serializable, since would come both before and after .
A gap after a delete. With the same keys, deletes 5: it X-locks 5 and NEXT(5) = 7. Now looks up 6. The key 6 is not there, so S-locks NEXT(6), which is now 7, and waits. If aborts, 5 comes back; if commits, 5 is gone. In both cases sees a state that a serial run gives.
A deadlock. and both scan , so both hold S on 5 and 7. Then inserts 4 and waits for the S lock of on 5, and inserts 6 and waits for the S lock of on 7. The lock manager must abort one of them.
Correctness
The proof is on the proof page. Each key value of the domain is a slot, which may be empty. A scan reads all slots in its range, a lookup reads one slot, and a successful insert or delete writes one slot. The cover of is if it is in the index, and if it is not.
- The cover invariant. At every moment, each active transaction holds a lock on the current cover of every slot that it has used, and an X lock if it wrote the slot. Lines L2, L4, L5 and L8 lock the cover when an operation reads a slot, and lines L7 and L9 lock the new cover after a write. A cover can move only by an insert into the gap below it, which needs the instant X lock on it (line L6), or by a delete of the cover itself, which needs an X lock on it (line L9). So it can move only under a transaction that holds it in X, and that is never another holder.
- No phantoms. If two transactions use the same slot, one of them for a write, then both would hold a lock on its cover, one of them X. So the first one has ended before the second one uses the slot. The schedule of slot reads and writes is strict and conflict serializable in commit order, and every committed transaction gets the same results as in the serial run in commit order.
Proof: Next-key locking keeps a lock on the cover of every key value that a transaction used, so there are no phantomsfull
Setting. The index holds a set of keys from an ordered domain . EOF is a key above all of ; it is never in , but it can be locked. Each value is a slot, whether or not . The operations use the slots as follows:
- reads the slots (also the empty ones);
- reads the slot ;
- writes the slot if , and reads it if (a duplicate key);
- writes the slot if , and reads it otherwise.
The result of an operation depends only on the slots it reads or writes, and it changes only the slots it writes. A phantom is a change of a slot that a transaction read, by another transaction that is still running or that comes after it in the serial order. So it is enough to show that the schedule of slot reads and writes is strict and conflict serializable.
For , let be the smallest key of above , or EOF (line L1), and let the cover of be if and otherwise: the smallest element of that is at least . Locks are S or X, two locks of different transactions on one key are compatible only if both are S, and the lock table never has two incompatible holders on one key. A lock is held to the end of its transaction, except the instant lock of line L6, which is only tested. An operation runs in the same step in which it has all the locks that lines L2 to L9 ask for, computed on the current ; after a wait, the locks are computed again.
Lemma 1 (how a cover moves). Adding a key to changes the cover of exactly the slots with , and for those before the change, and after it. Removing a key changes the cover of exactly the slots with , which then becomes .
Proof. The cover is the smallest element of that is at least . A new element changes this minimum exactly when and is below the old minimum. Then no key lies in , so also none in , and . Removing changes the minimum exactly when was the minimum, and the next element is .
Invariant (I). After every step, for every active transaction and every slot that has read or written: holds a lock on , and the lock is X if has written .
Proof. By induction on the steps. At the start no transaction is active. A step that only grants locks, or that makes a transaction wait, does not change and only adds locks. A commit ends its transaction. The other steps are the following.
An operation of uses new slots. Look at just before the operation.
- : for , the cover of is a key of in , or the smallest key above , which is . Line L2 locks all of them.
- and the failed operations: line L4, L5 or L8 locks if and if not, which is , and does not change.
- A successful : line L7 locks in X, and after the insert .
- A successful : line L9 locks in X, and after the delete , because no key lies between and .
A change of by a transaction moves the cover of slots of . There are four ways that changes : a successful insert, a successful delete, and, at the abort of (line L10), the removal of a key that inserted and the return of a key that deleted. In each case holds an X lock on the old cover of every slot whose cover moves:
- An insert of by : by Lemma 1, the moved slots have the old cover , since . Line L6 tested an instant X lock on it in the same step, so no other transaction holds a lock on it.
- The return of a deleted key at the abort of : wrote the slot , so by (I) before the step, holds X on , the old cover of the moved slots.
- A delete of by : line L9 holds X on , the old cover of the moved slots.
- The removal of an inserted key at the abort of : wrote the slot and , so by (I), holds X on .
So if held a lock on the old cover, it would hold a lock that is incompatible with the X lock of on the same key. This cannot be, so no slot of another active transaction moves. If and the change comes from an operation, the new cover is after an insert (X by line L7) or after a delete (X by line L9). If and the change comes from the abort, ends in this step, and (I) says nothing about it.
Releases. Locks are released only at the end of their transaction, and the instant lock of line L6 is never kept, so no step removes a lock that (I) needs.
Theorem 1 (conflicting slot accesses do not overlap). If reads or writes the slot , and later another transaction makes an access to that conflicts with it (one of the two is a write), then ended before the access of .
Proof. Suppose is still active after the step of . By (I) after this step, and both hold a lock on the same key , and one of them holds X. The lock table never has such a pair.
Corollary 1 (no phantoms). The schedule of slot accesses is strict, and its committed projection is conflict equivalent to the serial schedule in commit order. Each committed transaction gets the same results as in the serial run of the committed transactions in commit order, and the final set of keys is the same.
Proof. By Theorem 1, every access that follows a write of another transaction to the same slot comes after the end of that transaction, so the schedule is strict. For committed and with conflicting accesses, the access of first, Theorem 1 puts the commit of before the access of , so before the commit of ; all conflicting pairs are in commit order.
For the results: by Theorem 1, between a write of a slot by a transaction that aborts and the abort, no other transaction uses the slot, and the undo of line L10 gives it back the value it had before the first write of . So the aborted transactions can be removed without changing what any other operation sees. The value of a slot that an operation of a committed transaction sees is then the value written by the last write before it, which by the order of the conflicting pairs is the last write in the serial run in commit order. The result of an operation depends only on the values of its slots, so it is the same as in the serial run, and so are the final values of all slots.
Deadlocks. The method does not prevent deadlocks: two transactions that have scanned the same range and then both insert into it each wait for the S lock of the other on a next key. The driver of the tests aborts the largest transaction id on a cycle of the wait-for graph; the proof above covers the undo of an aborted transaction.
What the tests check. The tests check (I) after every step of the driver, and Corollary 1 for every output, in three ways: against a serial run of the committed transactions in commit order on a plain sorted list, with the helper dbsched for strictness and conflict equivalence on the slots, and by brute force over all serial orders for up to three committed transactions. They do this for all interleavings of four pairs of programs (a scan against an insert into the range, a missed lookup against an insert into the gap, a gap below EOF, and a delete against a scan) and for 600 random interleavings of three or five transactions. They also run a naive variant that locks only the keys that exist and that the operation touches, and they check that it gives phantoms, in each of the four pairs and in the random runs.
Complexity
- Point operations. A lookup, insert or delete finds its key and the next key with one search of the index, in a B+ tree, and asks for one or two locks. In the code, a lock request compares with the holders of the key, up to of them, so an operation costs expected time. The code keeps the keys in a sorted list and scans it, which is simpler and slower.
- Scans. A scan that returns keys takes locks, so expected time.
- Space. The lock table holds the locks that are held, ; one scan adds one lock more than plain row locking.
- Concurrency. A lock on a key also blocks inserts into the gap below it. This can block more than the range that a scan asked for: with the keys 2, 5 and 7, a scan of locks the key 7, so it also blocks a delete of 7, which it did not read. With the keys 2, 5 and 9, it locks 9 and blocks inserts of 7 and 8, outside its range.
Properties
- Serializable with respect to the results. With locks held to the end, the transactions see the index as in a serial run, phantoms included (shown above).
- Strict. Every write holds its X lock to the end, so the schedules are strict and an abort needs no cascade.
- Not deadlock free. Scans followed by inserts into the same range can deadlock, as in the example. A wait-for graph or a timeout finds them.
- Locks only keys. A lock is asked for only on a key that is in the index at that moment, on EOF, or on the key that is being inserted. The lock table tests keys for equality and needs no predicate test.
Variants and improvements
- ARIES/KVL. Mohan's method for B-trees locks key values, and it refines the durations of the locks of inserts and deletes; it also handles indexes with duplicate keys, where a key value has a list of row ids.
- Previous-key locking. The same idea with the gaps above the keys: a lock on a key covers the gap up to the next key, and inserts test the previous key. A key below all others plays the part of EOF.
- Range lock modes. Lomet (1993) treats the key and the gap beside it as separate resources and gives modes that lock one without the other, so that an insert into a gap does not wait for a reader of the key, and a reader of a key does not block the gap. SQL Server, for example, has modes of this kind for its serializable level.
- Gap locks. MySQL InnoDB, for example, uses next-key locks under its default level, and has gap locks that cover only the gap without the key.
- Coarser locks. Multiple granularity locking can instead lock the whole table in S for a scan. This also stops phantoms, but it blocks every writer of the table.
When to use it
Use key-range locking when a lock-based system must give serializable range scans on a B-tree, or must make "not found" stay true for the rest of a transaction, for example for a check of a unique key. It is the standard answer to the phantom problem in systems with two-phase locking. Where most transactions only read, multiversion schemes, for example serializable snapshot isolation, avoid the read locks; where the range is not a range of one index, a predicate or table lock is needed.
Pitfalls
- Forgetting the next key after a range. A scan that locks only the keys that it returns lets an insert into the last gap through, and a lookup that finds nothing and locks nothing lets the key appear later.
- Releasing the next-key lock of a delete. If a delete releases its lock on the next key before the commit, another transaction can read the larger gap and then see the key come back at an abort.
- Locking the next key too late. The next key must be computed and locked in the same step as the insert or the read, under the latch of the page. After a wait, it must be computed again: the old next key may have been deleted, or a new key may lie in between.
- The gap is larger than the range. A lock on the next key blocks inserts into the whole gap below it, so a short scan near a sparse part of the index can block many inserts. Range lock modes reduce this.
- The EOF key. The gap after the last key needs a lock too. An index that has no EOF key lets phantoms appear at the end of the key space.
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()
key_range_locking.py 247 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/key-range-locking/. The authors are listed in prov/VVNHG6.jsonl.
"""Next-key locking on an ordered index, with S and X locks held to the end.
A lock on a key that is in the index covers the key and the gap below it,
down to the previous key. EOF is a key above all others that covers the last
gap. A scan locks every key that it returns and the next key after the
range; a lookup that finds nothing locks the next key; an insert tests the
next key with an instant X lock; a delete keeps an X lock on the next key.
So a phantom cannot appear in a range or in a gap that a transaction read.
"""
import bisect
import math
S, X = "S", "X"
EOF = math.inf
class LockManager:
def __init__(self):
self.locks = {} # key -> {txn: mode}
self.waiting = {} # txn -> (key, mode)
def mode(self, txn, key):
return self.locks.get(key, {}).get(txn)
def try_lock(self, txn, key, mode, instant=False):
"""Grant mode on key to txn, or record a wait and return False. An
instant lock is only tested; nothing is kept unless txn held it."""
old = self.mode(txn, key)
new = X if X in (old, mode) else S
if old == new:
return True
for u, m in self.locks.get(key, {}).items():
if u != txn and not (m == S and new == S):
self.waiting[txn] = (key, new)
return False
if not instant:
self.locks.setdefault(key, {})[txn] = new
self.waiting.pop(txn, None)
return True
def release_all(self, txn):
self.waiting.pop(txn, None)
for key in [k for k, h in self.locks.items() if txn in h]:
del self.locks[key][txn]
if not self.locks[key]:
del self.locks[key]
def waits_for(self):
edges = set()
for txn, (key, mode) in self.waiting.items():
for u, m in self.locks.get(key, {}).items():
if u != txn and not (m == S and mode == S):
edges.add((txn, u))
return edges
class KeyRangeIndex:
"""An ordered set of keys with next-key locking. With naive=True, it
locks only the keys that exist and that the operation touches, which
lets phantoms through."""
def __init__(self, keys, naive=False):
self.keys = sorted(keys)
self.naive = naive
self.lm = LockManager()
self.undo = {} # txn -> list of (op, key) to undo on abort
def present(self, k):
i = bisect.bisect_left(self.keys, k)
return i < len(self.keys) and self.keys[i] == k
def next_key(self, k):
i = bisect.bisect_right(self.keys, k) # @line L1
return self.keys[i] if i < len(self.keys) else EOF
def needs(self, op):
"""The locks (key, mode, instant) that op needs now."""
name, k = op[0], op[1]
if name == "scan":
lo, hi = k, op[2]
out = [(v, S, False) for v in self.keys if lo <= v <= hi]
if not self.naive:
out.append((self.next_key(hi), S, False)) # @line L2
return out
if name == "fetch":
if self.present(k):
return [(k, S, False)]
return [] if self.naive else [(self.next_key(k), S, False)] # @line L4
if name == "insert":
if self.present(k):
return [(k, S, False)] # @line L5
nxt = [] if self.naive else [(self.next_key(k), X, True)] # @line L6
return nxt + [(k, X, False)] # @line L7
if name == "delete":
if not self.present(k):
return [] if self.naive else [(self.next_key(k), S, False)] # @line L8
return [(k, X, False)] + ([] if self.naive else [(self.next_key(k), X, False)]) # @line L9
raise ValueError("unknown operation %r" % (name,))
def execute(self, txn, op):
"""Run op, whose locks are held. Return (result, slot accesses)."""
name, k = op[0], op[1]
if name == "scan":
lo, hi = k, op[2]
found = tuple(v for v in self.keys if lo <= v <= hi) # @line L3
return found, [("r", v) for v in range(lo, hi + 1)]
if name == "fetch":
return self.present(k), [("r", k)]
if name == "insert":
if self.present(k):
return False, [("r", k)]
bisect.insort(self.keys, k)
self.undo.setdefault(txn, []).append(("insert", k))
return True, [("w", k)]
if not self.present(k):
return False, [("r", k)]
self.keys.remove(k)
self.undo.setdefault(txn, []).append(("delete", k))
return True, [("w", k)]
def attempt(self, txn, op):
"""Ask for the locks that op needs now, in order. If one must wait,
return None; the caller tries again later, and the locks are then
computed again. Otherwise run op."""
for key, mode, instant in self.needs(op):
if not self.lm.try_lock(txn, key, mode, instant):
return None
return self.execute(txn, op)
def end(self, txn, commit):
"""Commit, or abort and undo the changes of txn, then release its locks."""
for name, k in reversed(self.undo.pop(txn, [])):
if not commit: # @line L10
if name == "insert":
self.keys.remove(k)
else:
bisect.insort(self.keys, k)
self.lm.release_all(txn)
def find_cycle(edges):
"""The nodes of some cycle of the directed graph, or None."""
succ = {}
for a, b in sorted(edges):
succ.setdefault(a, []).append(b)
state = {}
for start in sorted(succ):
if start in state:
continue
path, stack = [start], [iter(succ[start])]
state[start] = 1
while stack:
for w in stack[-1]:
if state.get(w) == 1:
return path[path.index(w):]
if w not in state:
state[w] = 1
path.append(w)
stack.append(iter(succ.get(w, ())))
break
else:
state[path.pop()] = 2
stack.pop()
return None
def slot(k):
return "EOF" if k == EOF else "k%d" % k
def run(keys, programs, arrival, naive=False, check=None):
"""Run programs (txn -> list of operations) on an index with the given
keys. arrival lists the transaction of each step (each operation, and
the commit at the end) in the order the steps are offered; a waiting
transaction keeps its place. When every unfinished transaction waits,
abort the largest id on a cycle of the wait-for graph. check(index,
touched) runs after each step. Return the results of each committed
transaction, the schedule on the key slots, and the final keys."""
idx = KeyRangeIndex(keys, naive)
pos = {t: 0 for t in programs}
results = {t: [] for t in programs}
touched = {t: {} for t in programs} # txn -> {key: "r" or "w"}
out, 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:
cycle = find_cycle(idx.lm.waits_for())
if cycle is None:
raise RuntimeError("every transaction waits, but there is no cycle")
victim = max(cycle)
idx.end(victim, commit=False)
out.append(("a", victim, None))
results.pop(victim)
touched[victim] = {}
pending = [t for t in pending if t != victim]
blocked.clear()
else:
t = pending[k]
if pos[t] == len(programs[t]):
idx.end(t, commit=True)
out.append(("c", t, None))
touched[t] = {}
else:
got = idx.attempt(t, programs[t][pos[t]])
if got is None:
blocked.add(t)
continue
result, acts = got
results[t].append(result)
for kind, v in acts:
out.append((kind, t, slot(v)))
if touched[t].get(v) != "w":
touched[t][v] = kind
blocked.clear()
pos[t] += 1
pending.pop(k)
if check:
check(idx, touched)
return results, tuple(out), tuple(idx.keys)
def serial_results(keys, programs, order):
"""Run the programs one after the other on a plain sorted list."""
cur = sorted(keys)
results = {}
for t in order:
res = []
for op in programs[t]:
name, k = op[0], op[1]
if name == "scan":
res.append(tuple(v for v in cur if k <= v <= op[2]))
elif name == "fetch":
res.append(k in cur)
elif name == "insert":
res.append(k not in cur)
if k not in cur:
bisect.insort(cur, k)
else:
res.append(k in cur)
if k in cur:
cur.remove(k)
results[t] = res
return results, tuple(cur)
test_key_range_locking.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/key-range-locking/. The authors are listed in prov/VVNHG6.jsonl.
import random
import pytest
import dbsched
import key_range_locking as krl
from key_range_locking import EOF, S, X
KEYS = [2, 5, 7]
def test_next_key_and_the_locks_of_each_operation() -> None:
idx = krl.KeyRangeIndex(KEYS)
assert idx.next_key(5) == 7 and idx.next_key(4) == 5 and idx.next_key(7) == EOF
assert idx.needs(("scan", 3, 6)) == [(5, S, False), (7, S, False)]
assert idx.needs(("scan", 6, 8)) == [(7, S, False), (EOF, S, False)]
assert idx.needs(("fetch", 4)) == [(5, S, False)]
assert idx.needs(("fetch", 5)) == [(5, S, False)]
assert idx.needs(("insert", 4)) == [(5, X, True), (4, X, False)]
assert idx.needs(("insert", 5)) == [(5, S, False)]
assert idx.needs(("delete", 5)) == [(5, X, False), (7, X, False)]
assert idx.needs(("delete", 4)) == [(5, S, False)]
def test_instant_lock_is_not_kept() -> None:
lm = krl.LockManager()
assert lm.try_lock(1, 5, X, instant=True) and lm.mode(1, 5) is None
assert lm.try_lock(2, 5, S) and not lm.try_lock(1, 5, X, instant=True)
assert lm.waits_for() == {(1, 2)}
def check_state(idx, touched):
"""The cover invariant: for every slot that an active transaction used,
it holds a lock on the key that covers the slot now, X if it wrote it."""
for t, slots in touched.items():
for v, kind in slots.items():
cov = v if idx.present(v) else idx.next_key(v)
m = idx.lm.mode(t, cov)
assert m is not None and (kind == "r" or m == X), (t, v, cov, m)
def violations(keys, programs, results, out, final):
"""The ways in which a run is not like the serial run in commit order."""
bad = []
order = [a[1] for a in out if a[0] == "c"]
want, want_final = krl.serial_results(keys, {t: programs[t] for t in order}, order)
if want != results or want_final != final:
bad.append("results")
cp = dbsched.committed_projection(out)
if not dbsched.conflict_equivalent(cp, dbsched.serial_schedule(cp, order)):
bad.append("conflicts")
if not dbsched.is_strict(out):
bad.append("strict")
if len(order) <= 3 and not dbsched.is_conflict_serializable(out):
bad.append("serializable")
return bad
def _arrivals(programs):
seqs = [[("r", t, "x")] * (len(programs[t]) + 1) for t in sorted(programs)]
for a in dbsched.interleavings(seqs):
yield [x[1] for x in a]
def test_the_phantom_is_blocked() -> None:
programs = {1: [("scan", 3, 6), ("scan", 3, 6)], 2: [("insert", 4)]}
arrival = [1, 2, 1, 1, 2]
results, out, final = krl.run(KEYS, programs, arrival, check=check_state)
assert results == {1: [(5,), (5,)], 2: [True]} and final == (2, 4, 5, 7)
assert dbsched.format(out) == "r1(k3) r1(k4) r1(k5) r1(k6) r1(k3) r1(k4) r1(k5) r1(k6) c1 w2(k4) c2"
# Without the lock on the next key, the insert gets in between the two scans.
results, out, final = krl.run(KEYS, programs, arrival, naive=True)
assert results[1] == [(5,), (4, 5)]
assert not dbsched.is_conflict_serializable(out)
def test_deadlock_and_undo() -> None:
# Both scan, then both insert into the scanned range: each instant X waits for the other.
programs = {1: [("scan", 3, 6), ("insert", 4)], 2: [("insert", 1), ("scan", 3, 6), ("insert", 6)]}
arrival = [2, 1, 2, 1, 2, 1, 2]
results, out, final = krl.run(KEYS, programs, arrival, check=check_state)
assert ("a", 2, None) in out and results == {1: [(5,), True]}
assert final == (2, 4, 5, 7) # the insert of 1 by T2 is undone
assert violations(KEYS, programs, results, out, final) == []
PROGRAMS = [
{1: [("scan", 3, 6), ("scan", 3, 6)], 2: [("insert", 4)]},
{1: [("fetch", 4), ("fetch", 4)], 2: [("insert", 4), ("delete", 5)]},
{1: [("fetch", 8), ("scan", 6, 8)], 2: [("insert", 8)]}, # the gap below EOF
{1: [("delete", 5), ("insert", 3)], 2: [("scan", 4, 6), ("fetch", 3)]},
]
@pytest.mark.parametrize("programs", PROGRAMS)
def test_all_interleavings(programs) -> None:
naive_bad = 0
for arrival in _arrivals(programs):
results, out, final = krl.run(KEYS, programs, arrival, check=check_state)
assert violations(KEYS, programs, results, out, final) == []
r, o, f = krl.run(KEYS, programs, arrival, naive=True)
naive_bad += bool(violations(KEYS, programs, r, o, f))
assert naive_bad > 0 # every one of these pairs has a phantom without next-key locks
def random_programs(rng, n):
programs = {}
for t in range(1, n + 1):
ops = []
for _ in range(rng.randint(1, 3)):
kind = rng.choice(["scan", "fetch", "insert", "insert", "delete"])
if kind == "scan":
lo = rng.randint(1, 8)
ops.append((kind, lo, min(8, lo + rng.randint(0, 3))))
else:
ops.append((kind, rng.randint(1, 8)))
programs[t] = ops
return programs
def test_random_interleavings() -> None:
rng = random.Random(4)
aborts, naive_bad = 0, 0
for n in [3] * 400 + [5] * 200:
keys = sorted(rng.sample(range(1, 9), rng.randint(2, 5)))
programs = random_programs(rng, n)
arrival = [t for t in programs for _ in range(len(programs[t]) + 1)]
rng.shuffle(arrival)
results, out, final = krl.run(keys, programs, arrival, check=check_state)
assert violations(keys, programs, results, out, final) == []
aborts += bool(dbsched.aborted(out))
r, o, f = krl.run(keys, programs, arrival, naive=True)
naive_bad += bool(violations(keys, programs, r, o, f))
assert aborts > 0 and naive_bad > 0
History
Eswaran, Gray, Lorie and Traiger (1976) described phantoms, which locks on single rows cannot stop, and proposed predicate locks, which are costly to test. For indexes, Mohan (1990) described ARIES/KVL, which locks key values in a B-tree and closes each gap with a lock on the next key, with locks of instant and commit duration. Lomet (1993) treated keys and the ranges between them as separate lockable resources, and Graefe (2010) surveyed these methods and their later forms. MySQL InnoDB, for example, uses next-key locks, and SQL Server has key-range locks for its serializable level.
References
- C. Mohan, ARIES/KVL: a key-value locking method for concurrency control of multiaction transactions operating on B-tree indexes, Proceedings of the 16th International Conference on Very Large Data Bases (VLDB), 1990, pages 392 to 405, next-key locking on the key values of a B-tree index, with instant and commit-duration locks for inserts and deletes
- David B. Lomet, Key range locking strategies for improved concurrency, Proceedings of the 19th International Conference on Very Large Data Bases (VLDB), 1993, pages 655 to 664, locks on key ranges as resources, and lock modes for a key and the gap beside it
- Goetz Graefe, A survey of B-tree locking techniques, ACM Transactions on Database Systems 35(3), 2010, article 16, the sections on key-range locking, next-key locking and the protection of gaps against phantoms
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 VVNHG6 Edit this page History Report an error Markdown