Algorithm Search⌘K

Data structureintro

Lock table

Also called lock manager, lock compatibility matrix.

A hash table from each locked item to its granted group and a FIFO queue of waiting requests, with a compatibility matrix of lock modes. It is the core of a lock manager.

Time
O(1 + (1 + a) g) expected releaseO(1 + g + q) expected requestO(k^2) wait-for-graph
Space
O(L) extra
Where
L = the number of granted and waiting requests in the table; a = the number of waiting requests that a release grants; g = the number of holders of the item; k = the number of active transactions; q = the number of requests that wait on the item

A lock table is the data structure inside the lock manager of a database system. It is a hash table keyed by the name of a data item. The entry of an item holds the granted group, the transactions that hold a lock on the item with their modes, and a FIFO wait queue of requests that cannot be granted yet. A compatibility matrix tells which modes can be held together by different transactions. A scheduler such as two-phase locking calls the table for every read and write, and the wait-for graph for deadlock detection is read from it.

In plain words

Think of a desk with one card for each file in use. The card lists who uses the file now and how: reading, which many people can do at the same time, or writing, which needs the file alone. Below them, the card lists the people who wait, in the order they came.

When a person asks for a file, the clerk finds its card. If nobody waits and the new use goes with the current uses, the person gets the file. If not, the name goes at the end of the waiting list. When a person gives the file back, the clerk lets in people from the top of the list while each one goes with the uses that remain. A reader who wants to write goes to the front of the list.

If the waiting people make a closed circle, the clerk sends one away.

The abstract type

The table holds locks of transactions on items. A lock has a mode from a finite set MM. The modes come with:

  • a compatibility relation: compat(h,m)\mathit{compat}(h, m) is true when a transaction can be granted mode mm on an item while another transaction holds mode hh on it;
  • a supremum sup⁡(a,b)\sup(a, b), the weakest mode that is at least as strong as aa and bb, with compat(sup⁡(a,b),m)\mathit{compat}(\sup(a, b), m) true exactly when compat(a,m)\mathit{compat}(a, m) and compat(b,m)\mathit{compat}(b, m) are both true.

For shared (S) and exclusive (X) locks, the matrix is:

held \ requested S X
S yes no
X no no

and sup⁡(S,X)=X\sup(S, X) = X. The matrix of multiple granularity locking has five modes, IS, IX, S, SIX and X, and the same table serves it.

The operations are:

  • request(T, x, m): ask for mode mm on xx. The result is granted or waits. A request by a transaction that already holds mode hh on xx is a conversion to sup⁡(h,m)\sup(h, m).
  • release(T, x): give up the lock of TT on xx. The result is the list of waiting requests that this grants.
  • cancel(T): take back the waiting request of TT, if there is one. A transaction that aborts while it waits needs this.
  • release_all(T): cancel(T) and then release every lock of TT. Strict two-phase locking calls it at commit or abort.
  • waits_for(): the edges T→UT \to U of the wait-for graph.

A transaction has at most one waiting request at a time, because it stops when a request waits.

Representation

  • The hash table. It maps an item to its entry. An item with no holder and no waiter has no entry, so the table holds only the items in use. Its size is O(L)O(L) for LL granted and waiting requests.
  • The entry of an item. It has the granted group, a map from a transaction to its mode; the group mode, the supremum of the granted modes, or none if the group is empty; and the wait queue, a list of requests (T,m,conversion)(T, m, \mathit{conversion}) in which every conversion comes before every new request.
  • The lists of a transaction. A map from each transaction to the set of items it holds locks on, and a map from each waiting transaction to the item it waits on. With them, release_all and cancel do not scan the whole table.

The test on line L6 compares the new mode with one group mode, not with each holder, because of the property of sup⁡\sup. A conversion of TT must be compared with the supremum of the other holders, without the old mode of TT, since a lock is never in conflict with another lock of the same transaction.

Operations

  1. REQUEST(T, x, m) ▷ granted or waits
  2. 1e ← the entry of x; make an empty one if x has none
  3. 2if T holds mode h on x then ▷ a conversion
  4. 3if sup(h, m) = h then return granted ▷ the lock T holds is enough
  5. 4if compat(the sup of the modes of the other holders, sup(h, m)) then
  6. set the mode of T to sup(h, m); return granted
  7. 5put (T, sup(h, m), conversion) into the queue after the last conversion
  8. return waits
  9. 6if the queue of e is empty and compat(group mode of e, m) then
  10. add (T, m) to the granted group; return granted
  11. 7append (T, m) to the queue of e; return waits
  12. RELEASE(T, x)
  13. 8remove T from the granted group of x
  14. 9group mode ← the sup of the modes that are left
  15. WAKE(x)
  16. WAKE(x)
  17. 10while the queue of x is not empty do
  18. 11r ← the head; if r.mode is not compatible with the group (without r.T, for a conversion) then stop
  19. 12remove r from the queue; grant r.mode to r.T; tell r.T to continue
  20. 13if x has no holder and no waiter then remove the entry of x

