Algorithm Search⌘K

Algorithmcore

Multiple granularity locking

Also called intention locks, hierarchical locking, MGL.

Lock the nodes of a hierarchy of database, tables and rows. Intention modes IS, IX and SIX on the ancestors let a coarse lock and a fine lock see each other with one test per node.

Time
O(d k) expected per-row-access · per-subtree-lock
Space
O(d) extra
Where
d = the depth of the hierarchy; k = the number of active transactions; n = the number of rows under the locked node
Properties
deterministiconline

Multiple granularity locking (MGL) lets transactions lock data at different sizes: a whole database, a table, a page or one row. The data items form a tree, and a lock on a node covers every node below it. To make a lock on a table and a lock on one of its rows see each other, a transaction must first put an intention lock on every ancestor of the node it locks: IS (intention shared) before a shared lock below, IX (intention exclusive) before an exclusive lock below. With the five modes IS, IX, S, SIX and X and their compatibility matrix, the lock table finds every conflict with one test per node on the path from the root. Gray, Lorie and Putzolu introduced the method in 1975 for System R. With the two-phase rule on top, the schedules are conflict serializable, exactly as if each transaction had locked every row that it covers.

In plain words

Think of a building with floors and rooms. You can book a single room, or a whole floor at once. If you book a floor for a quiet meeting, nobody else may move furniture in any room of that floor. But the person who books one room does not walk past your floor booking at the desk; the clerk would have to check every room of the floor.

So each person who books a room first puts a small note on the floor and on the building: "someone is working in a room here". A person who wants the whole floor sees the notes and knows at once whether a room is in use. Notes go on from the top down, and come off from the bottom up. Notes do not clash with other notes, only with real bookings.

The problem

The input is a stream of transactions that read and write rows of tables. Some of them touch a few rows, and some scan or update whole tables. The scheduler must give conflict serializable schedules, as two-phase locking does for single items.

Locks on rows only are correct but expensive: a scan of a table with nn rows takes nn locks. Locks on tables only are cheap but give little concurrency: two transactions that write different rows of a table wait for each other. MGL allows both sizes at the same time. The hard part is the conflict between a coarse lock and a fine lock on different nodes: S on a table and X on one of its rows. The model is one site with a lock table in main memory, and items form a tree of known shape, with the database at the root.

The algorithm

The five modes have these meanings:

  • IS: the transaction will take S locks on some nodes below.
  • IX: the transaction will take X (or S) locks on some nodes below.
  • S: the transaction reads the whole subtree.
  • SIX: S and IX together; the transaction reads the whole subtree and writes some nodes below, which it locks in X.
  • X: the transaction writes the whole subtree.

Two locks of different transactions on the same node are compatible as in this table:

held \ requested IS IX S SIX X
IS yes yes yes yes no
IX yes yes no no no
S yes no yes no no
SIX yes no no no no
X no no no no no

The table follows from the meanings. Two intentions never clash, since the real conflict, if any, shows up on a node lower down. A real access to the subtree (S, the S part of SIX, or X) clashes with a real access of the other side when one of the two is a write. It also clashes with an intention of the other side when one of the two is about writes: S clashes with IX, and X clashes with IS and IX. The modes are ordered IS < IX < SIX < X and IS < S < SIX, and the supremum of IX and S is SIX. A transaction that holds S on a table and now wants to write a row converts its table lock to SIX.

  1. LOCK(T, v, m) ▷ m in IS, IX, S, SIX, X
  2. 1if v is not the root and the lock of T on parent(v) is weaker than IS (for m in IS, S)
  3. or weaker than IX (for m in IX, SIX, X) then reject the request
  4. 2m' ← sup(the mode of T on v, m)
  5. 3if m' is not compatible with the lock of each other transaction on v then
  6. 4T waits, with an edge to each holder that blocks m'
  7. 5else grant m' to T on v
  8. LOCK-SUBTREE(T, v, m) ▷ how a transaction uses LOCK
  9. 6for each proper ancestor u of v, from the root down do
  10. LOCK(T, u, IX if m in IX, SIX, X, else IS)
  11. 7LOCK(T, v, m)
  12. UNLOCK(T, v)
  13. 8reject if T holds a lock on a child of v ▷ release from the leaves up
  14. 9at commit or abort (strict 2PL): release all locks of T, deepest nodes first

The usual operations become:

operation locks
read row rr of table tt IS on the database, IS on tt, S on rr
write row rr of table tt IX on the database, IX on tt, X on rr
scan table tt IS on the database, S on tt
scan tt and update some rows IX on the database, SIX on tt, X on each row it writes
rewrite all of tt IX on the database, X on tt

