Algorithm Search⌘K

Algorithmcore

Primary copy locking

Also called primary site locking, primary copy two-phase locking.

Distributed two-phase locking in which each item has one primary copy whose site grants all locks on the item.

Space
O(r + w n) extra
Counts
messages 3r + w(2n + 1) worst
Where
n = the largest number of copies of an item; r = the number of reads of a transaction; w = the number of writes of a transaction
Properties
deterministiciterative
Origin
Michael Stonebraker, 1979

Primary copy locking is a form of distributed two-phase locking for replicated data. Each item has several copies, and one of them is the primary copy. Only the site of the primary copy keeps locks for the item. A transaction locks the item at that site before it reads any copy or writes the item. At commit it sends its writes to every copy, and the primary releases the locks only when all copies have the new value. This gives one-copy serializability with one lock request per item, not one per copy as in read-one write-all. The cost is an extra message for a read of a copy that is not the primary, and the primary site is a single point of failure for its items.

In plain words

A library has several copies of a book in different rooms. Only the front desk keeps the list of who has borrowed the book, and you ask the front desk before you open any copy. To change the book, you get permission at the desk, give the new page to every room, and wait until each room says that it has the page. Only then does the desk let the next person in.

Because every reader and writer of the book passes through the one desk, they never see the book in a half-changed state, even when they read different copies. If the desk is closed, nobody can use the book.

The problem

A database holds items x,y,…x, y, \dots, and each item has copies at a fixed set of sites. The system must run transactions so that the history is one-copy serializable. Transactions run at a home site and send messages to the other sites. The model is the asynchronous model: messages take any time and are not lost, and each channel between two sites is first in, first out. Sites can fail by stopping (crash failure) and stay down, and a message to a failed site comes back as "no response". The page assumes that at least one copy of each item stays up.

For each item xx, a fixed copy is the primary copy, at the site P(x)P(x). The site P(x)P(x) runs a lock table for xx with S (shared) and X (exclusive) locks. Two locks of different transactions conflict unless both are S.

The algorithm

  1. PRIMARY-COPY-TRANSACTION(T)
  2. 1for each operation of T, in order do
  3. 2if the operation is a read of x then
  4. 3ask the site P(x) for an S lock on x
  5. 4read one copy of x: the copy at the home site of T if there is one, else the primary copy
  6. 5else ▷ a write of x
  7. 6ask the site P(x) for an X lock on x; compute the new value of x
  8. 7commit T ▷ T holds all its locks here
  9. 8send the new value of each written x to every copy of x except the primary copy
  10. 9wait until each of these copies has acknowledged or is found down
  11. 10tell each primary site to install the new values on its primary copies and release the locks of T

A read of the primary copy is one message: the lock request asks the primary to read the copy and send the value with the grant. A read of a local copy needs the lock at the primary and then a local read, which sends no message. If the local copy is down, the transaction reads the primary copy instead, still under its S lock. A transaction that reads and then writes an item upgrades its S lock to an X lock.

If a lock request gets "no response", the primary of the item is down and the transaction aborts. A transaction that holds or waits for a lock at a primary that fails, and has not reached line L7, also aborts. An abort sends a release to every primary site that the transaction asked. A transaction that has passed line L7 goes on to the end. The atomic commitment of a transaction whose writes span several primary sites, for example by two-phase commit, is outside the pseudocode: line L7 is one decision.

Deadlocks. The primaries are separate lock managers, so a cycle of waits can span several sites. The code uses a central detector that reads the lock tables of all up sites, builds the wait-for graph and aborts the transaction with the largest id in each cycle. A distributed detector such as Chandy-Misra-Haas can do the same job.

Example

The items are xx with copies at AA (primary), BB and CC, yy with copies at BB (primary) and CC, and zz with copies at AA (primary) and CC. The counts below are from the code, and they count only messages between different sites.

A write. T1=w1[x]T_1 = w_1[x] runs at site DD, which holds no copy. It sends a lock request to AA and gets the grant (2 messages). At commit it sends the new value 100 to xBx_B and xCx_C and gets two acknowledgments (4 messages). Then it sends one release to AA, which installs 100 on xAx_A and drops the lock (1 message). That is 7 messages, and all three copies hold 100. Read-one write-all would lock all three copies: 6 messages before the commit protocol.

Reads. T1=r1[x]T_1 = r_1[x] at site BB locks xx at AA and reads the local copy xBx_B: 2 messages for the lock and 1 for the release. The same read at site AA costs nothing. A read of yy at site AA, which holds no copy of yy, sends the lock request to BB, and the grant carries the value of yBy_B: again 2 messages and 1 release. Under read-one write-all, the read at BB would cost no message at all, which is the extra cost of primary copy reads that Bernstein and Goodman point out.