cancel(T) removes the request of TT from its queue and then calls WAKE, because the request it removes can be the head that blocks the others. release_all(T) calls cancel(T) and then RELEASE for each item of TT.

The wait-for graph. For each waiting request of TT on xx, add an edge T→UT \to U for each holder U≠TU \ne T of xx whose mode is not compatible with the mode that TT waits for, and for each transaction UU with a request ahead of TT in the queue of xx. The second kind of edge comes from FIFO order: TT cannot pass UU, even if the modes of TT and UU are compatible. A cycle in this graph is a deadlock (see Correctness), and the detector finds it with depth-first search.

Example

Take S and X modes on one item xx.

step call result granted group of xx queue of xx
1 request(1, x, S) granted (L6) 1:S
2 request(2, x, S) granted (L6) 1:S, 2:S
3 request(3, x, X) waits (L7) 1:S, 2:S 3:X
4 request(4, x, S) waits (L7) 1:S, 2:S 3:X, 4:S
5 request(1, x, X) waits (L5) 1:S, 2:S 1:X, 3:X, 4:S
6 release(2, x) grants 1:X 1:X 3:X, 4:S
7 release(1, x) grants 3:X 3:X 4:S
8 release(3, x) grants 4:S 4:S

At step 4, S is compatible with the group mode S, but T4T_4 still waits, because T3T_3 waits ahead of it. If T4T_4 could pass, a stream of readers could keep T3T_3 out forever. At step 5, T1T_1 asks to convert its S lock to X. The conversion goes to the front of the queue, so it waits only for T2T_2. After step 5, the wait-for graph has the edges

1→2,3→1,3→2,4→1,4→3.1 \to 2, \quad 3 \to 1, \quad 3 \to 2, \quad 4 \to 1, \quad 4 \to 3.

There is no cycle. There is no edge 4→24 \to 2: when T2T_2 leaves and nothing else changes, T4T_4 still waits for T1T_1 and T3T_3.

A conversion deadlock: T1T_1 and T2T_2 both hold S on xx, and both ask for X. Each conversion waits for the S lock of the other one, so the graph has the cycle 1→2→11 \to 2 \to 1. If the detector aborts T2T_2, release_all(2) releases its S lock, and WAKE grants X to T1T_1.

Correctness

The table keeps three invariants after each operation:

  1. Safety. The modes of two different transactions in a granted group are compatible.
  2. No lost wake-up. If the queue of xx is not empty, its head cannot be granted now: some other holder has a mode that is not compatible with the mode of the head.
  3. Bookkeeping. Each waiting transaction is in exactly one queue, at the item that it waits on.

Lines L4 and L6, and the grant in L12, add a mode only when it is compatible with the other holders, so they keep invariant 1. WAKE stops only when the queue is empty or the head does not fit, which gives invariant 2 after each release and cancel. A new request that waits at L7 or a conversion that waits at L5 becomes the head only when it does not fit.

From invariant 2 and the FIFO rule, every waiting transaction has at least one edge out of it in the wait-for graph: to an incompatible holder if it is the head, and to the head otherwise. Every edge is real: while UU keeps the lock or the place in the queue that gives the edge T→UT \to U, the request of TT is not granted. And the edges are complete: if every UU with an edge T→UT \to U leaves the item, then TT becomes the head with only compatible holders, and WAKE grants it. So a set of waiting transactions in which nobody can ever continue contains a cycle, and each cycle is such a set. A scheduler that runs strict two-phase locking on this table produces only conflict serializable and strict schedules, by the two-phase locking theorem. The full proofs are on the proof page.

Proof: The lock table grants only compatible locks, loses no wake-up, and its wait-for graph shows every deadlockfull

The modes come with compat\mathit{compat} and sup⁡\sup as on the page, with the property

compat(sup⁡(a,b),m)  ⟺  compat(a,m) and compat(b,m).(P)\mathit{compat}(\sup(a, b), m) \iff \mathit{compat}(a, m) \text{ and } \mathit{compat}(b, m). \tag{P}

For a set GG of modes let sup⁡G\sup G be the supremum of its elements, and say that compat(sup⁡∅,m)\mathit{compat}(\sup \emptyset, m) is true. By (P) and induction on ∣G∣|G|, compat(sup⁡G,m)\mathit{compat}(\sup G, m) holds exactly when compat(h,m)\mathit{compat}(h, m) holds for each h∈Gh \in G. For S and X modes, (P) holds by the table: sup⁡(a,b)\sup(a, b) is X unless a=b=Sa = b = S, and no mode is compatible with X.

