Algorithm Search⌘K

Algorithmcore

Read-one write-all

Also called ROWA, ROWA-available, available copies.

A replica control protocol that reads any one copy of an item and writes all copies, or all available copies in its fault-tolerant form.

Space
O(r + w n) extra
Counts
messages 2(r + w) n 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
Philip A. Bernstein, Nathan Goodman, 1984

Read-one write-all (ROWA) is the simplest way to keep the copies of a replicated item consistent. A transaction reads any one copy of an item, and it writes every copy. Each site runs strict two-phase locking on its own copies. The result is one-copy serializable: the users see the same results as with one copy of each item and a serial order of the transactions. Plain ROWA cannot write an item while one of its sites is down. The available copies form (ROWA-A) writes all copies whose sites answer, and it adds two checks at commit, missing writes validation and access validation, together with a copier transaction that brings a recovered copy up to date. Without these checks the scheme is wrong, and the page shows a history that proves it.

In plain words

A club keeps the same member list in three offices. To look up a name, you can phone any one office. To change the list, you must phone all three offices and get each of them to make the change. Then every office always has the same list, and any one of them gives the correct answer.

If one office is closed, plain ROWA cannot change the list at all. The available copies form changes the list in the offices that are open and notes which office was closed. Before it finishes, it checks that the closed office is still closed, and that no open office closed in the meantime. A closed office that opens again does not answer lookups until it has copied the current list from another office.

The problem

A database holds items x,y,…x, y, \dots, and each item has copies xA,xB,…x_A, x_B, \dots at a fixed set of sites. Users submit transactions as if each item had one copy. The replica control protocol maps each logical read and write to actions on copies. The output must be one-copy serializable (1SR): the physical history must be equivalent to a serial history of the same transactions on a database with one copy of each item.

The model is the asynchronous model with one strong addition. Sites fail by stopping (crash failure), a failed site loses its lock table and keeps its stored values, and a request to a failed site comes back as "no response". The answer "no response" is never wrong: the network does not lose messages, and it does not partition. This is a failure detector that makes no mistakes, and the available copies form is correct only under it. Each site runs strict two-phase locking on its copies, with S locks for reads and X locks for writes held until commit or abort.

The algorithm

  1. ROWA-A-TRANSACTION(T)
  2. 1for each operation of T, in order do
  3. 2if the operation is a read of x then
  4. 3for each copy x_A of x, in a fixed order, until one read succeeds do
  5. 4ask site A for an S lock on x_A and read x_A
  6. 5if no copy answered then abort T
  7. 6else ▷ a write of x with value v
  8. 7send an X lock request for x_A, with v, to every copy x_A of x
  9. 8wait until each site has granted or is found down
  10. 9if no site granted then abort T ▷ plain ROWA: if any site is down
  11. 10record the copies at the down sites as missed copies of T
  12. 11for each missed copy x_A of T do
  13. 12if site A is up again then abort T ▷ missing writes validation
  14. 13for each copy x_A that T read or wrote do
  15. 14if site A failed after T locked x_A then abort T ▷ access validation
  16. 15commit T at every site it accessed: install its writes and release its locks

Plain ROWA is the same procedure with the stronger test of line L9: a write aborts if any copy did not answer. It then never has missed copies, and lines L11 to L14 never abort in a run without failures.

Recovery. A site that recovers starts a new epoch and marks each replicated copy as unreadable. A read of an unreadable copy is refused, and line L3 then tries the next copy. For each such copy xAx_A, the site starts a copier transaction that reads xx at another site and writes the value to all copies of xx, with the same procedure. A copy becomes readable again when a committed write, of the copier or of a user transaction, is installed on it. A copy with no other copy stays readable.

Validation at commit. A site records its epoch when it grants a lock, and line L14 compares it with the epoch at commit. In the code, lines L11 to L15 are one atomic step. In a real system this step is the vote phase of an atomic commitment protocol such as two-phase commit: each site that T accessed must still have T's locks, and each missed site must still be down.

Deadlocks. Strict 2PL at the sites can deadlock, also across sites. The code uses a central deadlock 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 replace it.

Example

A plain write. Item xx has copies at AA and BB, and yy has copies at AA, BB and CC. Transaction T1=r1[x] w1[y]T_1 = r_1[x]\, w_1[y] runs alone. It reads xAx_A and writes all three copies of yy. The code records the physical history r1[xA] w1[yC] w1[yB] w1[yA] c1r_1[x_A]\, w_1[y_C]\, w_1[y_B]\, w_1[y_A]\, c_1, in the order in which the random network delivered the grants. It sends 2⋅1+2⋅3=82 \cdot 1 + 2 \cdot 3 = 8 messages: one request and one answer for the read, and one request and one grant for each copy of yy.