Why the primary waits for the acknowledgments. In the code, the flag early_release makes the primary release the X lock when the new values are sent, not when they are acknowledged. With 3 random transactions per run, 1 of 200 runs gives a history that is not 1SR. In that run, T3=w3[x]T_3 = w_3[x] runs at DD and T2=r2[x] w2[x]T_2 = r_2[x]\, w_2[x] runs at CC:

c3  w3[xA]  r2[xC]  w3[xB]  w3[xC]  c2  w2[xA]  w2[xB]  w2[xC]c_3\; w_3[x_A]\; r_2[x_C]\; w_3[x_B]\; w_3[x_C]\; c_2\; w_2[x_A]\; w_2[x_B]\; w_2[x_C]

T3T_3 commits and the primary AA installs its value and releases the lock at once. T2T_2 gets the lock at AA and reads its local copy xCx_C before the value of T3T_3 arrives there. So T2T_2 reads the initial value of xx, and its write then overwrites the write of T3T_3: a lost update. In the order T3 T2T_3\, T_2, T2T_2 would read from T3T_3; in the order T2 T3T_2\, T_3, the last write of xx would be by T3T_3, but every copy ends with the value of T2T_2. With the acknowledgments, all 200 runs are 1SR in commit order.

Correctness

The proofs are on the proof page.

  • One-copy serializability (theorem). Every history is 1SR, in the order of the commits (line L7). The X lock of a writer at the primary covers the installs at all copies (lines L8 to L10), and the S lock of a reader covers its read. So a reader sees the value of the last writer that committed before it, at any copy it reads, and conflicting transactions are ordered at the primary in the order of their commits.
  • Failures. A failed primary grants no more locks, so its items stop, but the history stays 1SR. The tests inject one site failure at a random step in 200 runs, and all histories are 1SR in commit order. A copy at a failed site misses writes, and the code never reads it again, because the site never comes back.
Proof: Primary copy locking gives one-copy serializable histories in commit orderfull

We use the line numbers of the pseudocode on the page. The model is the model of the page and of the code.

The model. Each item xx has copies at a fixed set of sites, and one of them is the primary copy, at the site P(x)P(x). Only P(x)P(x) keeps locks for xx, with S and X modes, and two locks of different transactions on xx conflict unless both are S. Channels between two sites are first in, first out, and messages are not lost. A site can fail by stopping. It then stays down, it loses its lock table, and a message to it comes back as "no response". A transaction that holds or waits for a lock at a failed site and has not reached line L7 aborts. For each item, at least one site with a copy stays up. A transaction reads an item at most once and does not read an item after it writes it. The history over copies records rT[xA]r_T[x_A] when site AA returns a value and wT[xA]w_T[x_A] when site AA installs a value. The 1SR definition is that of Bernstein, Hadzilacos and Goodman (1987), Section 8.3, as on the page one-copy serializability.

Let γT\gamma_T be the moment of line L7 for a committed transaction TT, and let C\mathcal{C} be the set of committed transactions, with the initial transaction T0T_0 first.

Lemma 1 (lock intervals). If T∈CT \in \mathcal{C} gets a lock on xx at time gg, and P(x)P(x) releases it at time ρ\rho (or P(x)P(x) fails at time ρ\rho), then g<γT<ρg < \gamma_T < \rho. For two committed transactions with conflicting locks on xx, the intervals [g,ρ][g, \rho] are disjoint, and their order is the order of the γ\gamma values.

Proof. Line L7 runs only after the last operation of TT got its lock, and line L10 sends the release after line L7, so g<γT<ρg < \gamma_T < \rho. Conflicting locks are never held together at P(x)P(x), so two such intervals cannot overlap while P(x)P(x) is up. After P(x)P(x) fails, no lock on xx is granted again, so no interval starts after a failure. Each γ\gamma is inside its own interval, so the intervals and the γ\gamma values are in the same order. □\square

Lemma 2 (installs inside the X interval). Let U∈CU \in \mathcal{C} write xx, with X interval [gU,ρU][g_U, \rho_U], and let ρU\rho_U be a release, not a failure of P(x)P(x). Then every copy of xx at a site that is up when the install arrives installs the value of UU at a time in (γU,ρU](\gamma_U, \rho_U], and the primary copy installs it at ρU\rho_U. If ρU\rho_U is a failure of P(x)P(x), the copies at up sites still install the value of UU after γU\gamma_U, and no transaction gets a lock on xx after ρU\rho_U.