For an item xx with entry ee, write gr(x)\mathit{gr}(x) for the granted group, a map from transactions to modes, and Q(x)Q(x) for the queue. For a request r=(T,m,c)r = (T, m, c) in Q(x)Q(x), its blockers are the holders U≠TU \ne T in gr(x)\mathit{gr}(x) with ¬compat(gr(x)[U],m)\neg\mathit{compat}(\mathit{gr}(x)[U], m). Say rr fits when it has no blockers. For a conversion, TT itself is in gr(x)\mathit{gr}(x), and its own mode is not a blocker.

The code tests "fits" with one sup. For a new request (T∉gr(x)T \notin \mathit{gr}(x)), rr fits exactly when compat(sup⁡gr(x),m)\mathit{compat}(\sup \mathit{gr}(x), m), by (P). For a conversion, rr fits exactly when compat(sup⁡(gr(x)∖T),m)\mathit{compat}(\sup(\mathit{gr}(x) \setminus T), m). These are the tests of lines L4, L6 and L11.

Invariants. Between operations:

  • (I1) For each xx and each two different T,UT, U in gr(x)\mathit{gr}(x), compat(gr(x)[T],gr(x)[U])\mathit{compat}(\mathit{gr}(x)[T], \mathit{gr}(x)[U]).
  • (I2) For each xx with Q(x)Q(x) not empty, the head of Q(x)Q(x) does not fit.
  • (I3) Each transaction has at most one request in all the queues together, and TT is in the map of waiting transactions with item xx exactly when TT has a request in Q(x)Q(x). In each queue, every conversion comes before every new request, and a conversion (T,m,true)(T, m, \mathit{true}) in Q(x)Q(x) has T∈gr(x)T \in \mathit{gr}(x).
  • (I4) An entry with no holder and no waiter is not in the table.

The compatibility relation is symmetric for S and X and for the matrix of multiple granularity locking. For (I1), we only need that a mode is added to gr(x)\mathit{gr}(x) when it is compatible with each mode of the other holders, in the order (held, requested) of the matrix.