Why the validations are needed. This is the example of Bernstein, Hadzilacos and Goodman. Item xx has copies at AA and BB, and yy has copies at CC and DD. Let T1=r1[x] w1[y]T_1 = r_1[x]\, w_1[y] and T2=r2[y] w2[x]T_2 = r_2[y]\, w_2[x].

step event effect
1 T1T_1 reads xAx_A, T2T_2 reads yCy_C both reads get the initial value 0
2 sites AA and CC fail the S locks on xAx_A and yCy_C are lost
3 T1T_1 writes yy yCy_C: no response, yDy_D: granted
4 T2T_2 writes xx xAx_A: no response, xBx_B: granted
5 both commit yD=100y_D = 100, xB=200x_B = 200

The code, run with the validations turned off, gives the history r1[xA] r2[yC] w1[yD] w2[xB] c1 c2r_1[x_A]\, r_2[y_C]\, w_1[y_D]\, w_2[x_B]\, c_1\, c_2 with 12 messages. At the copy level it is conflict serializable, because no two actions touch the same copy. But it is not 1SR. In a serial one-copy history, either T1T_1 comes first and T2T_2 reads yy from T1T_1, or T2T_2 comes first and T1T_1 reads xx from T2T_2. Here both read the initial values. The brute-force test of the code finds no serial order.

With the validations on, line L14 sees that AA failed after T1T_1 locked xAx_A, and it aborts T1T_1; for the same reason, at CC, it aborts T2T_2. The history ends in a1 a2a_1\, a_2. If AA and CC had recovered before the commit, line L12 would have aborted both instead.

A wrong copier. Let the copier of a recovered copy write only that copy. In one test run (seed 28), site AA recovers and its copier T1000T_{1000} brings xAx_A up to date, while a user transaction T3=r3[x] w3[x]T_3 = r_3[x]\, w_3[x] runs. The history contains r1000[xB] r3[xB] w1000[xA] c1000 w3[xB] w3[xA] c3r_{1000}[x_B]\, r_3[x_B]\, w_{1000}[x_A]\, c_{1000}\, w_3[x_B]\, w_3[x_A]\, c_3. The copier takes no lock on xBx_B that conflicts with the S lock of T3T_3. In the one-copy view, both transactions read the initial xx and both write xx, which is a lost update, and no serial order fits. When the copier writes all copies of xx, its write on xBx_B waits for the S lock of T3T_3, and all 250 test runs with one failure and one recovery are 1SR.

Correctness

The claims are proved on the proof page, in the model above.

  • One-copy serializability (theorem). Every history of ROWA-A, and so of plain ROWA, is 1SR, in the order of the commits. The proof has two steps. First, at the moment a writer of xx commits, every copy of xx at an up site holds its X lock and gets its value: a copy that did not answer must still be down (line L12), and a copy that answered must still be locked (line L14). So every readable copy at an up site holds the last committed value of xx. Second, a reader of xAx_A holds its S lock on xAx_A until it commits, and its site does not fail in that time. So no writer of xx can commit between the read and the commit of the reader.
  • The validations are needed. The example above is a history that the protocol without lines L11 to L14 accepts, and it is not 1SR.
  • The copier must be a full transaction. A copier that writes only the recovered copy gives histories that are not 1SR. The tests find them.
Proof: The available copies form of read-one write-all gives one-copy serializable historiesfull

We use the line numbers of the pseudocode on the page. This proof is for the simplified model of the page, which is also the model of the code. It follows the argument of Bernstein, Hadzilacos and Goodman (1987), Section 8.6, in a shorter form.

The model. Each item xx has copies xAx_A at a fixed set of sites. Sites fail by stopping. A failed site loses its lock table and its queued requests, and it keeps the values of its copies. A request to a failed site comes back as "no response", and only a failed site gives that answer. A site that recovers starts a new epoch, marks all its copies unreadable and refuses reads on them. A write to an unreadable copy is allowed, and a copy becomes readable when a committed write is installed on it. Each site runs strict two-phase locking on its own copies: a read holds an S lock on the copy and a write holds an X lock, both until the end of the transaction, and two locks of different transactions on one copy conflict unless both are S. A write is staged at the site when its lock is granted and installed at commit. The validations of lines L11 to L14 and the commit of line L15 are one atomic step. This step stands for an atomic commitment protocol. A transaction reads an item at most once and does not read an item after it writes it. The copier of a recovered copy is an ordinary transaction that reads xx and writes the value to all copies of xx, so it is part of the history like every other transaction.

The physical history HH is the sequence of copy actions in the order of the grants: rT[xA]r_T[x_A] when TT gets the S lock on xAx_A, wT[xA]w_T[x_A] when TT gets the X lock, and then cTc_T or aTa_T. For a committed transaction TT, let γT\gamma_T be the moment of its commit step. Let C\mathcal{C} be the set of committed transactions, with the initial transaction T0T_0 that wrote every copy before the start.