A transaction may hold a lock on a node that a stronger lock above already covers, for example S on a row under its own S on the table. It is redundant and harmless. Line L1 is a little more permissive than the rule of Gray, Lorie and Putzolu, which asks for exactly IS or IX on the parent: here any mode at least IS (or at least IX) is enough, so a transaction that holds S on a table may still lock a row in S.

Example

Take a database with tables A and B, each with rows 1 and 2.

step request result why
1 T1T_1: IX db, SIX A, X A1 granted T1T_1 reads table A and updates row A1
2 T2T_2: IS db, IS A, S A2 granted IS is compatible with SIX; T2T_2 and T1T_1 both read A2
3 T3T_3: IS db, S A waits for T1T_1 S is not compatible with SIX: T1T_1 writes a row of A
4 T4T_4: IX db, IX B, X B1 granted IX on db is compatible with IX and IS; table B is free
5 T2T_2: IX db, IX A waits for T1T_1 T2T_2 wants to write A2 too; IX is not compatible with SIX

After step 5 the wait-for graph has the edges T3→T1T_3 \to T_1 and T2→T1T_2 \to T_1. When T1T_1 commits and releases X on A1, then SIX on A, then IX on db, T2T_2 gets IX on A at once, and T3T_3 still waits: S on A is not compatible with the IX of T2T_2.

At step 3, the conflict between the scan of T3T_3 and the row write of T1T_1 is found on node A, with one test, although the two transactions never name the same row. Without the intention locks, T3T_3 would hold S on A and T1T_1 X on A1, and both would be granted.

A deadlock. Let T1T_1 rewrite table A and then table B, and T2T_2 rewrite B and then A. T1T_1 holds X on A and waits for X on B, which T2T_2 holds while it waits for A. MGL does not prevent deadlocks, and the tests find them with the wait-for graph.

Correctness

The proof is on the proof page. Say that TT implicitly holds S on a leaf ℓ\ell when it holds S, SIX or X on ℓ\ell or on an ancestor of ℓ\ell, and implicitly holds X on ℓ\ell when it holds X on ℓ\ell or on an ancestor.

  • The parent rule holds at all times. Line L1 checks it when a lock is granted, conversions only make the parent lock stronger, and line L8 keeps a parent lock until the locks below it are gone.
  • Implicit locks never conflict. Suppose TT implicitly holds X on ℓ\ell through node aa, and UU implicitly holds S or X on ℓ\ell through node bb. Both nodes are on the path from the root to ℓ\ell. If a=ba = b, the modes on that node conflict. If aa is above bb, then UU holds some lock on aa by the parent rule, and nothing is compatible with X. If bb is above aa, then TT holds at least IX on bb, and IX, SIX and X are not compatible with S, SIX or X. In each case the lock table would hold two conflicting locks on one node, which it never does.
  • Serializability. So the implicit locks on the leaves behave as S and X locks of two-phase locking: each read or write of a row runs under an implicit lock of the right mode, and two conflicting implicit locks are never held at the same time. With strict 2PL, every implicit lock is held to the end of the transaction, so by the two-phase locking theorem the committed projection is conflict serializable, and the schedule is strict.
Proof: Under the granular lock protocol, implicit locks on the leaves never conflict, so strict 2PL with intention locks is serializablefull

Setting. The items form a rooted tree. Reads and writes act on the leaves. Each transaction holds at most one mode on each node, from M={IS,IX,S,SIX,X}M = \{IS, IX, S, SIX, X\}, with the compatibility matrix of the page. The order on MM is IS < IX < SIX < X and IS < S < SIX, and m≥nm \ge n means that mm is nn or above it in this order. For a mode mm, let need(m)=IS\mathrm{need}(m) = IS if m∈{IS,S}m \in \{IS, S\} and need(m)=IX\mathrm{need}(m) = IX if m∈{IX,SIX,X}m \in \{IX, SIX, X\}.

The matrix has two facts that the proof uses. Both can be read off the table:

  • (F1) X is compatible with no mode.
  • (F2) Each mode m≥IXm \ge IX, that is IX, SIX or X, is compatible with none of S, SIX and X.

The tests also check that the matrix is symmetric, that it follows from the meanings of the modes, and that the supremum sup⁡(a,b)\sup(a, b) is the least mode above aa and bb, with compat(sup⁡(a,b),m)\mathrm{compat}(\sup(a, b), m) exactly when compat(a,m)\mathrm{compat}(a, m) and compat(b,m)\mathrm{compat}(b, m).