Lemma 1 (monotone blocking). If a request rr in Q(x)Q(x) does not fit, and a step only adds a holder to gr(x)\mathit{gr}(x) or raises the mode of a holder from hh to sup⁡(h,m′)\sup(h, m'), then rr still does not fit.

Proof. Let UU be a blocker of r=(T,m,c)r = (T, m, c), with mode hh. If the step does not change UU, then UU is still a blocker. If it raises the mode of UU to h′=sup⁡(h,m′)h' = \sup(h, m'), then by (P), compat(h′,m)\mathit{compat}(h', m) would need compat(h,m)\mathit{compat}(h, m), which is false. So UU is still a blocker. □\square

Lemma 2. Each operation keeps (I1) to (I4).

Proof. All operations start in a state where the invariants hold. Look at the operations one at a time.

REQUEST, line L3. Nothing changes.

REQUEST, line L4. TT holds hh, and the new mode n=sup⁡(h,m)n = \sup(h, m) is compatible with the sup of the other holders, so with each of their modes. This keeps (I1). The step raises one mode, so by Lemma 1 a head that did not fit still does not fit, which keeps (I2). The queues do not change.

REQUEST, line L5. The conversion (T,n,true)(T, n, \mathit{true}) goes after the last conversion in Q(x)Q(x), so conversions stay first. TT did not wait before the call (the code refuses a request from a waiting transaction), and T∈gr(x)T \in \mathit{gr}(x), so (I3) holds. If Q(x)Q(x) was not empty and had a conversion or a new request at the head, the new conversion either goes behind the old head (when the old head is a conversion), or becomes the new head (when the queue has no conversion). In the second case, and when Q(x)Q(x) was empty, the new head is this conversion, and line L4 found that it does not fit, so (I2) holds. In the first case the head does not change. The granted groups do not change, so (I1) holds.

REQUEST, line L6. The queue is empty and mm is compatible with the group mode, so with each holder. This keeps (I1). No queue changes, and Q(x)Q(x) stays empty, so (I2) holds for xx; other items do not change.

REQUEST, line L7. The new request goes at the end. If Q(x)Q(x) was empty, the new head is this request, and it does not fit, since line L6 failed and the queue was empty. Otherwise the head does not change. (I3) holds as in L5.

RELEASE, lines L8 to L13. Removing a holder keeps (I1). Then WAKE runs. Each pass of the loop grants the head only if it fits, so (I1) holds after each grant: the new mode is compatible with every other holder. For a conversion, the grant replaces the mode of TT by the larger mode, and the other holders do not change. WAKE removes the granted request from the queue and from the map of waiting transactions, so (I3) holds. The loop stops when the queue is empty or the head does not fit, which is (I2) for xx. Line L13 removes the entry if it is empty, which is (I4). Other items do not change.

CANCEL. The request of TT leaves Q(x)Q(x) and the map. The relative order of the other requests does not change, so conversions stay first. Then WAKE runs, as above, and restores (I2) for xx, also when the removed request was the head.

RELEASE_ALL. It is a CANCEL followed by RELEASE calls, each of which keeps the invariants. □\square

Theorem 1 (safety). At every moment, two different transactions that hold locks on the same item hold compatible modes.

Proof. This is (I1), by Lemma 2 and induction on the number of operations, from the empty table. □\square

Theorem 2 (FIFO). A new request is granted only when every request that came to Q(x)Q(x) before it has been granted or cancelled. A conversion is granted only when every conversion that came to Q(x)Q(x) before it has been granted or cancelled.

Proof. Line L6 grants a new request only when Q(x)Q(x) is empty. WAKE grants only the head of the queue. A new request enters at the end, and later requests go behind it, except conversions, which go behind the conversions already there. So everything ahead of a new request came earlier, and a new request reaches the head only when all of them have left the queue. The same holds for conversions among conversions. □\square

The wait-for graph. The edges are T→UT \to U for each waiting request r=(T,m,c)r = (T, m, c) in Q(x)Q(x) and each UU that is a blocker of rr or has a request ahead of rr in Q(x)Q(x). Every UU with an edge into it is an active transaction: it holds a lock or waits.

Theorem 3 (every waiter has an out edge). If TT waits, then TT has at least one edge out of it.

Proof. Let rr be the request of TT in Q(x)Q(x). If rr is not the head, the head belongs to another transaction, by (I3), and gives the edge T→headT \to \mathrm{head}. If rr is the head, by (I2) it does not fit, so it has a blocker U≠TU \ne T. □\square

Theorem 4 (soundness and completeness of the edges). Let TT wait on xx with request rr, and let N(T)N(T) be the set of transactions UU with an edge T→UT \to U.

  1. While some U∈N(T)U \in N(T) keeps its lock on xx in the mode that gives the edge, or keeps its request ahead of rr in Q(x)Q(x), the request rr is not granted.
  2. If each U∈N(T)U \in N(T) releases its lock on xx or leaves Q(x)Q(x), and no other transaction joins gr(x)\mathit{gr}(x) meanwhile with a mode that blocks rr, then rr is granted.

Proof. (1) A request is granted only by WAKE, only as the head, and only if it fits. If UU has a request ahead of rr, then rr is not the head. If UU is a blocker with the same mode, rr does not fit. A blocker that raises its mode is still a blocker by Lemma 1.

(2) After the last U∈N(T)U \in N(T) leaves, every request ahead of rr in the original queue is gone, and a request that joined later went behind rr, unless it was a conversion of a holder and rr is a new request. Such a conversion belongs to a transaction VV that held a lock on xx already. If VV was a blocker of rr, it is in N(T)N(T) and has left. If not, its conversion goes ahead of rr, and TT gets the new edge T→VT \to V, so the hypothesis of (2) applies to the new set N(T)N(T) too. So at some point rr is the head. It has no blocker then: every blocker at the time of the request was in N(T)N(T) and left, and by hypothesis no new blocker came. The last call to RELEASE or CANCEL that removed a member of N(T)N(T) ran WAKE, and WAKE grants a head that fits. If rr became the head at that call, it was granted then, or WAKE granted the requests ahead of it and then reached rr. □\square

Theorem 5 (deadlock). Call a nonempty set DD of waiting transactions deadlocked if no transaction in DD can be granted until some transaction in DD acts. Since a waiting transaction does nothing until it is granted or aborted, a deadlocked set waits forever unless a transaction of DD is aborted.

  1. Each cycle of the wait-for graph is a deadlocked set.
  2. If every active transaction waits, the wait-for graph has a cycle.

Proof. (1) Let CC be a cycle. Each T∈CT \in C waits, because only a waiting transaction has edges out of it. Each T∈CT \in C has an edge to some U∈CU \in C. By Theorem 4 (1), TT is not granted while UU keeps its lock or its place, and UU waits too, so UU does not release anything or leave the queue unless it is granted or aborted. So the first transaction of CC to be granted would need an earlier grant in CC, which is impossible. So no transaction of CC is granted, unless one of them is aborted.

(2) Every edge goes to an active transaction, so if all active transactions wait, every node with an edge into it waits, and by Theorem 3 every waiting node has an edge out of it. Start at any waiting transaction and follow out edges. The walk stays among the finitely many waiting transactions, so it repeats a node, and the part between the two visits is a cycle. □\square

Part (2) is what a scheduler uses when all its transactions wait: it builds the graph, finds a cycle with depth-first search, and aborts one transaction on it. release_all of the victim then calls CANCEL, which removes its request and runs WAKE, so by Lemma 2 no waiting request is left behind a head that fits.

Theorem 6 (use with strict two-phase locking). Let a scheduler take an S lock through REQUEST before each read and an X lock before each write, let it run an action only after the lock is granted, and let it call release_all only at the commit or abort of a transaction. Then the output schedule is strict, and its committed projection is conflict serializable.

Proof. Each transaction is two-phase, because it releases no lock before its end, and holds every lock until then. Two conflicting actions pi(x)p_i(x) and qj(x)q_j(x) need locks on xx in modes that are not compatible (at least one is X). By Theorem 1 these locks are not held at the same time, so if pi(x)p_i(x) comes first, TiT_i released its lock before TjT_j got its lock, which is after the end of TiT_i. So every action that follows a write of another transaction on the same item follows the end of that transaction, which is the definition of a strict schedule. The schedule is a two-phase locked schedule, so by the two-phase locking theorem its committed projection is conflict serializable. □\square

The tests check (I1) to (I3) and Theorem 5 (2) on every state of a strict 2PL driver: all interleavings of three sets of two or three short transactions, and 55 random interleavings of four or six. They check Theorem 6 on each output with the brute force classes of the helper dbsched, which tries every serial order and does not use a conflict graph.

Complexity

The hash table gives the entry of an item in O(1)O(1) expected time. With gg holders and qq waiting requests on the item:

operation time notes
request, new O(1)O(1) expected L6 compares with the stored group mode
request, conversion O(1+g+q)O(1 + g + q) expected the sup of the other holders, and the place after the last conversion
release O(1+g)O(1 + g) expected, plus O(g)O(g) per request it grants the new group mode is a sup over the holders
release_all the sum over the items of the transaction
wait-for graph O(k2)O(k^2) each of the kk waiting transactions gets at most g+q≤2kg + q \le 2k edges

A real lock manager keeps a count of the holders of each mode in the entry. Then the group mode and the sup of the other holders come from the counts in O(∣M∣)O(|M|) time, a constant, and a request that does not wait costs O(1)O(1) expected. The space is O(L)O(L) for LL granted and waiting requests, plus O(k)O(k) for the lists of the transactions.

Variants

  • Update mode. Many systems add a mode U for a read that will probably be followed by a write. Two U locks are not compatible, so two transactions that read with intent to write cannot both hold the item and then deadlock in their conversions to X, as in the example. Systems differ in whether a new S request is compatible with a held U lock.
  • Intention modes. The five modes IS, IX, S, SIX and X of multiple granularity locking use the same table with a 5×55 \times 5 matrix. Lock names for key ranges, as in key-range locking, are also entries of the same table.
  • Lock escalation. When one transaction holds too many row locks in one table, the lock manager replaces them with one lock on the table. This saves memory and can cause new waits.
  • Other wait rules. A system can let a compatible new request pass the queue. That gives more concurrency and can starve a writer. A system can also refuse to wait: wait-die and wound-wait abort one side by timestamp instead, so no wait-for graph is needed. A timeout instead of a graph also breaks deadlocks, with false positives.
  • Latches on the table. In a multithreaded system the lock table is itself shared, so each bucket of the hash table has a short-term mutex (a latch). The latch protects the entry for the time of one call only.
  • Locks without waiting. Conservative two-phase locking asks for all the locks of a transaction in one call and grants all or none, so a waiting transaction holds nothing.

When to use it

Use a lock table in any scheduler that locks named items: two-phase locking and its variants, locking for B+ tree pages and key ranges, and locks on schema objects. It is the standard choice when transactions conflict often enough that waiting is cheaper than an abort and a restart. Where conflicts are rare, optimistic concurrency control avoids the cost of a table call for each access, and multiversion systems avoid locks for reads.

Pitfalls

  • A lost wake-up. A transaction that aborts while it waits must leave the queue through cancel, and cancel must call WAKE. If the cancelled request was the head, the requests behind it can fit now, and without WAKE they wait forever although nothing blocks them.
  • Conversions at the end of the queue. If T1T_1 holds S and T3T_3 waits for X, a conversion of T1T_1 to X at the end of the queue waits for T3T_3, which waits for T1T_1. This is a deadlock that the table itself made. Put conversions before new requests.
  • A conversion compared with its own lock. If line L4 compares the new mode with the full group mode, a transaction that holds S alone can never convert to X, because X is not compatible with its own S.
  • Edges only to the holders. A wait-for graph with edges only to holders misses waits that come from FIFO order. Then the detector can fail to see a deadlock in which some transaction waits behind another waiter.
  • Empty entries. An entry with no holder and no waiter must leave the hash table (L13), or the table grows with every item that was ever locked.
  • Hashed lock names. Some systems lock a hash of the key instead of the key. Two different keys with the same hash then conflict, which is safe but gives false waits.

Implementations

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

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()
lock_table.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lock-table/. The authors are listed in prov/J4XAN4.jsonl.

"""A lock table: a hash table from items to a granted group and a FIFO wait queue.

Each entry holds the granted group (a dict from transaction to its mode), the
group mode (the supremum of the granted modes) and a queue of waiting
requests. A request is granted at once only if it is compatible with the group
mode and nobody waits; otherwise it waits. A conversion (an upgrade of a lock
that the transaction already holds) goes ahead of all new requests in the
queue, behind earlier conversions. A release grants waiting requests from the
head of the queue for as long as they are compatible.

The modes, the compatibility matrix and the supremum are parameters, so the
same table serves S and X locks and the five modes of multiple granularity
locking. A transaction has at most one waiting request at a time.
"""

from collections import namedtuple

S, X = "S", "X"

# compatible[held][requested]
COMPAT_SX = {S: {S: True, X: False}, X: {S: False, X: False}}
SUP_SX = {(S, S): S, (S, X): X, (X, S): X, (X, X): X}

Request = namedtuple("Request", "txn mode conversion")


class Entry:
    """The lock entry of one item."""

    __slots__ = ("granted", "group", "queue")

    def __init__(self):
        self.granted = {}  # txn -> mode, in grant order
        self.group = None  # supremum of the granted modes, None if no holder
        self.queue = []  # waiting Requests, conversions first


class LockTable:
    def __init__(self, compat=COMPAT_SX, sup=SUP_SX):
        self.compat = compat
        self.sup = sup
        self.table = {}  # item -> Entry; a Python dict is a hash table
        self.waiting = {}  # txn -> item it waits on
        self.held = {}  # txn -> set of items it holds locks on

    # ----- helpers -----

    def _group_of(self, entry, without=None):
        g = None
        for t, m in entry.granted.items():
            if t != without:
                g = m if g is None else self.sup[(g, m)]
        return g

    def _ok(self, group, mode):
        return group is None or self.compat[group][mode]

    def _grant(self, entry, txn, item, mode):
        entry.granted[txn] = mode
        entry.group = self._group_of(entry)
        self.held.setdefault(txn, set()).add(item)

    # ----- operations -----

    def request(self, txn, item, mode):
        """Ask for a lock. Return True if it is granted now, False if txn waits."""
        if txn in self.waiting:
            raise ValueError("transaction %r already waits" % (txn,))
        entry = self.table.get(item)  # @line L1
        if entry is None:
            entry = self.table[item] = Entry()
        old = entry.granted.get(txn)
        if old is not None:  # @line L2
            new = self.sup[(old, mode)]
            if new == old:
                return True  # @line L3
            if self._ok(self._group_of(entry, without=txn), new):  # @line L4
                self._grant(entry, txn, item, new)
                return True
            k = 0  # @line L5
            while k < len(entry.queue) and entry.queue[k].conversion:
                k += 1
            entry.queue.insert(k, Request(txn, new, True))
            self.waiting[txn] = item
            return False
        if not entry.queue and self._ok(entry.group, mode):  # @line L6
            self._grant(entry, txn, item, mode)
            return True
        entry.queue.append(Request(txn, mode, False))  # @line L7
        self.waiting[txn] = item
        return False

    def _wake(self, item):
        """Grant requests from the head of the queue while they fit."""
        entry = self.table[item]
        grants = []
        while entry.queue:  # @line L10
            req = entry.queue[0]
            others = self._group_of(entry, without=req.txn) if req.conversion else entry.group
            if not self._ok(others, req.mode):  # @line L11
                break
            entry.queue.pop(0)  # @line L12
            self._grant(entry, req.txn, item, req.mode)
            del self.waiting[req.txn]
            grants.append((req.txn, item, req.mode))
        if not entry.granted and not entry.queue:  # @line L13
            del self.table[item]
        return grants

    def release(self, txn, item):
        """Release the lock of txn on item. Return the requests granted as a result."""
        entry = self.table.get(item)
        if entry is None or txn not in entry.granted:
            raise ValueError("%r holds no lock on %r" % (txn, item))
        del entry.granted[txn]  # @line L8
        entry.group = self._group_of(entry)  # @line L9
        self.held[txn].discard(item)
        return self._wake(item)

    def cancel(self, txn):
        """Remove the waiting request of txn, if any (used when txn aborts)."""
        item = self.waiting.pop(txn, None)
        if item is None:
            return []
        entry = self.table[item]
        entry.queue = [r for r in entry.queue if r.txn != txn]
        return self._wake(item)

    def release_all(self, txn):
        """Cancel the wait of txn and release all its locks, in sorted item order."""
        grants = self.cancel(txn)
        for item in sorted(self.held.get(txn, ()), key=repr):
            grants += self.release(txn, item)
        self.held.pop(txn, None)
        return grants

    # ----- inspection -----

    def mode(self, txn, item):
        entry = self.table.get(item)
        return None if entry is None else entry.granted.get(txn)

    def holders(self, item):
        entry = self.table.get(item)
        return {} if entry is None else dict(entry.granted)

    def queue(self, item):
        entry = self.table.get(item)
        return [] if entry is None else [(r.txn, r.mode) for r in entry.queue]

    def waits_for(self):
        """Edges (T, U): T waits for U because U holds an incompatible lock on
        the item, or U has a request ahead of T in the queue (FIFO)."""
        edges = set()
        for txn, item in sorted(self.waiting.items(), key=repr):
            entry = self.table[item]
            pos = next(k for k, r in enumerate(entry.queue) if r.txn == txn)
            mode = entry.queue[pos].mode
            for u, m in entry.granted.items():
                if u != txn and not self.compat[m][mode]:
                    edges.add((txn, u))
            for r in entry.queue[:pos]:
                if r.txn != txn:
                    edges.add((txn, r.txn))
        return edges


def find_cycle(edges):
    """Return the nodes of some cycle of the directed graph, or None."""
    succ = {}
    for a, b in sorted(edges, key=repr):
        succ.setdefault(a, []).append(b)
    color = {}
    for start in sorted(succ, key=repr):
        if start in color:
            continue
        stack = [(start, iter(succ.get(start, ())))]
        path = [start]
        color[start] = 1
        while stack:
            v, it = stack[-1]
            for w in it:
                if color.get(w) == 1:
                    return path[path.index(w):]
                if w not in color:
                    color[w] = 1
                    stack.append((w, iter(succ.get(w, ()))))
                    path.append(w)
                    break
            else:
                color[v] = 2
                stack.pop()
                path.pop()
    return None
test_lock_table.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lock-table/. The authors are listed in prov/J4XAN4.jsonl.

import random

import pytest

import dbsched
from lock_table import COMPAT_SX, S, X, LockTable, find_cycle


def check_invariants(lt):
    for item, entry in lt.table.items():
        modes = list(entry.granted.items())
        for a in range(len(modes)):
            for b in range(a + 1, len(modes)):
                assert COMPAT_SX[modes[a][1]][modes[b][1]], (item, modes)
        if entry.queue:
            # No lost wake-up: the head of the queue cannot be granted now.
            head = entry.queue[0]
            others = [m for t, m in entry.granted.items() if t != head.txn]
            assert any(not COMPAT_SX[m][head.mode] for m in others)
        for r in entry.queue:
            assert lt.waiting[r.txn] == item
    assert sum(len(e.queue) for e in lt.table.values()) == len(lt.waiting)


def run_strict_2pl(txns, arrival):
    """Strict 2PL on top of the lock table. arrival is the order in which the
    transactions offer their next action; a blocked transaction keeps its place.
    A deadlock aborts the largest transaction id on a cycle of the wait-for graph."""
    progs = {}
    for text in txns:
        acts = dbsched.parse(text)
        progs[acts[0][1]] = list(acts)
    lt = LockTable()
    out, pos, blocked = [], {t: 0 for t in progs}, set()
    pending = list(arrival)
    while pending:
        k = next((k for k, t in enumerate(pending) if t not in blocked), None)
        if k is None:
            cycle = find_cycle(lt.waits_for())
            assert cycle is not None, "every transaction waits but there is no cycle"
            assert all(t in blocked for t in cycle)
            victim = max(cycle)
            out.append(("a", victim, None))
            grants = lt.release_all(victim)
            blocked.discard(victim)
            pending = [t for t in pending if t != victim]
        else:
            t = pending[k]
            kind, _, item = progs[t][pos[t]]
            grants = []
            if kind in "rw":
                if not lt.request(t, item, S if kind == "r" else X):
                    blocked.add(t)
                    check_invariants(lt)
                    continue
            out.append(progs[t][pos[t]])
            pos[t] += 1
            pending.pop(k)
            if kind in "ca":
                grants = lt.release_all(t)
        for g in grants:
            blocked.discard(g[0])
        check_invariants(lt)
        for cycle_txn in blocked:
            assert cycle_txn in lt.waiting
    assert not lt.table and not lt.waiting
    return tuple(out)


def test_example():
    lt = LockTable()
    assert lt.request(1, "x", S) and lt.request(2, "x", S)
    assert not lt.request(3, "x", X)  # waits behind two readers
    assert not lt.request(4, "x", S)  # FIFO: does not pass the writer
    assert lt.queue("x") == [(3, X), (4, S)]
    assert not lt.request(1, "x", X)  # conversion goes to the front
    assert lt.queue("x") == [(1, X), (3, X), (4, S)]
    assert lt.waits_for() == {(1, 2), (3, 1), (3, 2), (4, 1), (4, 3)}
    assert lt.release(2, "x") == [(1, "x", X)]
    assert lt.holders("x") == {1: X}
    assert lt.release(1, "x") == [(3, "x", X)]
    assert lt.release(3, "x") == [(4, "x", S)]
    check_invariants(lt)


def test_upgrade_and_reentry():
    lt = LockTable()
    assert lt.request(1, "x", S)
    assert lt.request(1, "x", S)  # already held
    assert lt.request(1, "x", X)  # sole holder upgrades at once
    assert lt.request(1, "x", S)  # X covers S
    assert lt.mode(1, "x") == X
    with pytest.raises(ValueError):
        lt.release(2, "x")


def test_upgrade_deadlock_is_a_cycle():
    lt = LockTable()
    assert lt.request(1, "x", S) and lt.request(2, "x", S)
    assert not lt.request(1, "x", X)
    assert not lt.request(2, "x", X)
    assert sorted(find_cycle(lt.waits_for())) == [1, 2]
    with pytest.raises(ValueError):
        lt.request(1, "y", S)  # a waiting transaction cannot ask again
    assert lt.release_all(2) == [(1, "x", X)]
    assert find_cycle(lt.waits_for()) is None


def test_cancel_wakes_followers():
    lt = LockTable()
    assert lt.request(1, "x", X)
    assert not lt.request(2, "x", X)
    assert not lt.request(3, "x", S)
    assert lt.release_all(1) == [(2, "x", X)]
    assert lt.cancel(2) == []  # 2 holds now; nothing waits for it to cancel
    assert lt.release_all(2) == [(3, "x", S)]


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


@pytest.mark.parametrize("txns", SETS)
def test_strict_2pl_on_all_interleavings(txns):
    outcomes = set()
    for s in dbsched.interleavings(txns):
        out = run_strict_2pl(txns, [a[1] for a in s])
        assert dbsched.is_conflict_serializable(out)
        assert dbsched.is_strict(out)
        outcomes.add(out)
    assert len(outcomes) > 1


def test_strict_2pl_on_random_interleavings():
    rng = random.Random(11)
    items = "xyz"
    for n in [4] * 40 + [6] * 15:
        txns = []
        for t in range(1, n + 1):
            acts = ["%s%d(%s)" % (rng.choice("rw"), t, rng.choice(items)) for _ in range(rng.randint(1, 3))]
            txns.append(" ".join(acts + ["c%d" % t]))
        s = dbsched.random_schedule(rng, txns)
        out = run_strict_2pl(txns, [a[1] for a in s])
        assert dbsched.is_conflict_serializable(out)
        assert dbsched.is_strict(out)

History

Shared and exclusive locks, the compatibility matrix and lock conversions come from the System R work at IBM in the 1970s, where Gray, Lorie, Putzolu and Traiger also gave the intention modes of multiple granularity locking. Bernstein, Hadzilacos and Goodman (1987) describe a two-phase locking scheduler with a lock table and deadlock detection with the waits-for graph. Gray and Reuter (1993) describe a full lock manager, with the lock table as a hash table of lock headers, the granted and waiting requests of each lock, conversions, and deadlock detection.

References

  1. Jim Gray and Andreas Reuter, Transaction Processing, Concepts and Techniques, Morgan Kaufmann, 1993, Chapter 7 (lock modes and the compatibility matrix) and Chapter 8 (lock implementation, the lock table with its granted and waiting requests, conversions, and deadlock detection)
  2. Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 3 (the implementation of a two-phase locking scheduler with a lock table, and deadlock detection with the waits-for graph)
  3. Gerhard Weikum and Gottfried Vossen, Transactional Information Systems, Morgan Kaufmann, 2001, Chapter 4 (locking schedulers, lock conversions and deadlock handling)

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.release
  • a full proof of time.request
  • a full proof of time.wait-for-graph
  • 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)
WritingW4 complete
  • a review of the text: no review record reviews/J4XAN4/text.yaml