Definition (one-copy serializability). HH is one-copy serializable if there is a serial order SS of C\mathcal{C}, run on a database with one copy of each item, such that (a) TT reads xx from UU in HH (that is, rT[xA]r_T[x_A] reads from wU[xA]w_U[x_A] for some copy) exactly when TT reads xx from UU in SS, and (b) for each item xx, if WW writes xx last in SS, then wW[xA]w_W[x_A] is the last committed write on xAx_A in HH for some copy xAx_A.

Lemma 1 (held locks survive). Let T∈CT \in \mathcal{C} hold a lock on xAx_A that it got at time tt. Then site AA did not fail in the interval [t,γT][t, \gamma_T], and TT holds the lock during the whole interval.

Proof. At time tt, TT records the epoch of AA (line L4 or L8). Line L14 runs at γT\gamma_T and finds AA up and in the same epoch, or TT would abort. A failure of AA in [t,γT][t, \gamma_T] would put AA down, and a recovery after it would change the epoch, so there was no failure. Only a failure, the commit or an abort removes a lock, so TT holds it until γT\gamma_T. □\square

Lemma 2 (a committed write reaches every live copy). Let T∈CT \in \mathcal{C} write xx. At the moment γT\gamma_T, every copy xAx_A at a site that is up holds an X lock of TT, and line L15 installs the write of TT on it. At least one such copy exists.

Proof. Line L7 sends a request to every copy of xx, and line L8 waits for each answer. Take a copy xAx_A at a site that is up at γT\gamma_T. If AA answered "no response", line L10 recorded xAx_A as missed, and line L12 would abort TT because AA is up. So AA granted the lock, and by Lemma 1 TT still holds it at γT\gamma_T. Line L15 installs the staged value. Line L9 aborts TT if no copy granted, so some copy granted, and by Lemma 1 its site is up at γT\gamma_T. □\square

For a time tt and an item xx, let last(x,t)\mathrm{last}(x, t) be the transaction of C\mathcal{C} that writes xx and has the largest γ\gamma before tt, or T0T_0 if there is none.

Lemma 3 (readable copies are current). At every time tt between two steps, every readable copy xAx_A at a site that is up holds the value installed by last(x,t)\mathrm{last}(x, t).

Proof. By induction on the steps. At the start, every copy holds the value of T0T_0. Only four kinds of step change a copy, its readability or last(x,t)\mathrm{last}(x, t). A failure makes a site down, and a recovery makes all its copies unreadable, so neither step can break the claim. An abort installs nothing. A commit of a transaction TT that writes xx makes T=last(x,t)T = \mathrm{last}(x, t) after the step, and by Lemma 2 it installs its value on every copy of xx at an up site. A commit of a transaction that does not write xx changes neither the copies of xx nor last(x,t)\mathrm{last}(x, t). □\square

Lemma 4 (one order of grants). If U,V∈CU, V \in \mathcal{C} both write xAx_A, the order of wU[xA]w_U[x_A] and wV[xA]w_V[x_A] in HH is the order of γU\gamma_U and γV\gamma_V. If T∈CT \in \mathcal{C} reads xAx_A at time tt, then no transaction of C\mathcal{C} other than TT holds an X lock on xAx_A at time tt or commits a write on xAx_A in [t,γT][t, \gamma_T].

Proof. By Lemma 1, a committed transaction holds its lock on xAx_A from the grant to its commit, with no failure of AA in between, so the lock table of AA is not cleared in that interval. Two X locks conflict, so the intervals of UU and VV are disjoint, and the one that is granted first commits first. The S lock of TT conflicts with an X lock, so the interval [t,γT][t, \gamma_T] of TT is disjoint from the X interval of every other committed writer of xAx_A. □\square

So in HH, the write that rT[xA]r_T[x_A] reads from (the last committed write on xAx_A before it) is the last write installed on xAx_A before time tt.

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

Proof. Let T∈CT \in \mathcal{C} read xx at copy xAx_A at time tt, and let U=last(x,t)U = \mathrm{last}(x, t). The copy is readable and its site is up, because the site granted the read, so by Lemma 3 and the note after Lemma 4, TT reads xx from UU in HH. We show that UU is also the last writer of xx before TT in SS. First, γU<t<γT\gamma_U < t < \gamma_T. Suppose that some V∈CV \in \mathcal{C}, V≠TV \neq T, writes xx and has t<γV<γTt < \gamma_V < \gamma_T. By Lemma 1, AA is up at γV\gamma_V, so by Lemma 2 VV holds an X lock on xAx_A at γV\gamma_V. By Lemma 1, TT holds its S lock on xAx_A at the same moment. The two locks conflict, which is impossible. No writer of xx has γ\gamma between γU\gamma_U and tt, by the choice of UU. A transaction does not read an item after it writes it, so TT does not read its own write. So TT reads xx from UU in SS, and condition (a) holds in this direction. Each read of TT in SS is one read of TT in HH, so condition (a) holds in both directions.