Proof. Line L8 sends the installs after γU\gamma_U. Line L9 waits for an acknowledgment or "no response" from each copy that is not the primary, so each of these installs happens before line L10 sends the release, and so before ρU\rho_U. The primary copy installs the value in the same step in which P(x)P(x) handles the release (line L10). If P(x)P(x) fails first, UU goes on with lines L8 to L10, because it has passed line L7, and P(x)P(x) grants no lock after it fails. □\square

So if some transaction gets a lock on xx after the X interval of UU, that interval ended with a release, and all installs of UU at up sites happened before it.

Lemma 3 (one order of installs). For each copy xAx_A, the committed writes of xx are installed on xAx_A in the order of their γ\gamma values.

Proof. Take two committed writers UU and VV of xx with γU<γV\gamma_U < \gamma_V. By Lemma 1, the X interval of UU ends before VV gets its X lock, so by the note after Lemma 2 it ended with a release, and UU installs on xAx_A before ρU\rho_U. VV installs after γV>gV>ρU\gamma_V > g_V > \rho_U. □\square

Theorem 1 (one-copy serializability). Every history of the protocol is one-copy serializable, with the serial order of the γ\gamma values.

Proof. Let T∈CT \in \mathcal{C} read xx, with the S lock interval [gT,ρT][g_T, \rho_T], at the copy xAx_A at time tt with gT<t<γTg_T < t < \gamma_T. Line L4 reads the local copy, or the primary copy if there is no local copy or its site is down; a read at a down site returns nothing, so AA is up at tt. Let UU be the writer of xx with the largest γU<γT\gamma_U < \gamma_T, or T0T_0.

Every committed writer VV of xx has an X interval that is disjoint from [gT,ρT][g_T, \rho_T] by Lemma 1. If γV<γT\gamma_V < \gamma_T, the interval of VV ends before gTg_T, so by the note after Lemma 2 its install on xAx_A happens before gT<tg_T < t, because AA is up at tt and so was up before. If γV>γT\gamma_V > \gamma_T, the interval of VV starts after ρT>t\rho_T > t, so its install on xAx_A happens after tt. So the writes installed on xAx_A before tt are exactly those of the writers with γV<γT\gamma_V < \gamma_T, and by Lemma 3 the last of them is the write of UU. So TT reads xx from UU in the history. In the serial order of the γ\gamma values, TT also reads xx from UU, the last writer of xx before TT; TT does not read its own write. Each read of TT in one history is one read of TT in the other, so the reads-from relations are equal.

For the final writes, let WW be the writer of xx with the largest γ\gamma. At least one site with a copy xAx_A of xx stays up, so by Lemma 2 xAx_A installs the value of WW, and by Lemma 3 no committed write is installed on xAx_A after it. So wW[xA]w_W[x_A] is the final write of xAx_A. ■\blacksquare

Where each part is used. The proof uses two facts at the primary: the X lock covers the installs at all copies (Lemma 2), and the S lock covers the read (Theorem 1). If the primary releases the X lock when the installs are sent instead of when they are acknowledged, Lemma 2 fails. The test file finds such a history: T3T_3 writes xx, the primary AA installs and releases, T2T_2 locks xx at AA and reads its local copy xCx_C before the install of T3T_3 arrives there. T2T_2 reads xx from T0T_0 although T3T_3 committed before it, and the history has no one-copy serial order.

Theorem 2 (messages). Count only messages between different sites. Let the home site of TT hold no copy and let the items of TT have different primary sites. A read costs 2 messages, a write of an item with nn copies costs 2+2(n−1)=2n2 + 2(n - 1) = 2n messages, and the release costs one message per primary site. So TT with rr reads and ww writes on items with at most nn copies sends at most 3r+w(2n+1)3r + w(2n + 1) messages.

Proof. A read sends a lock request to the primary, and the grant carries the value of the primary copy (lines L3 and L4): 2 messages. A write sends a lock request and gets a grant (line L6), and at commit one install and one acknowledgment per copy other than the primary (lines L8 and L9). Line L10 sends one release to each primary site. A read of a local copy that is not the primary costs the same 2 messages for the lock and none for the read. ■\blacksquare