Definitions. TT implicitly holds X on a leaf ℓ\ell if TT holds X on some node on the path from the root to ℓ\ell (the leaf included). TT implicitly holds S on ℓ\ell if it holds S, SIX or X on some node of that path. A read of ℓ\ell by TT needs an implicit S lock, and a write needs an implicit X lock; the driver checks this before each action.

Lemma 1 (safety of the table). At every moment, if two different transactions hold modes m1m_1 and m2m_2 on the same node, then m1m_1 and m2m_2 are compatible.

Proof. Line L5 grants m′m' to TT on vv only when m′m' is compatible with the mode of each other holder of vv. Release steps only remove locks. So the claim holds after each step, by induction. A conversion replaces the mode of TT by m′=sup⁡(old,m)m' = \sup(\text{old}, m), and the test is made with m′m'. □\square

Lemma 2 (parent rule). At every moment, if TT holds mode mm on a node vv that is not the root, then TT holds a mode ≥need(m)\ge \mathrm{need}(m) on the parent of vv. Hence, by induction up the path, TT holds a mode ≥need(m)\ge \mathrm{need}(m) on every proper ancestor of vv.

Proof. Look at the steps that could break the claim.

  • A grant of m′m' on vv (line L5). Line L1 checked that the mode of TT on the parent is at least need(m)\mathrm{need}(m), where mm is the mode that TT asked for. If the grant is a conversion, m′=sup⁡(mold,m)m' = \sup(m_{old}, m), and need(m′)\mathrm{need}(m') is the larger of need(mold)\mathrm{need}(m_{old}) and need(m)\mathrm{need}(m), since need\mathrm{need} is monotone and {IS,IX}\{IS, IX\} is a chain. The parent mode was at least need(mold)\mathrm{need}(m_{old}) by the claim before the step, and at least need(m)\mathrm{need}(m) by line L1, so it is at least need(m′)\mathrm{need}(m').
  • A grant on the parent pp of vv. This replaces the mode of TT on pp by a supremum, which is at least the old mode, so the claim for vv still holds.
  • A release of the lock of TT on the parent pp. Line L8 refuses it while TT holds a lock on a child of pp, and release at the end goes deepest first, so by the time pp is released, TT holds nothing on its children. □\square

For the second sentence: need(m′)≥need(m)\mathrm{need}(m') \ge \mathrm{need}(m) when m′≥need(m)m' \ge \mathrm{need}(m). If need(m)=IS\mathrm{need}(m) = IS this holds because every mode needs at least IS; if need(m)=IX\mathrm{need}(m) = IX, then m′≥IXm' \ge IX, and need(m′)=IX\mathrm{need}(m') = IX exactly when m′≥IXm' \ge IX. Applying the first sentence to the parent, then to its parent, and so on, gives a mode ≥need(m)\ge \mathrm{need}(m) on each ancestor.

Theorem 1 (implicit locks never conflict). At every moment, if TT implicitly holds X on a leaf ℓ\ell, then no other transaction UU implicitly holds S or X on ℓ\ell.

Proof. Let TT hold X on the node aa and UU hold mU∈{S,SIX,X}m_U \in \{S, SIX, X\} on the node bb, where aa and bb are on the path from the root to ℓ\ell. The nodes of one root path are ordered by depth, so there are three cases.

  • a=ba = b. Then TT holds X and UU holds mUm_U on the same node, which contradicts Lemma 1 by (F1).
  • aa is a proper ancestor of bb. By Lemma 2, UU holds a mode ≥need(mU)≥IS\ge \mathrm{need}(m_U) \ge IS on aa, so it holds some mode on aa, while TT holds X on aa. This contradicts Lemma 1 by (F1).
  • bb is a proper ancestor of aa. By Lemma 2, TT holds a mode ≥need(X)=IX\ge \mathrm{need}(X) = IX on bb, while UU holds S, SIX or X on bb. This contradicts Lemma 1 by (F2). □\square

Theorem 2 (serializability and strictness). Let each transaction follow the protocol (lines L1 to L8) and release all its locks only at its commit or abort (line L9). Then every output schedule is strict, and its committed projection is conflict serializable, in commit order.