For condition (b), let WW be the last writer of xx in SS, so WW has the largest γ\gamma among the writers of xx. By Lemma 2, some copy xAx_A gets the write of WW at γW\gamma_W. No committed transaction writes xAx_A after it, because by Lemma 4 such a write would come with a later commit. So wW[xA]w_W[x_A] is the last committed write on xAx_A in HH. ■\blacksquare

Plain ROWA. Plain ROWA aborts at line L9 if any copy did not answer, so no transaction has missed copies. The proof above holds without change. With no failures at all, lines L11 to L14 never abort, and the proof shows that strict two-phase locking at the copies, with one read and all writes, is enough.

Where each part is used. The examples on the page show that no part can be left out. Without line L12, the history r1[xA] r2[yC] w1[yD] w2[xB] c1 c2r_1[x_A]\, r_2[y_C]\, w_1[y_D]\, w_2[x_B]\, c_1\, c_2 commits after AA and CC fail; the copy level history is conflict serializable, but each transaction reads the item that the other one writes, before the write, so no serial one-copy order exists. Lemma 2 fails there, because CC is down and DD is up. A copier that writes only the recovered copy breaks Lemma 2 for itself: a reader that holds an S lock on another copy does not block the copier. The history r1000[xB] r3[xB] w1000[xA] c1000 w3[xB] w3[xA] c3r_{1000}[x_B]\, r_3[x_B]\, w_{1000}[x_A]\, c_{1000}\, w_3[x_B]\, w_3[x_A]\, c_3 from the test file is then possible, and it has no one-copy order.

Theorem 2 (messages). Let nn be the largest number of copies of an item. A transaction with rr reads and ww writes sends at most 2(r+w)n2(r + w)n messages for its reads and writes. If every item has exactly nn copies and every read succeeds at the first copy it tries, it sends exactly 2r+2wn2r + 2wn.

Proof. A read sends one request and gets one answer per copy it tries (lines L3 and L4), and it tries at most nn copies. A write sends one request to each copy and gets one answer (a grant or "no response") for each, at most 2n2n messages (lines L7 and L8). A write to xx always sends to every copy of xx, so with nn copies of each item and one try per read the count is exactly 2r+2wn2r + 2wn. The messages of the atomic commitment protocol of line L15 are not counted. ■\blacksquare

Complexity

Let nn be the largest number of copies of an item.

  • Messages. A read costs 2 messages if the first copy it tries answers, and at most 2n2n. A write of an item with nn copies costs 2n2n messages, one request and one answer per copy. A transaction with rr reads and ww writes sends at most 2(r+w)n2(r + w)n messages, and exactly 2r+2wn2r + 2wn if each item has nn copies and each read succeeds at its first try. The atomic commitment protocol adds its own messages, for example about 4s4s for two-phase commit over ss sites (prepare, vote, decision and acknowledgment).
  • Rounds. The writes to the copies of one item go out in parallel, so each operation takes one round trip when the first copy answers.
  • Space. A transaction keeps the values it read, one epoch per granted lock and its list of missed copies, O(r+wn)O(r + wn) in all. Each site keeps an epoch number and one readable flag per copy.
  • Availability. Plain ROWA can read while one copy is up, and it can write only while all copies are up. With nn copies that are each up with probability pp, independently, a write is possible with probability pnp^n, which falls as copies are added. ROWA-A can write while one copy is up.

Properties

  • 1SR, in commit order. Shown above.
  • Reads are cheap. A read touches one copy, so a read-mostly workload gains from more copies.
  • Writes touch every copy. The cost and the lock time of a write grow with nn.
  • Not partition tolerant. The available copies form relies on the answer "no response". If the network splits into two parts, each part can see the other as down, and two transactions can commit in the two parts with conflicting accesses on different copies of one item. BHG Section 8.8 gives such a history that is not 1SR. Plain ROWA blocks its writes instead.
  • Deadlocks. Strict 2PL at the sites can deadlock, so the system needs detection or prevention.