Complexity

  • Messages. A read costs 2 messages to the primary, or none if the home site is the primary. A write of an item with nn copies costs 2 for the lock and 2(n−1)2(n - 1) for the installs and acknowledgments. The release costs one message per primary site. A transaction with rr reads and ww writes, at a home site with no copies and with all its items at different primaries, sends at most 3r+w(2n+1)3r + w(2n + 1) messages.
  • Compared with read-one write-all. For a write, ROWA sends 2n2n lock messages and then the commit protocol sends values to the nn copies. Primary copy sends 2 lock messages, and the values go to the copies at commit. For a read of a local copy that is not the primary, ROWA sends nothing and primary copy sends 2 messages. So primary copy wins when writes are frequent, and ROWA wins for local reads.
  • Space. Each primary site keeps the lock table of its items only. A transaction keeps its reads and the new values of its writes, O(r+w)O(r + w), and O(wn)O(w n) entries for the acknowledgments it waits for.

Properties

  • 1SR, in commit order. Shown above.
  • One lock per item. No copy other than the primary has a lock table for the item.
  • A single point of failure per item. When the primary site is down, the item cannot be read or written, even when other copies are up. The method alone has no way to move the primary.
  • Load on the primary. All lock traffic for an item goes to one site. Placing the primaries of different items at different sites spreads the load.
  • Deadlocks. Two-phase locking at the primaries can deadlock across sites, so the system needs detection or prevention.

Variants and improvements

  • Centralized 2PL. One site keeps the locks of all items. Bernstein and Goodman (1981, Section 3.4) describe it and note that Alsberg and Day call this the primary site method. It is primary copy locking with the same primary site for every item, so the alias "primary site locking" also names this special case.
  • Primary copy for write-write conflicts only. The survey (Section 5.1) lists combinations in which primary copy 2PL orders writes against writes, while another method, for example basic 2PL, orders reads against writes. With basic 2PL for reads, a reader locks only the copy it reads.
  • A primary that moves. If the primary fails, the other copies can elect a new primary. This needs a protocol that agrees on the new primary and on the last committed writes, such as the view change of primary-backup replication or a consensus protocol like Raft or Paxos. Each group of copies of a shard then acts as one replicated lock manager, as in many sharded databases.
  • Lazy primary copy. The primary commits a transaction alone and sends the writes to the other copies after the commit. This is the lazy master scheme of eager and lazy replication. Reads of the other copies can then be stale, so the history is no longer 1SR unless reads also go to the primary.

When to use it

Use primary copy locking when an item has several copies, writes are not rare and the sites rarely fail, and you want one lock manager per item instead of one per copy. Put the primary of each item at the site that writes it most. Do not use it when local reads must be free of messages, or when the items must stay available while their primary is down; then use a quorum method or a primary that moves by consensus.

Pitfalls

  • Releasing before the copies have the value. If the primary releases the X lock when the writes are only sent, a reader can lock the item and read a copy that has not got the new value. The example shows the lost update that follows.
  • Reading without the lock. A read of a local copy without the S lock at the primary is cheap, but it can see a value in the middle of a write, or one that is about to change. This is what lazy replication does, and it is not 1SR.
  • Messages that pass each other. An abort sends a release after a lock request to the same site. If channels are not first in, first out, the release can arrive first and leave a lock that is never released. The code delivers in order on each channel.
  • A primary that is only slow. If a slow primary is taken for down and a new primary is chosen, the two can grant conflicting locks. Moving the primary needs agreement, not a timeout alone.

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.

primary_copy_locking.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/primary-copy-locking/. The authors are listed in prov/SBHSMT.jsonl.
"""Primary copy two-phase locking on replicated data.

A small simulation in one thread. Each item has copies at some sites, and
one copy is the primary copy. Only the site of the primary copy keeps locks
for the item. A transaction runs at a home site. It gets an S lock at the
primary before it reads any copy, and an X lock at the primary before it
writes. At commit it sends its writes to every copy and waits for the
acknowledgments. Only then does it tell the primary sites to install the
writes on the primary copies and release its locks (strict 2PL).

The network delivers messages in a random order chosen by a seeded
random.Random, but first in, first out on each channel (one pair of sites).
Only messages between different sites are counted. A site can fail and stay
down: a message to it comes back as "no response". The primary of an item
whose site is down cannot be locked, so the item is unavailable.

With early_release=True, the primary releases the locks when the writes are
sent, not after they are acknowledged. The tests show that this breaks
one-copy serializability.

The history uses copy names "x@A". A read is recorded when a copy returns
its value, a write when a copy installs it. Only committed transactions
install writes, so every write in the history is committed.
"""

SHARED, EXCLUSIVE = "S", "X"