Proof. Let pi(ℓ)p_i(\ell) come before qj(ℓ)q_j(\ell), i≠ji \ne j, on the same leaf, with at least one write. When pi(ℓ)p_i(\ell) runs, TiT_i implicitly holds S or X on ℓ\ell, through a lock on some node of the root path; it holds this lock to its end, since locks are released only at line L9, and conversions only make modes stronger, so the implicit lock stays. In the same way, when qj(ℓ)q_j(\ell) runs, TjT_j implicitly holds S or X on ℓ\ell. One of the two is an implicit X, because one action is a write. By Theorem 1, the two implicit locks are not held at the same time. TiT_i holds its lock from before pi(ℓ)p_i(\ell) to its end, and TjT_j holds its lock at the moment of qj(ℓ)q_j(\ell), which is after pi(ℓ)p_i(\ell). So TiT_i ended before qj(ℓ)q_j(\ell).

Every action that follows a write of another transaction on the same leaf therefore follows the end of that transaction, so the schedule is strict. Also every pair of conflicting actions of committed transactions TiT_i and TjT_j, with the action of TiT_i first, has cic_i before the action of TjT_j, and so before cjc_j. So all conflicting pairs are in commit order, and the committed projection is conflict equivalent to the serial schedule in commit order. □\square

The argument does not need the lock point of the two-phase locking theorem, because locks are held to the end; with locks released earlier (but still two-phase and from the leaves up) the same lemmas give the general case through that theorem, applied to the implicit locks on the leaves.