Variants and improvements

  • Quorum consensus. Quorum replication reads qrq_r copies and writes qwq_w copies, with qr+qw>nq_r + q_w > n and 2qw>n2 q_w > n. ROWA is the case qr=1q_r = 1, qw=nq_w = n. Quorums keep writes possible when some copies are down, and also when the network is partitioned, at the cost of more expensive reads.
  • Directory-oriented available copies. Bernstein, Hadzilacos and Goodman (Section 8.7) also give a version that keeps a directory of the available copies of each item. A transaction writes the copies that the directory lists, and special transactions change the directory when a copy fails or is created.
  • Virtual partitions. The sites that can talk to each other agree on a view of which sites are up, and the transactions apply ROWA inside the view. A view may read or write an item only if it holds a read or write quorum of its copies, so a read still touches one copy. BHG Section 8.10 describes this method.
  • Primary copy. Primary copy locking takes locks only at one copy of each item and sends the writes to the other copies. It costs fewer lock messages, and the primary is a single point of failure for its items.
  • Lazy replication. Lazy replication writes one copy inside the transaction and the other copies after the commit. It gives up 1SR for speed.

When to use it

Use plain ROWA when reads are much more frequent than writes, the copies are few and the sites rarely fail. Use ROWA-A when sites fail and recover but the network does not partition, for example within one machine room with a reliable failure detector. When the network can split, use quorums, a primary with a consensus protocol, or state machine replication.

Pitfalls

  • Writing all available copies without validation. This is the error of the example. The validations at commit are what make the scheme correct, and they must run inside the atomic commitment step.
  • A copier that writes only the new copy. The copier must conflict with readers of the other copies. Make it an ordinary transaction that reads xx and writes all copies of xx.
  • Reading a recovered copy too early. A copy that has just come back can hold a stale value. Mark it unreadable until a committed write is installed on it.
  • Trusting timeouts as failure detection. A slow site that is taken as down breaks the argument, because it can still hold locks and values. Use the available copies form only where "down" is certain, or use quorums.
  • Losing the epoch. Access validation needs to know that the site did not fail and recover while the transaction held its lock. A site that only checks "up now" misses a failure and recovery between the lock and the commit.

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()
read_one_write_all.py 355 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/read-one-write-all/. The authors are listed in prov/JG3SB7.jsonl.
"""Read-one write-all (ROWA) and the available copies form (ROWA-A).

This is a small simulation in one thread. Each site holds copies of some
items and runs strict two-phase locking on its own copies. A transaction is
a client that sends lock requests as messages. The network holds the
messages in flight, and a seeded random.Random picks the next one to deliver.

A read locks and reads one copy. A write locks all copies (ROWA) or all
copies whose sites answer (ROWA-A). A site can fail: it loses its lock table
and its queued requests, and a message to a failed site comes back as "no
response". A site that recovers marks its copies unreadable and starts one
copier transaction per item, which reads an available copy and writes the
local copy. ROWA-A commits a transaction only after the two validations of
Bernstein, Hadzilacos and Goodman (1987), Section 8.6. The copier is an
ordinary transaction: it writes the value it read to all available copies,
so it conflicts with every reader of x. With copier_writes_all=False it
writes only the recovered copy; the tests show that this breaks one-copy
serializability.

Simplifications, as stated on the page: the commit step (validation and the
installation of the writes at every site the transaction accessed) is one
atomic step, so it stands for an atomic commitment protocol such as
two-phase commit; deadlocks are found by a central detector that reads the
lock tables of all sites that are up.

The physical history uses copy names "x@A" (the copy of x at site A), so
that the one-copy serializability test of the tests can map it back to items.
"""

SHARED, EXCLUSIVE = "S", "X"


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

    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, copier_site=None):
        self.tid = tid
        self.ops = list(ops)          # ("r", x) or ("w", x)
        self.copier_site = copier_site
        self.i = 0
        self.status = "active"
        self.reads = {}
        self.accessed = []            # (site, item, epoch) for each granted lock
        self.missed = []              # (site, item) for each write that got no response
        self.touched = set()
        self.candidates = []
        self.pending = set()
        self.granted = 0