class Site:
    def __init__(self, sid, items, primary_of):
        self.sid = sid
        self.value = {x: 0 for x in items}
        self.up = True
        self.primary_of = sorted(primary_of)
        self.holders = {x: {} for x in self.primary_of}   # item -> {txn: mode}
        self.queue = {x: [] for x in self.primary_of}     # item -> [(txn, mode, read_here)]

    def compatible(self, x, txn, mode):
        for h, m in self.holders[x].items():
            if h != txn and (mode == EXCLUSIVE or m == EXCLUSIVE):
                return False
        return True


class Txn:
    def __init__(self, tid, ops, home):
        self.tid = tid
        self.ops = list(ops)
        self.home = home
        self.i = 0
        self.status = "active"       # active, committing, committed, aborted
        self.reads = {}
        self.writes = {}
        self.contacted = set()       # primary sites that may hold a lock or a request
        self.pending = set()


class PrimaryCopyDB:
    def __init__(self, placement, primary=None, early_release=False):
        self.placement = {x: sorted(s) for x, s in placement.items()}
        self.primary = dict(primary or {x: s[0] for x, s in self.placement.items()})
        self.early_release = early_release
        names = sorted({s for ss in placement.values() for s in ss})
        self.sites = {s: Site(s, [x for x in placement if s in placement[x]],
                              [x for x in placement if self.primary[x] == s])
                      for s in names}
        self.txns = {}
        self.net = []                # (src, dst, payload)
        self.history = []            # (kind, txn, "x@A" or None)
        self.commit_order = []
        self.messages = 0
        self.victims = []

    # ------------------------------------------------------------ network
    def send(self, src, dst, payload):
        if src != dst:
            self.messages += 1
        self.net.append((src, dst, payload))

    def deliver(self, k):
        chan = self.net[k][:2]
        k = next(j for j, m in enumerate(self.net) if m[:2] == chan)   # FIFO per channel
        src, dst, payload = self.net.pop(k)
        if payload[0] in ("granted", "value", "ack", "nores"):
            self.on_txn(self.txns[payload[1]], payload)
        elif not self.sites[dst].up:
            if payload[0] != "release":
                self.send(dst, src, ("nores", payload[1], payload, dst))
        else:
            self.on_site(self.sites[dst], src, payload)
        self.detect_deadlocks()

    # ------------------------------------------------------------- sites
    def on_site(self, site, src, payload):
        kind, tid = payload[0], payload[1]
        if kind == "lock":
            _, _, x, mode, read_here = payload
            if self.txns[tid].status == "aborted":
                return
            req = (tid, mode, read_here)
            if not site.queue[x] and site.compatible(x, tid, mode):
                self.grant(site, x, req)
            else:
                site.queue[x].append(req)
        elif kind == "read":
            x = payload[2]
            self.history.append(("r", tid, "%s@%s" % (x, site.sid)))
            self.send(site.sid, self.txns[tid].home, ("value", tid, x, site.value[x]))
        elif kind == "install":
            _, _, x, v = payload
            site.value[x] = v
            self.history.append(("w", tid, "%s@%s" % (x, site.sid)))
            self.send(site.sid, self.txns[tid].home, ("ack", tid, x, site.sid))
        elif kind == "release":
            for x, v in payload[2].items():
                site.value[x] = v
                self.history.append(("w", tid, "%s@%s" % (x, site.sid)))
            self.release(site, tid)

    def grant(self, site, x, req):
        tid, mode, read_here = req
        h = site.holders[x]
        h[tid] = EXCLUSIVE if mode == EXCLUSIVE or h.get(tid) == EXCLUSIVE else SHARED
        value = None
        if read_here:
            value = site.value[x]
            self.history.append(("r", tid, "%s@%s" % (x, site.sid)))
        self.send(site.sid, self.txns[tid].home, ("granted", tid, x, value))

    def release(self, site, tid):
        for x in site.primary_of:
            site.holders[x].pop(tid, None)
            site.queue[x] = [q for q in site.queue[x] if q[0] != tid]
        for x in site.primary_of:
            while site.queue[x] and site.compatible(x, site.queue[x][0][0], site.queue[x][0][1]):
                self.grant(site, x, site.queue[x].pop(0))

    def fail(self, sid):
        site = self.sites[sid]
        if not site.up:
            return
        site.up = False
        lost = {tid for x in site.primary_of for tid in site.holders[x]}
        lost |= {q[0] for x in site.primary_of for q in site.queue[x]}
        site.holders = {x: {} for x in site.primary_of}
        site.queue = {x: [] for x in site.primary_of}
        for tid in sorted(lost):
            t = self.txns[tid]
            if t.status == "active":      # a committing transaction keeps going
                self.abort(t)

    # ----------------------------------------------------------- clients
    def start(self, tid, ops, home):
        t = Txn(tid, ops, home)
        self.txns[tid] = t
        self.issue(t)

    def write_value(self, t):
        return t.tid * 100 + sum(t.reads[x] for x in sorted(t.reads)) % 100

    def issue(self, t):
        if t.i == len(t.ops):
            self.commit(t)
            return
        kind, x = t.ops[t.i]                                  # @line L1
        p = self.primary[x]
        t.contacted.add(p)
        if kind == "r":                                       # @line L2
            local = t.home in self.placement[x] and t.home != p
            # @line L3
            self.send(t.home, p, ("lock", t.tid, x, SHARED, not local))
        else:                                                 # @line L5
            # @line L6
            self.send(t.home, p, ("lock", t.tid, x, EXCLUSIVE, False))

    def on_txn(self, t, payload):
        if t.status in ("aborted", "committed"):
            return
        kind = payload[0]
        if t.status == "committing":
            # an ack, or "no response" from a copy whose site is down
            x, s = (payload[2], payload[3]) if kind == "ack" else (payload[2][2], payload[3])
            t.pending.discard((x, s))                         # @line L9
            if not t.pending:
                self.finish(t)
            return
        op, x = t.ops[t.i]
        if kind == "nores":
            if payload[2][0] == "read":
                # the local copy is down; read the primary copy, still under the lock
                self.send(t.home, self.primary[x], ("read", t.tid, x))
                return
            self.abort(t)                                     # the primary is down
            return
        if kind == "granted" and op == "r" and payload[3] is None:
            self.send(t.home, t.home, ("read", t.tid, x))     # @line L4
            return
        if op == "r":
            t.reads[x] = payload[3]                           # @line L4
        else:
            t.writes[x] = self.write_value(t)
        t.i += 1
        self.issue(t)

    def commit(self, t):
        # T holds all its locks here, so this is its lock point.
        t.status = "committing"                               # @line L7
        self.history.append(("c", t.tid, None))
        self.commit_order.append(t.tid)
        t.pending = set()
        for x in sorted(t.writes):                            # @line L8
            for s in self.placement[x]:
                if s != self.primary[x]:
                    t.pending.add((x, s))
                    self.send(t.home, s, ("install", t.tid, x, t.writes[x]))
        if self.early_release or not t.pending:
            self.finish(t)

    def finish(self, t):
        for p in sorted(t.contacted):                         # @line L10
            mine = {x: v for x, v in t.writes.items() if self.primary[x] == p}
            self.send(t.home, p, ("release", t.tid, mine))
        t.status = "committed"

    def abort(self, t):
        t.status = "aborted"
        self.history.append(("a", t.tid, None))
        for p in sorted(t.contacted):
            self.send(t.home, p, ("release", t.tid, {}))

    # ---------------------------------------------------------- deadlocks
    def waits_for(self):
        edges = {}
        for s in sorted(self.sites):
            site = self.sites[s]
            if not site.up:
                continue
            for x in site.primary_of:
                q = site.queue[x]
                for pos, (w, mode, _) in enumerate(q):
                    if self.txns[w].status != "active":
                        continue
                    for h, m in site.holders[x].items():
                        if h != w and (mode == EXCLUSIVE or m == EXCLUSIVE):
                            edges.setdefault(w, set()).add(h)
                    for w2, m2, _ in q[:pos]:
                        if w2 != w and (mode == EXCLUSIVE or m2 == EXCLUSIVE):
                            edges.setdefault(w, set()).add(w2)
        return edges

    def find_cycle(self, edges):
        color, stack = {}, []

        def dfs(u):
            color[u] = 1
            stack.append(u)
            for v in sorted(edges.get(u, ())):
                if color.get(v, 0) == 1:
                    return stack[stack.index(v):]
                if color.get(v, 0) == 0:
                    c = dfs(v)
                    if c:
                        return c
            stack.pop()
            color[u] = 2
            return None

        for u in sorted(edges):
            if color.get(u, 0) == 0:
                c = dfs(u)
                if c:
                    return c
        return None

    def detect_deadlocks(self):
        while True:
            cycle = self.find_cycle(self.waits_for())
            if not cycle:
                return
            active = [v for v in cycle if self.txns[v].status == "active"]
            victim = max(active)
            self.victims.append((victim, tuple(cycle)))
            self.abort(self.txns[victim])

    # ---------------------------------------------------------------- run
    def run(self, rng, txns, homes, events=(), start_spread=3):
        """txns: {tid: ops}; homes: {tid: site}; events: [(step, "fail", site)]."""
        starts = sorted((rng.randrange(start_spread), tid) for tid in sorted(txns))
        events = sorted(events)
        step = 0
        while True:
            while starts and starts[0][0] <= step:
                _, tid = starts.pop(0)
                self.start(tid, txns[tid], homes[tid])
            while events and events[0][0] <= step:
                self.fail(events.pop(0)[2])
                self.detect_deadlocks()
            if self.net:
                self.deliver(rng.randrange(len(self.net)))
            elif starts or events:
                nxt = [starts[0][0]] if starts else []
                nxt += [events[0][0]] if events else []
                step = max(step, min(nxt))
                continue
            else:
                break
            step += 1
        stuck = [t.tid for t in self.txns.values() if t.status not in ("committed", "aborted")]
        if stuck:
            raise RuntimeError("transactions left waiting: %r" % stuck)
        return self.history