Deadlock. The protocol does not prevent deadlocks. A waiting transaction has a request (v,m′)(v, m') that is not compatible with the lock of some other holder of vv, and the wait-for graph has an edge to each such holder. If every unfinished transaction waits, every node of the graph has an edge out of it, and every edge goes to an unfinished transaction, so the graph has a cycle. The driver of the tests then aborts the largest transaction id on the cycle and releases its locks.

The tests check Lemma 2 and Theorem 1 after every step of the driver, on all interleavings of four pairs of programs (a scan and a row write, a table update and a row read, two table rewrites in opposite orders, a read then write against a read) and on 250 random interleavings of three or six transactions on a database with three tables. On each output they check Theorem 2 with the helper dbsched: strictness, and conflict equivalence with the serial schedule in commit order, and for up to three transactions also against every serial order by brute force.

Complexity

  • Locks per access. A row access takes d+1d + 1 lock requests on a hierarchy of depth dd, one per node on the path. A scan of a subtree with nn rows takes d+1d + 1 requests instead of the nn row locks of flat locking. Requests for the upper nodes are usually conversions that do nothing, because the transaction already holds the intention lock.
  • Time per request. The test of line L3 compares the new mode with each other holder, O(k)O(k) for kk holders, or O(1)O(1) with a count of each mode in the lock entry. The lookup of the node is O(1)O(1) expected with a hash table.
  • Space. One lock entry per locked node. The upper nodes, the database and the tables, have many holders in IS and IX at a time, which is why their entries need counts per mode.

Properties

  • Output class. With strict 2PL, conflict serializable and strict.
  • Same schedules as row locking. The proof shows that MGL is equivalent to locking every covered leaf, so it gives the serializability of row locking with the lock count of table locking.
  • Deadlocks. MGL can deadlock, as in the example, and also in new ways: two transactions that hold S on the same table and both convert to SIX wait for each other. A deadlock detector or a timeout is needed.
  • Phantoms at table level. An insert of a row into table tt needs IX on tt, which is not compatible with S on tt. So a scan that locks the whole table in S sees no phantoms in that table. Row locks alone do not stop phantoms; key-range locking does that at row level.

Variants and improvements

  • Directed acyclic graphs. Gray, Lorie, Putzolu and Traiger (1976) extend the rules to a DAG of resources, for example a row that is reached both through its table and through an index. To lock a node in S, a transaction needs an intention lock on at least one parent; to lock it in X, on every parent.
  • Lock escalation. When a transaction holds too many row locks under one table, the lock manager converts its table lock from IS or IX to S or X and drops the row locks. This saves memory, and it can cause waits and deadlocks that the rows alone would not cause.
  • Update mode. Many systems add a U mode for a read that will probably be followed by a write; see the lock table page.
  • Key ranges in indexes. In a B+ tree index, the keys and the gaps between them are the leaves under the index node, and key-range locking locks them with modes of the same kind.
  • Degrees of consistency. The 1976 paper also defines degrees of consistency 0 to 3 by how long read and write locks are held. They are the root of the SQL isolation levels.

When to use it

Use MGL in any locking system with data at several sizes, which in practice means every relational system that locks: point updates lock rows, and scans, bulk loads and schema changes lock tables. It pays when one workload has both short transactions that touch a few rows and long ones that touch large parts of a table. When all access is by row, flat row locking with an IX on the table is the whole story. When the data is a tree that is always searched from the root, the tree locking protocol releases locks earlier.

Pitfalls

  • A missing intention lock. Every ancestor needs its intention lock, from the root down. A row lock without IX on its table is invisible to a transaction that locks the table.
  • A release from the top. If TT releases its IX on a table while it holds X on a row, another transaction can lock the table in S and read the row that TT writes. Release from the leaves up, or all at once at the end.
  • IS for a write. A transaction that read a row under IS on the table and now writes it must convert the table lock to IX before it locks the row in X. Line L1 rejects the request otherwise.
  • Conversion deadlocks. Two transactions that both scan a table in S and then want to update a row both ask for SIX, and each waits for the S of the other. Take SIX at the start if the update is likely.
  • Escalation surprises. An escalation in the middle of a transaction can make it wait for a table lock that it did not plan for.

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()
multiple_granularity_locking.py 248 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiple-granularity-locking/. The authors are listed in prov/ZVVV9H.jsonl.

"""Multiple granularity locking with the modes IS, IX, S, SIX and X.

The items form a tree, here a database with tables and rows. A lock on a node
covers the whole subtree below it. Before a transaction locks a node, it
must hold an intention lock on the parent: IS or stronger for IS and S, and
IX or stronger for IX, SIX and X. It releases locks from the leaves up. With
strict 2PL on top, all locks are released at the end of the transaction.

The lock manager here grants a request when it is compatible with the locks
of the other transactions on the node; otherwise the request waits and is
tried again later. The page lock-table adds a FIFO queue.
"""

IS, IX, S, SIX, X = "IS", "IX", "S", "SIX", "X"
MODES = (IS, IX, S, SIX, X)

_ROWS = {
    IS: {IS: True, IX: True, S: True, SIX: True, X: False},
    IX: {IS: True, IX: True, S: False, SIX: False, X: False},
    S: {IS: True, IX: False, S: True, SIX: False, X: False},
    SIX: {IS: True, IX: False, S: False, SIX: False, X: False},
    X: {IS: False, IX: False, S: False, SIX: False, X: False},
}
COMPAT = _ROWS  # COMPAT[held][requested]

# The supremum: IS < IX, IS < S, IX < SIX, S < SIX, SIX < X.
_UP = {IS: {IS, IX, S, SIX, X}, IX: {IX, SIX, X}, S: {S, SIX, X}, SIX: {SIX, X}, X: {X}}


def sup(a, b):
    if a is None:
        return b
    if b is None:
        return a
    common = _UP[a] & _UP[b]
    return next(m for m in MODES if m in common and _UP[m] >= common)


def at_least(held, needed):
    return held is not None and held in _UP[needed]


# The parent of a node must be held in at least this mode.
PARENT_NEEDS = {IS: IS, S: IS, IX: IX, SIX: IX, X: IX}


class Hierarchy:
    """A tree given by a map from each node to its parent (None for the root)."""

    def __init__(self, parent):
        self.parent = dict(parent)
        self.children = {}
        for v, p in self.parent.items():
            if p is not None:
                self.children.setdefault(p, []).append(v)

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

    def depth(self, v):
        return len(self.path(v)) - 1

    def leaves(self, v):
        kids = self.children.get(v)
        if not kids:
            return [v]
        return [leaf for k in kids for leaf in self.leaves(k)]


class MGLLockManager:
    def __init__(self, tree):
        self.tree = tree
        self.locks = {}  # node -> {txn: mode}
        self.waiting = {}  # txn -> (node, mode) it waits for

    def mode(self, txn, node):
        return self.locks.get(node, {}).get(txn)

    def lock(self, txn, node, mode):
        """Ask for mode on node. Return True if txn holds it now, False if it waits.
        Raise ValueError if txn breaks the parent rule."""
        p = self.tree.parent[node]
        if p is not None and not at_least(self.mode(txn, p), PARENT_NEEDS[mode]):  # @line L1
            raise ValueError("%r needs %s on %r before %s on %r" % (txn, PARENT_NEEDS[mode], p, mode, node))
        old = self.mode(txn, node)
        new = sup(old, mode)  # @line L2
        if new == old:
            return True
        for u, m in self.locks.get(node, {}).items():  # @line L3
            if u != txn and not COMPAT[m][new]:
                self.waiting[txn] = (node, new)  # @line L4
                return False
        self.locks.setdefault(node, {})[txn] = new  # @line L5
        self.waiting.pop(txn, None)
        return True

    def unlock(self, txn, node):
        """Release the lock of txn on node. Raise ValueError if txn still
        holds a lock on a child of node (locks go from the leaves up)."""
        for c in self.tree.children.get(node, ()):
            if self.mode(txn, c) is not None:  # @line L8
                raise ValueError("%r still holds a lock below %r" % (txn, node))
        del self.locks[node][txn]
        if not self.locks[node]:
            del self.locks[node]

    def release_all(self, txn):
        """Drop the wait of txn and release all its locks, deepest first."""
        self.waiting.pop(txn, None)
        mine = [v for v, h in self.locks.items() if txn in h]
        for v in sorted(mine, key=lambda v: (-self.tree.depth(v), repr(v))):  # @line L9
            self.unlock(txn, v)

    def covers(self, txn, leaf, kind):
        """True if the locks of txn on leaf or an ancestor allow kind (r or w) on leaf."""
        for v in self.tree.path(leaf):
            m = self.mode(txn, v)
            if m == X or (kind == "r" and m in (S, SIX)):
                return True
        return False

    def waits_for(self):
        """Edges (T, U): T waits for a mode that the lock of U on the node blocks."""
        edges = set()
        for txn, (node, mode) in self.waiting.items():
            for u, m in self.locks.get(node, {}).items():
                if u != txn and not COMPAT[m][mode]:
                    edges.add((txn, u))
        return edges


def plan(tree, txn, ops):
    """Turn operations into steps of txn: ("lock", node, mode), (kind, txn, leaf)
    for kind r or w, and a final ("c", txn, None). The operations are
    ("read", row), ("write", row), ("scan", table), ("update", table, rows)
    that reads the table and writes the given rows, and ("rewrite", table)
    that writes every row."""
    steps = []

    def path_locks(node, mode):  # @line L6
        intent = IX if mode in (IX, SIX, X) else IS
        for v in tree.path(node)[:-1]:
            steps.append(("lock", v, intent))
        steps.append(("lock", node, mode))  # @line L7

    for op in ops:
        name, node = op[0], op[1]
        if name == "read":
            path_locks(node, S)
            steps.append(("r", txn, node))
        elif name == "write":
            path_locks(node, X)
            steps.append(("w", txn, node))
        elif name == "scan":
            path_locks(node, S)
            steps.extend(("r", txn, leaf) for leaf in tree.leaves(node))
        elif name == "update":
            path_locks(node, SIX)
            steps.extend(("r", txn, leaf) for leaf in tree.leaves(node))
            for row in op[2]:
                steps.append(("lock", row, X))
                steps.append(("w", txn, row))
        elif name == "rewrite":
            path_locks(node, X)
            steps.extend(("w", txn, leaf) for leaf in tree.leaves(node))
        else:
            raise ValueError("unknown operation %r" % (name,))
    steps.append(("c", txn, None))
    return steps


def find_cycle(edges):
    """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)
    state = {}
    for start in sorted(succ, key=repr):
        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 run(tree, plans, arrival, check=None):
    """Run the step lists of plans (txn -> steps) under strict 2PL with
    multiple granularity locks. arrival lists the transaction of each step 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(manager) runs after each step. Return the
    schedule of reads, writes, commits and aborts on the leaves."""
    mgr = MGLLockManager(tree)
    pos = {t: 0 for t in plans}
    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(mgr.waits_for())
            if cycle is None:
                raise RuntimeError("every transaction waits, but there is no cycle")
            victim = max(cycle)
            out.append(("a", victim, None))
            mgr.release_all(victim)
            pending = [t for t in pending if t != victim]
            blocked.clear()
        else:
            t = pending[k]
            step = plans[t][pos[t]]
            if step[0] == "lock":
                if not mgr.lock(t, step[1], step[2]):
                    blocked.add(t)
                    if check:
                        check(mgr)
                    continue
            elif step[0] in "rw":
                if not mgr.covers(t, step[2], step[0]):
                    raise RuntimeError("%r runs %r without a lock" % (t, step))
                out.append(step)
            else:
                out.append(step)
                mgr.release_all(t)
                blocked.clear()
            pos[t] += 1
            pending.pop(k)
        if check:
            check(mgr)
    return tuple(out)
test_multiple_granularity_locking.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiple-granularity-locking/. The authors are listed in prov/ZVVV9H.jsonl.

import itertools
import random

import pytest

import dbsched
import multiple_granularity_locking as mgl
from multiple_granularity_locking import IS, IX, MODES, S, SIX, X


def make_tree(rows_per_table=2, tables="AB"):
    parent = {"db": None}
    for t in tables:
        parent[t] = "db"
        for r in range(1, rows_per_table + 1):
            parent["%s%d" % (t, r)] = t
    return mgl.Hierarchy(parent)


# What each mode says: (access to the whole subtree, access that it announces below).
MEANING = {IS: (None, "r"), IX: (None, "w"), S: ("r", None), SIX: ("r", "w"), X: ("w", None)}


def _clash(a, b):
    return a is not None and b is not None and (a == "w" or b == "w")


def test_matrix_follows_from_the_meaning_of_the_modes() -> None:
    for a, b in itertools.product(MODES, repeat=2):
        (ea, ia), (eb, ib) = MEANING[a], MEANING[b]
        # Two modes clash if their subtree accesses clash, or if a subtree access
        # of one clashes with an access that the other announces below.
        clash = _clash(ea, eb) or _clash(ea, ib) or _clash(ia, eb)
        assert mgl.COMPAT[a][b] == (not clash), (a, b)
        assert mgl.COMPAT[a][b] == mgl.COMPAT[b][a]


def test_sup_is_the_least_upper_bound() -> None:
    # m is at least as strong as n when every mode compatible with m is compatible with n.
    def ok_with(m):
        return {k for k in MODES if mgl.COMPAT[m][k]}

    def geq(m, n):
        return ok_with(m) <= ok_with(n)

    for a, b in itertools.product(MODES, repeat=2):
        u = mgl.sup(a, b)
        assert geq(u, a) and geq(u, b)
        assert all(geq(m, u) for m in MODES if geq(m, a) and geq(m, b))
        for m in MODES:  # one sup test replaces two compatibility tests
            assert mgl.COMPAT[u][m] == (mgl.COMPAT[a][m] and mgl.COMPAT[b][m])
    assert mgl.sup(IX, S) == SIX


def test_rules_are_enforced() -> None:
    tree = make_tree()
    mgr = mgl.MGLLockManager(tree)
    with pytest.raises(ValueError):
        mgr.lock(1, "A1", S)  # no intention lock on A
    assert mgr.lock(1, "db", IS) and mgr.lock(1, "A", IS)
    with pytest.raises(ValueError):
        mgr.lock(1, "A1", X)  # X needs IX on the parent
    assert mgr.lock(1, "A1", S)
    with pytest.raises(ValueError):
        mgr.unlock(1, "A")  # the child A1 is still locked
    mgr.release_all(1)
    assert mgr.locks == {}


def test_coarse_and_fine_locks() -> None:
    tree = make_tree()
    mgr = mgl.MGLLockManager(tree)
    # T1 updates table A: IX on db, SIX on A, then X on row A1.
    assert mgr.lock(1, "db", IX) and mgr.lock(1, "A", SIX) and mgr.lock(1, "A1", X)
    # T2 reads row A2: IS on A is compatible with SIX.
    assert mgr.lock(2, "db", IS) and mgr.lock(2, "A", IS) and mgr.lock(2, "A2", S)
    # T3 scans table A: S on A is not compatible with SIX.
    assert mgr.lock(3, "db", IS) and not mgr.lock(3, "A", S)
    # T4 writes row B1: no conflict on table B.
    assert mgr.lock(4, "db", IX) and mgr.lock(4, "B", IX) and mgr.lock(4, "B1", X)
    assert mgr.waits_for() == {(3, 1)}
    # T2 now wants to write A2: IX on A conflicts with SIX.
    assert mgr.lock(2, "db", IX) and not mgr.lock(2, "A", IX)
    assert mgr.waits_for() == {(3, 1), (2, 1)}
    mgr.release_all(1)
    assert mgr.lock(2, "A", IX) and not mgr.lock(3, "A", S)
    assert mgr.covers(4, "B1", "w") and not mgr.covers(4, "B2", "r")


def check_state(mgr):
    tree = mgr.tree
    holders = {t for h in mgr.locks.values() for t in h}
    # The parent rule holds for every lock at every moment.
    for node, h in mgr.locks.items():
        p = tree.parent[node]
        for t, m in h.items():
            assert p is None or mgl.at_least(mgr.mode(t, p), mgl.PARENT_NEEDS[m])
    # The oracle: the implicit locks on the leaves never conflict.
    for leaf in tree.leaves("db"):
        for t, u in itertools.permutations(sorted(holders), 2):
            if mgr.covers(t, leaf, "w"):
                assert not mgr.covers(u, leaf, "r"), (leaf, t, u)


def _plans(tree, programs):
    return {t: mgl.plan(tree, t, ops) for t, ops in programs.items()}


def _check_output(out, plans, brute_force):
    assert dbsched.is_strict(out)
    cp = dbsched.committed_projection(out)
    commit_order = [a[1] for a in out if a[0] == "c"]
    assert dbsched.conflict_equivalent(cp, dbsched.serial_schedule(cp, commit_order))
    if brute_force:
        assert tuple(commit_order) in dbsched.conflict_serializable_orders(out)
    ended = {a[1] for a in out if a[0] in "ca"}
    assert ended == set(plans)


PAIRS = [
    (2, {1: [("scan", "A")], 2: [("write", "A1")]}),
    (2, {1: [("update", "A", ["A1"])], 2: [("read", "A2")]}),
    (1, {1: [("rewrite", "A"), ("rewrite", "B")], 2: [("rewrite", "B"), ("rewrite", "A")]}),
    (1, {1: [("read", "A1"), ("write", "A1")], 2: [("read", "A1")]}),
]


@pytest.mark.parametrize("rows,programs", PAIRS)
def test_all_interleavings_of_two(rows, programs) -> None:
    tree = make_tree(rows)
    plans = _plans(tree, programs)
    seqs = [[t] * len(plans[t]) for t in sorted(plans)]
    aborts = 0
    for arrival in dbsched.interleavings([[("r", t, "x")] * len(s) for t, s in zip(sorted(plans), seqs)]):
        out = mgl.run(tree, plans, [a[1] for a in arrival], check_state)
        _check_output(out, plans, brute_force=True)
        aborts += any(a[0] == "a" for a in out)
    if programs[1][0][0] == "rewrite":
        assert aborts > 0  # the opposite order of tables gives deadlocks


def test_random_interleavings_of_up_to_six() -> None:
    rng = random.Random(3)
    tree = make_tree(2, "ABC")
    rows = [v for v in tree.parent if len(v) == 2]
    tables = ["A", "B", "C"]
    deadlocks = 0
    for n in [3] * 150 + [6] * 100:
        programs = {}
        for t in range(1, n + 1):
            ops = []
            for _ in range(rng.randint(1, 2)):
                kind = rng.choice(["read", "read", "write", "write", "scan", "update", "rewrite"])
                if kind in ("read", "write"):
                    ops.append((kind, rng.choice(rows)))
                elif kind == "update":
                    tab = rng.choice(tables)
                    ops.append((kind, tab, [tab + rng.choice("12")]))
                else:
                    ops.append((kind, rng.choice(tables)))
            programs[t] = ops
        plans = _plans(tree, programs)
        arrival = [t for t in plans for _ in plans[t]]
        rng.shuffle(arrival)
        out = mgl.run(tree, plans, arrival, check_state)
        _check_output(out, plans, brute_force=(n <= 3))
        deadlocks += any(a[0] == "a" for a in out)
    assert deadlocks > 0

History

Gray, Lorie and Putzolu presented granular locks with the modes IS, IX, S, SIX and X at the first VLDB conference in 1975, from the System R project at IBM San Jose. The longer paper by Gray, Lorie, Putzolu and Traiger (1976) gave the rules for DAGs and argued that the protocol is equivalent to locking the leaves, and it also defined the degrees of consistency. The method has been part of the lock manager of almost every relational system since. Bernstein, Hadzilacos and Goodman (1987) and Gray and Reuter (1993) give the textbook treatment.

References

  1. J. N. Gray, R. A. Lorie and G. R. Putzolu, Granularity of locks in a large shared data base, Proceedings of the First International Conference on Very Large Data Bases (VLDB), 1975, the lock modes IS, IX, S, SIX and X, the compatibility matrix, and the rules for locking a hierarchy of resources from the root down
  2. J. N. Gray, R. A. Lorie, G. R. Putzolu and I. L. Traiger, Granularity of locks and degrees of consistency in a shared data base, in G. M. Nijssen (ed.), Modelling in Data Base Management Systems, North-Holland, 1976, the granular lock protocol for hierarchies and for directed acyclic graphs of resources, and its equivalence to locking the leaves
  3. Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 3 (multigranularity locking and the intention modes)
  4. Jim Gray and Andreas Reuter, Transaction Processing, Concepts and Techniques, Morgan Kaufmann, 1993, Chapter 7 (lock granularity and intention lock modes) and Chapter 8 (their implementation in the lock manager)

About this page

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

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