class ReplicatedDB:
    """Sites, clients and the network. mode is "rowa" or "available"."""

    def __init__(self, placement, mode="available", copier_writes_all=True):
        self.mode = mode
        self.copier_writes_all = copier_writes_all
        self.placement = {x: sorted(s) for x, s in placement.items()}
        sites = 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]])
                      for s in sites}
        self.txns = {}
        self.net = []                 # messages in flight: (dst, payload)
        self.history = []             # physical history: (kind, txn, "x@A" or None)
        self.messages = 0
        self.next_copier = 1000
        self.victims = []

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

    def deliver(self, k):
        dst, payload = self.net.pop(k)
        if dst[0] == "site":
            site = self.sites[dst[1]]
            if not site.up:
                tid = payload[1]
                self.send(("txn", tid), ("nores", tid, site.sid, payload[2]))
            else:
                self.on_site(site, payload)
        else:
            self.on_reply(self.txns[dst[1]], payload)
        self.detect_deadlocks()

    # ------------------------------------------------------------- sites
    def on_site(self, site, payload):
        op, tid, x, value = payload
        t = self.txns[tid]
        if t.status != "active":
            return
        if op == "r" and x not in site.readable:
            self.send(("txn", tid), ("unreadable", tid, site.sid, x))
            return
        mode = SHARED if op == "r" else EXCLUSIVE
        req = (tid, mode, op, value)
        if not site.queue[x] and site.compatible(x, tid, mode):
            self.grant(site, x, req)
        else:
            site.queue[x].append(req)

    def grant(self, site, x, req):
        tid, mode, op, value = req
        h = site.holders[x]
        h[tid] = EXCLUSIVE if mode == EXCLUSIVE or h.get(tid) == EXCLUSIVE else SHARED
        copy = "%s@%s" % (x, site.sid)
        if op == "r":
            self.history.append(("r", tid, copy))
            self.send(("txn", tid), ("granted", tid, site.sid, x, site.value[x], site.epoch))
        else:
            site.staged.setdefault(tid, {})[x] = value
            self.history.append(("w", tid, copy))
            self.send(("txn", tid), ("granted", tid, site.sid, x, None, site.epoch))

    def release(self, site, tid):
        site.staged.pop(tid, None)
        for x in site.items:
            site.holders[x].pop(tid, None)
            site.queue[x] = [q for q in site.queue[x] if q[0] != tid]
        for x in site.items:
            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
        for x in site.items:
            for tid, _, op, _ in site.queue[x]:
                self.send(("txn", tid), ("nores", tid, sid, x))
        site.up = False
        site.holders = {x: {} for x in site.items}
        site.queue = {x: [] for x in site.items}
        site.staged = {}

    def recover(self, sid):
        site = self.sites[sid]
        if site.up:
            return
        site.up = True
        site.epoch += 1
        site.readable = set()
        for x in site.items:
            if len(self.placement[x]) > 1:
                self.start(self.next_copier, [("r", x), ("w", x)], copier_site=sid)
                self.next_copier += 1
            else:
                site.readable.add(x)

    # ----------------------------------------------------------- clients
    def start(self, tid, ops, copier_site=None):
        t = Txn(tid, ops, copier_site)
        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
        if kind == "r":                                   # @line L2
            # @line L3
            t.candidates = [s for s in self.placement[x] if s != t.copier_site]
            self.read_next(t, x)
        else:                                             # @line L6
            # @line L7
            if t.copier_site and not self.copier_writes_all:
                targets = [t.copier_site]
            else:
                targets = self.placement[x]
            t.pending = set(targets)
            t.granted = 0
            value = t.reads[x] if t.copier_site else self.write_value(t)
            for s in targets:
                t.touched.add(s)
                self.send(("site", s), ("w", t.tid, x, value))

    def read_next(self, t, x):
        if not t.candidates:
            self.abort(t)                                 # @line L5
            return
        s = t.candidates.pop(0)
        t.touched.add(s)
        self.send(("site", s), ("r", t.tid, x, None))     # @line L4

    def on_reply(self, t, payload):
        if t.status != "active":
            return
        kind, x = t.ops[t.i]
        if kind == "r":
            if payload[0] == "granted":
                _, _, s, _, value, epoch = payload
                t.reads[x] = value
                t.accessed.append((s, x, epoch))
                t.i += 1
                self.issue(t)
            else:
                self.read_next(t, x)
            return
        # @line L8
        s = payload[2]
        if payload[0] == "granted":
            t.granted += 1
            t.accessed.append((s, x, payload[5]))
        else:
            t.missed.append((s, x))                       # @line L10
        t.pending.discard(s)
        if t.pending:
            return
        if t.granted == 0 or (self.mode == "rowa" and any(m[1] == x for m in t.missed)):
            self.abort(t)                                 # @line L9
            return
        t.i += 1
        self.issue(t)

    def commit(self, t):
        # One atomic step: the two validations, then the commit at every site.
        # mode "naive" skips the validations; it is the wrong protocol that
        # the tests use as a non-example.
        check = self.mode != "naive"
        for s, x in t.missed:                             # @line L11
            if check and self.sites[s].up:
                self.abort(t)                             # @line L12
                return
        for s, x, epoch in t.accessed:                    # @line L13
            site = self.sites[s]
            if check and (not site.up or site.epoch != epoch):
                self.abort(t)                             # @line L14
                return
        # @line L15
        for s in sorted(t.touched):
            site = self.sites[s]
            if not site.up:
                continue
            for x, v in site.staged.get(t.tid, {}).items():
                site.value[x] = v
                site.readable.add(x)
            self.release(site, t.tid)
        t.status = "committed"
        self.history.append(("c", t.tid, None))

    def abort(self, t):
        t.status = "aborted"
        self.history.append(("a", t.tid, None))
        for s in sorted(t.touched):
            if self.sites[s].up:
                self.release(self.sites[s], t.tid)

    # ---------------------------------------------------------- deadlocks
    def waits_for(self):
        """Edges waiter -> txn it waits for, from the lock tables of up sites."""
        edges = {}
        for s in sorted(self.sites):
            site = self.sites[s]
            if not site.up:
                continue
            for x in site.items:
                q = site.queue[x]
                for pos, (w, mode, _, _) in enumerate(q):
                    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
            victim = max(cycle)
            self.victims.append((victim, tuple(cycle)))
            self.abort(self.txns[victim])

    # ---------------------------------------------------------------- run
    def run(self, rng, txns, events=(), start_spread=3):
        """txns: {tid: ops}. events: [(step, "fail" or "recover", site)].
        Transactions start at random steps in range(start_spread)."""
        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])
            while events and events[0][0] <= step:
                _, what, s = events.pop(0)
                if what == "fail":
                    self.fail(s)
                else:
                    self.recover(s)
                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 for t in self.txns.values() if t.status == "active"]
        if stuck:
            raise RuntimeError("transactions left waiting: %r" % [t.tid for t in stuck])
        return self.history