test_primary_copy_locking.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/primary-copy-locking/. The authors are listed in prov/SBHSMT.jsonl.
import itertools
import random
import unittest

from primary_copy_locking import PrimaryCopyDB

PLACEMENT = {"x": ["A", "B", "C"], "y": ["B", "C"], "z": ["A", "C"]}
SITES = ["A", "B", "C", "D"]


def item(copy):
    return copy.split("@")[0]


def physical_view(db):
    """Reads-from on items and the final writer of each copy, from the
    copy-level history. Every write in the history is committed."""
    committed = {t for t, x in db.txns.items() if x.status == "committed"}
    last = {}
    rf = {}
    for kind, t, c in db.history:
        if kind == "w":
            last[c] = t
        elif kind == "r" and t in committed:
            rf[(t, item(c))] = last.get(c, 0)
    return committed, rf, last


def serial_view(db, order):
    last, rf = {}, {}
    for t in order:
        for kind, x in db.txns[t].ops:
            if kind == "r" and (t, x) not in rf:
                rf[(t, x)] = last.get(x, 0)
            elif kind == "w":
                last[x] = t
    return rf, last


def equivalent(db, order):
    """The definition of one-copy serializability (BHG Section 8.3)."""
    committed, rf, final_copy = physical_view(db)
    rf1, final1 = serial_view(db, order)
    if rf1 != rf:
        return False
    return all(any(item(c) == x and t == w for c, t in final_copy.items())
               for x, w in final1.items())