test_read_one_write_all.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/read-one-write-all/. The authors are listed in prov/JG3SB7.jsonl.
import itertools
import random
import unittest

import dbsched
from read_one_write_all import ReplicatedDB

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


def one_copy_order(db):
    """A serial one-copy order equivalent to the physical history, by the
    definition of Bernstein, Hadzilacos and Goodman (Section 8.3): the same
    reads-from relation on items, and each final write of the one-copy
    history is a final write on some copy. None if there is no such order."""
    cp = dbsched.committed_projection(tuple(db.history))
    item = lambda copy: copy.split("@")[0]
    phys_rf = {}
    for occ, src in dbsched.reads_from(cp).items():
        phys_rf[(occ[0], item(occ[2]))] = None if src is None else src[0]
    finals = {(occ[0], item(c)) for c, occ in dbsched.final_writes(cp).items()}
    txns = sorted(dbsched.committed(cp))
    assert len(txns) <= dbsched.MAX_BRUTE_FORCE
    for order in itertools.permutations(txns):
        serial = tuple((k, t, x) for t in order for k, x in db.txns[t].ops)
        rf = {(occ[0], occ[2]): None if src is None else src[0]
              for occ, src in dbsched.reads_from(serial).items()}
        fw = dbsched.final_writes(serial)
        if rf == phys_rf and all((occ[0], x) in finals for x, occ in fw.items()):
            return order
    return None


def random_txns(rng, n):
    txns = {}
    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
    return txns


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