def one_copy_orders(db):
    committed = sorted(t for t, x in db.txns.items() if x.status == "committed")
    assert len(committed) <= 6
    return [o for o in itertools.permutations(committed) if equivalent(db, o)]


def random_txns(rng, n):
    txns, homes = {}, {}
    for tid in range(1, n + 1):
        ops = []
        for x in rng.sample(sorted(PLACEMENT), rng.randint(1, 2)):
            ops += [(k, x) for k in rng.choice([["r"], ["w"], ["r", "w"]])]
        txns[tid] = ops
        homes[tid] = rng.choice(SITES)
    return txns, homes


def live_copies_agree(db):
    for x, sites in PLACEMENT.items():
        if not db.sites[db.primary[x]].up:
            continue
        vals = {db.sites[s].value[x] for s in sites if db.sites[s].up}
        if len(vals) > 1:
            return False
    return True


class TestPrimaryCopy(unittest.TestCase):
    def test_one_copy_serializable_in_commit_order(self):
        for seed in range(200):
            rng = random.Random(seed)
            db = PrimaryCopyDB(PLACEMENT)
            txns, homes = random_txns(rng, rng.randint(2, 4))
            db.run(rng, txns, homes)
            committed = [t for t in db.commit_order if db.txns[t].status == "committed"]
            self.assertTrue(equivalent(db, committed), seed)
            self.assertTrue(live_copies_agree(db), seed)

    def test_with_site_failures(self):
        for seed in range(200):
            rng = random.Random(1000 + seed)
            db = PrimaryCopyDB(PLACEMENT)
            txns, homes = random_txns(rng, 3)
            events = [(rng.randrange(8), "fail", rng.choice(["A", "B", "C"]))]
            db.run(rng, txns, homes, events)
            committed = [t for t in db.commit_order if db.txns[t].status == "committed"]
            self.assertTrue(equivalent(db, committed), seed)
            self.assertTrue(live_copies_agree(db), seed)

    def test_early_release_is_wrong(self):
        bad = 0
        for seed in range(200):
            rng = random.Random(seed)
            db = PrimaryCopyDB(PLACEMENT, early_release=True)
            txns, homes = random_txns(rng, 3)
            db.run(rng, txns, homes)
            bad += not one_copy_orders(db)
        self.assertGreater(bad, 0)

    def test_locks_only_at_the_primary(self):
        # A write of x with three copies, from a home site that holds no copy:
        # lock request and grant at A, two installs and two acks, one release.
        db = PrimaryCopyDB(PLACEMENT)
        db.run(random.Random(0), {1: [("w", "x")]}, {1: "D"})
        self.assertEqual(db.messages, 2 + 2 * 2 + 1)
        self.assertEqual(sorted(c for k, t, c in db.history if k == "w"), ["x@A", "x@B", "x@C"])
        self.assertEqual({db.sites[s].value["x"] for s in "ABC"}, {100})

    def test_read_costs(self):
        # Reading the local copy at B needs a lock at the primary A: 2 messages.
        db = PrimaryCopyDB(PLACEMENT)
        db.run(random.Random(0), {1: [("r", "x")]}, {1: "B"})
        self.assertEqual(db.messages, 2 + 1)            # lock, grant, release
        self.assertEqual(db.history[0], ("r", 1, "x@B"))
        # With no local copy, the lock request reads the primary copy at once.
        db = PrimaryCopyDB(PLACEMENT)
        db.run(random.Random(0), {1: [("r", "y")]}, {1: "A"})
        self.assertEqual(db.messages, 2 + 1)
        self.assertEqual(db.history[0], ("r", 1, "y@B"))
        # At the primary site itself, a read sends no message.
        db = PrimaryCopyDB(PLACEMENT)
        db.run(random.Random(0), {1: [("r", "x")]}, {1: "A"})
        self.assertEqual(db.messages, 0)

    def test_failed_primary_makes_the_item_unavailable(self):
        db = PrimaryCopyDB(PLACEMENT)
        db.fail("A")
        db.run(random.Random(0), {1: [("r", "x")], 2: [("r", "y")]}, {1: "B", 2: "C"})
        self.assertEqual(db.txns[1].status, "aborted")
        self.assertEqual(db.txns[2].status, "committed")

    def test_deadlock_on_upgrade_is_broken(self):
        found = False
        for seed in range(80):
            db = PrimaryCopyDB(PLACEMENT)
            db.run(random.Random(seed), {1: [("r", "x"), ("w", "x")], 2: [("r", "x"), ("w", "x")]},
                   {1: "B", 2: "C"}, start_spread=1)
            self.assertTrue(one_copy_orders(db))
            for victim, cycle in db.victims:
                found = True
                self.assertEqual(victim, max(cycle))
        self.assertTrue(found)

    def test_oracle_rejects_a_stale_read(self):
        # T1 writes x at A only, then T2 reads the old copy at B and writes y,
        # and T1 read y: the BHG history H1 is serial but not 1SR.
        db = PrimaryCopyDB({"x": ["A", "B"], "y": ["C"]})
        db.txns = {}
        from primary_copy_locking import Txn
        db.txns[1] = Txn(1, [("r", "y"), ("w", "x")], "A")
        db.txns[2] = Txn(2, [("r", "x"), ("w", "y")], "A")
        db.txns[1].status = db.txns[2].status = "committed"
        db.history = [("r", 1, "y@C"), ("w", 1, "x@A"), ("r", 2, "x@B"), ("w", 2, "y@C")]
        self.assertEqual(one_copy_orders(db), [])


if __name__ == "__main__":
    unittest.main()

History

Stonebraker (1979) proposed the primary copy method for distributed INGRES, to keep the copies of data consistent with locks at one copy. Alsberg and Day (1976) had earlier proposed a primary site scheme for the resilient sharing of distributed resources, which the survey files under centralized 2PL. In their 1981 survey, Bernstein and Goodman described primary copy 2PL beside basic, voting and centralized 2PL, and compared their message costs. Later systems kept the idea of one lock manager per item or per shard, and made the primary fault tolerant with replication protocols such as Paxos.

References

  1. Philip A. Bernstein and Nathan Goodman, Concurrency control in distributed database systems, ACM Computing Surveys 13(2), 1981, pages 185 to 221, Section 3.2, Primary Copy 2PL (the message costs of reads and writes compared with basic 2PL), Section 3.4, Centralized 2PL, and Section 5.1, the methods that combine primary copy 2PL with other techniques
  2. Michael Stonebraker, Concurrency control and consistency of multiple copies of data in distributed INGRES, IEEE Transactions on Software Engineering SE-5(3), 1979, pages 188 to 194, the primary copy scheme for the multiple copies of data in distributed INGRES
  3. Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 8, Replicated Data, Section 8.3 (the definition of one-copy serializability used in the proof)

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 space.extra
  • a full proof of messages.worst
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)
WritingW0 stub
  • complexity claims in the front matter