class TestRowa(unittest.TestCase):
    def test_no_failures_one_copy_serializable(self):
        for seed in range(150):
            rng = random.Random(seed)
            db = ReplicatedDB(PLACEMENT, mode="rowa")
            db.run(rng, random_txns(rng, rng.randint(2, 4)))
            self.assertIsNotNone(one_copy_order(db), seed)
            self.assertTrue(copies_agree(db), seed)

    def test_all_short_pairs_commit_alone(self):
        # Each transaction run alone commits, and all copies get its writes.
        rng = random.Random(7)
        for tid, ops in random_txns(rng, 6).items():
            db = ReplicatedDB(PLACEMENT, mode="rowa")
            db.run(random.Random(tid), {tid: ops})
            self.assertEqual(db.txns[tid].status, "committed")
            self.assertTrue(copies_agree(db))

    def test_available_copies_with_failures(self):
        for seed in range(250):
            rng = random.Random(seed)
            db = ReplicatedDB(PLACEMENT, mode="available")
            site = rng.choice(["A", "B", "C"])
            t_fail = rng.randrange(6)
            events = [(t_fail, "fail", site), (t_fail + rng.randrange(1, 8), "recover", site)]
            db.run(rng, random_txns(rng, 3), events)
            self.assertIsNotNone(one_copy_order(db), seed)
            self.assertTrue(copies_agree(db), seed)

    def test_copier_that_writes_only_the_new_copy_is_wrong(self):
        # Seed 0 of the test above: a copier reads x@A and writes only x@B
        # while T3 holds a shared lock on x@A; the result is not 1SR.
        bad = 0
        for seed in range(40):
            rng = random.Random(seed)
            db = ReplicatedDB(PLACEMENT, mode="available", copier_writes_all=False)
            site = rng.choice(["A", "B", "C"])
            t_fail = rng.randrange(6)
            events = [(t_fail, "fail", site), (t_fail + rng.randrange(1, 8), "recover", site)]
            db.run(rng, random_txns(rng, 3), events)
            bad += one_copy_order(db) is None
        self.assertGreater(bad, 0)

    def test_plain_rowa_aborts_a_write_when_a_copy_is_down(self):
        db = ReplicatedDB(PLACEMENT, mode="rowa")
        db.fail("B")
        db.run(random.Random(1), {1: [("r", "x")], 2: [("w", "y")], 3: [("w", "z")]})
        self.assertEqual(db.txns[1].status, "committed")   # reads copy at A
        self.assertEqual(db.txns[2].status, "aborted")     # y@B is down
        self.assertEqual(db.txns[3].status, "committed")   # z is on A and C

    def test_available_copies_write_skips_a_down_copy(self):
        db = ReplicatedDB(PLACEMENT, mode="available")
        db.fail("B")
        db.run(random.Random(1), {2: [("w", "y")]})
        self.assertEqual(db.txns[2].status, "committed")
        self.assertEqual(db.sites["C"].value["y"], 200)

    def bhg_example(self, mode):
        # T1 = r1[x] w1[y], T2 = r2[y] w2[x]. T1 reads x@A, T2 reads y@C,
        # then A and C fail, so each write misses one copy.
        db = ReplicatedDB({"x": ["A", "B"], "y": ["C", "D"]}, mode=mode)
        db.start(1, [("r", "x"), ("w", "y")])
        db.start(2, [("r", "y"), ("w", "x")])
        while len([a for a in db.history if a[0] == "r"]) < 2:
            db.deliver(0)
        while db.net and db.net[0][0][0] == "txn":
            db.deliver(0)
        db.fail("A")
        db.fail("C")
        while db.net:
            db.deliver(0)
        return db

    def test_naive_write_all_available_is_not_1sr(self):
        db = self.bhg_example("naive")
        self.assertEqual(db.txns[1].status, "committed")
        self.assertEqual(db.txns[2].status, "committed")
        self.assertEqual(dbsched.format(db.history).count("r"), 2)
        self.assertIsNone(one_copy_order(db))
        # The copy-level history itself is conflict serializable.
        self.assertTrue(dbsched.is_conflict_serializable(tuple(
            (k, t, None if c is None else c.replace("@", "_")) for k, t, c in db.history)))

    def test_validation_rejects_the_bhg_example(self):
        db = self.bhg_example("available")
        self.assertEqual(db.txns[1].status, "aborted")
        self.assertEqual(db.txns[2].status, "aborted")
        self.assertIsNotNone(one_copy_order(db))

    def test_message_count(self):
        # A read costs one round trip, a write to k copies costs k round trips.
        db = ReplicatedDB({"x": ["A", "B"], "y": ["A", "B", "C"]}, mode="rowa")
        db.run(random.Random(3), {1: [("r", "x"), ("w", "y")]})
        self.assertEqual(db.messages, 2 * 1 + 2 * 3)

    def test_deadlock_is_broken(self):
        # Two transactions read x, then both write x: each waits for the
        # shared lock of the other on the copy they both read.
        found = False
        for seed in range(60):
            db = ReplicatedDB({"x": ["A", "B"]}, mode="rowa")
            db.run(random.Random(seed), {1: [("r", "x"), ("w", "x")],
                                         2: [("r", "x"), ("w", "x")]}, start_spread=1)
            self.assertIsNotNone(one_copy_order(db))
            for victim, cycle in db.victims:
                found = True
                self.assertEqual(victim, max(cycle))
        self.assertTrue(found)

    def test_helper_self_test(self):
        self.assertTrue(dbsched._self_test())


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

History

Read-one write-all is the basic replica control rule of the early work on replicated databases. Thomas (1979) and Gifford (1979) proposed voting schemes in which a write needs only a part of the copies, so that writes go on when some copies are down. Bernstein and Goodman (1984) gave the available copies algorithm, with missing writes validation, access validation and copier transactions, and proved it correct with the theory of one-copy serializability. Bernstein, Hadzilacos and Goodman (1987) present the theory, the counterexample to the naive algorithm and the full algorithm in Chapter 8 of their book.

References

  1. Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 8, Replicated Data: the one-copy serializability theory (Sections 8.3 and 8.4), the atomicity of failures and recoveries (Section 8.5), the available copies algorithm with missing writes validation and access validation and its correctness, Theorem 8.7 (Section 8.6), the directory-oriented form (Section 8.7), communication failures (Section 8.8) and the virtual partition algorithm (Section 8.10)
  2. Philip A. Bernstein and Nathan Goodman, An algorithm for concurrency control and recovery in replicated distributed databases, ACM Transactions on Database Systems 9(4), 1984, pages 596 to 615, the available copies algorithm, its treatment of site failures and recoveries, and its correctness 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