Algorithm Search⌘K

Algorithmresearch

RAMP transactions

Also called read atomic multi-partition transactions, read atomic isolation.

Read atomic transactions over partitioned data: a reader sees all or none of the writes of each transaction, never waits for other clients, and needs at most two round trips.

Space
O(k) extra
Counts
messages 4k worstmessages 2k best
Where
k = the number of items that one transaction reads or writes
Properties
deterministiciterative
Origin
Peter Bailis, Alan Fekete, Ali Ghodsi, Joseph M. Hellerstein, Ion Stoica, 2014

RAMP transactions (read atomic multi-partition transactions) let a client write several items on different partitions so that other clients see either all of the new versions or none of them. This property is read atomic isolation. A writer first places its new versions on the partitions and only then marks them as committed. A reader first reads the last committed version of each item, and each version carries metadata about the other items that its transaction wrote. If the metadata shows that the reader got a version of one item but an older version of a sibling item, the reader fetches the missing version in a second round. No client ever waits for another client, and a crashed writer does not block anybody.

In plain words

Two users become friends. The application stores the friendship twice, once in the list of each user, and the two lists are on different servers. Another user must never see that Sam is a friend of Mary while Mary is not yet a friend of Sam.

With RAMP, the writer first puts the two new list entries on their servers, marked as not yet visible. When both servers have them, it tells both servers to make them visible. A reader may arrive when one server has made its entry visible and the other has not. The visible entry says "I was written together with an entry of the other list, at time 1", so the reader asks the other server for that exact entry. The server has it already, because the writer put it there before it made anything visible, so the server answers at once.

The problem

A database is split into partitions, and each item has one copy on one partition. Clients run two kinds of transactions: a write transaction PUT_ALL(W)(W) that writes a set WW of items, and a read transaction GET_ALL(I)(I) that reads a set II of items. The model is the asynchronous model: messages take any time and are not lost, and a client can fail by stopping (crash failure).

A read transaction has a fractured read if a transaction TT wrote versions of xx and yy, and the reader got the version of xx from TT but a version of yy older than the version from TT. A system gives read atomic isolation (RA) if no transaction has a fractured read and no transaction reads data that is not committed, aborted or intermediate.

The system must give RA with two scalability conditions. Synchronization independence: a transaction of one client never waits for a transaction of another client, so each client can always finish. Partition independence: a transaction contacts only the partitions of its own items.

RA is weaker than snapshot isolation and serializability. Two transactions can write the same item at the same time, and nothing stops another writer between a read of an item and a write of it. RA is the right level for writes that must be seen together, such as both halves of a two-way relation, an item and its entry in a secondary index, or a base table and a materialized view.

The algorithm

Each write transaction gets a unique timestamp, made from a client id and a sequence number of the client; no central server is needed. Each partition keeps all the versions it has received, and for each item the timestamp lastCommit[x]\mathrm{lastCommit}[x] of the newest committed version. This is a small form of multiversion concurrency control. RAMP-Fast (RAMP-F) stores with each version the set of the other items of its transaction.

  1. RAMP-FAST
  2. ▷ client: PUT_ALL(W), W is a set of (item, value)
  3. 1ts ← a new unique timestamp (sequence number, client id)
  4. 2for each (x, v) in W, in parallel: send PREPARE(x, v, ts, md = the other items of W) to the partition of x
  5. 3wait until every partition has answered PREPARED
  6. 4for each x in W, in parallel: send COMMIT(x, ts) to the partition of x
  7. ▷ client: GET_ALL(I), I is a set of items
  8. 5for each x in I, in parallel: ret[x] ← GET(x, none) from the partition of x
  9. 6for each y in I: v_latest[y] ← the largest ret[x].ts over the x in I with y in ret[x].md (⊥ if none)
  10. 7for each x in I with v_latest[x] > ret[x].ts, in parallel: ret[x] ← GET(x, v_latest[x])
  11. 8return the values of ret
  12. ▷ partition
  13. 9on PREPARE(x, v, ts, md): add the version (x, v, ts, md) to versions; answer PREPARED
  14. 10on COMMIT(x, ts): lastCommit[x] ← max(lastCommit[x], ts); answer COMMITTED
  15. 11on GET(x, ts_req): if ts_req is none, answer the version of x with timestamp lastCommit[x], else the version of x with timestamp ts_req

The key fact is that a partition makes a version visible (line L10) only after every partition of the transaction has the version (lines L3 and L9). So when a reader learns about a sibling version from metadata, the version is already on its partition, and the GET of line L7 returns it at once. The reader never asks for a version that is not there and never waits.

RAMP-Small (RAMP-S) stores no item sets, only the timestamp. The reader always does two rounds. In the first round it gets the timestamp lastCommit[x]\mathrm{lastCommit}[x] of each item. In the second round it sends the whole set SS of these timestamps to each partition, and the partition returns the version of xx with the largest timestamp in SS that it has for xx. Writes are the same as in RAMP-F.

RAMP-Hybrid (RAMP-H) stores a Bloom filter of the items of the transaction in place of the set. A reader asks in the second round for each item that the filter of a newer version may contain. A false positive asks for a version that does not exist, and the partition answers "none". With no false positives RAMP-H reads act like RAMP-F reads; with all false positives they act like RAMP-S reads.

Example

The test file builds this case. Items xx and yy are on partitions P0P_0 and P1P_1. Transaction T1T_1 with timestamp 1 writes x=11x = 11 and y=12y = 12. Both PREPARE messages have arrived (line L9), so both partitions have the versions. The COMMIT has reached P0P_0, so lastCommit[x]=1\mathrm{lastCommit}[x] = 1, but it has not reached P1P_1, where lastCommit[y]=⊥\mathrm{lastCommit}[y] = \bot. Then a client reads xx and yy.

step line what happens
1 L5 P0P_0 returns x=11x = 11, timestamp 1, metadata {y}\{y\}; P1P_1 returns y=0y = 0, timestamp ⊥\bot, no metadata
2 L6 vlatest[y]=1v_{\mathrm{latest}}[y] = 1, from the metadata of xx; vlatest[x]=⊥v_{\mathrm{latest}}[x] = \bot
3 L7 1>⊥1 > \bot, so the reader sends GET(y,1)(y, 1) to P1P_1
4 L11 P1P_1 has the prepared version of yy with timestamp 1 and returns y=12y = 12
5 L8 the reader returns x=11x = 11, y=12y = 12

The read takes 2 round trips and 6 messages, and lastCommit[y]\mathrm{lastCommit}[y] at P1P_1 is still ⊥\bot at the end. A reader that stops after one round returns x=11x = 11, y=0y = 0, which is a fractured read. RAMP-S also returns x=11x = 11, y=12y = 12: the set SS is {1,⊥}\{1, \bot\}, and P1P_1 has a version of yy at timestamp 1.

Correctness

The proof is in proofs/correctness.md. It follows the Appendix of Bailis et al. (2014) and is a theorem in the model of the page. The main steps are these.

  1. If a partition ever sets lastCommit[x]=t\mathrm{lastCommit}[x] = t, then every version of the transaction with timestamp tt is on its partition. This holds because COMMIT is sent only after all PREPARED answers.
  2. For RAMP-F, let the read return the timestamp f[x]=max⁡(ret[x].ts,vlatest[x])f[x] = \max(\mathrm{ret}[x].ts, v_{\mathrm{latest}}[x]) for each xx. If TT wrote xx at f[x]=tf[x] = t and also wrote y∈Iy \in I, then tt came from a first round version of some item of TT, whose metadata names yy (or which is yy itself), so f[y]≥tf[y] \ge t. That is exactly the absence of fractured reads.
  3. Every timestamp returned is a value of lastCommit\mathrm{lastCommit} or a sibling of one, so the transaction is committed. A writer that crashed before line L3 is never visible.
  4. For RAMP-S, the set SS contains tt, and by step 1 the partition of yy has a version at tt, so it returns a timestamp of at least tt for yy.
  5. Each GET finds its version at once by step 1, so no partition and no client waits for another client.

The tests check read atomicity in a simulation where messages arrive in a random order from a seeded generator. Each run has 2 to 4 write transactions of 2 or 3 items and 2 to 4 read transactions of 2 to 4 items, over 4 items on 3 partitions, and in half of the tests one writer crashes at a random step. Over 200 seeds per test (608 reads), RAMP-F and RAMP-S give no fractured read and no read of an uncommitted version, and every reader finishes in at most 2 rounds. The one round reader of the same runs has a fractured read in 90 of 200 runs without crashes and 77 of 200 with crashes (a measurement of this simulation).

Proof: RAMP-Fast and RAMP-Small reads are read atomic and never waitfull

We use the line numbers of the pseudocode on the page. The model is the model of the page and of the code: each item has one copy on one partition, clients send messages to partitions and partitions answer, messages arrive in any order and are not lost, and a writer client can crash at any moment and then sends nothing more. Timestamps are pairs (sequence number, client id), so two write transactions never have the same timestamp. The initial version of every item has the timestamp ⊥\bot, smaller than all others, and belongs to no write transaction.

We say that a write transaction TT with timestamp tt is committed when its client has passed line L3, that is, when it starts to send COMMIT messages. A version of xx with timestamp tt is a sibling of a version of yy with timestamp tt: both come from the same transaction.

Lemma 1 (siblings are present). If some partition has lastCommit[x]=t≠⊥\mathrm{lastCommit}[x] = t \ne \bot, or has ever had it, then TT is committed and every version that TT writes is in the set of versions of its partition.

Proof. A partition changes lastCommit[x]\mathrm{lastCommit}[x] only at line L10, when a COMMIT(x,t)(x, t) arrives. The client sends COMMIT only at line L4, after line L3 saw a PREPARED answer for each item of TT. A partition sends PREPARED only after line L9 has added the version. Versions are never removed (the code keeps them all). □\square

Lemma 2 (every request is answered at once). Each GET of line L5 or L7, and each second round GET of RAMP-S, finds the version it asks for, so the partition answers in the same step.

Proof. A GET of line L5 asks for lastCommit[x]\mathrm{lastCommit}[x], which is ⊥\bot (always present) or a version that line L9 added before. In RAMP-F, line L7 asks for xx at a timestamp t=vlatest[x]t = v_{\mathrm{latest}}[x]. This tt came from a version of some item zz that the reader got at line L5 from lastCommit[z]\mathrm{lastCommit}[z], and the metadata of that version names xx, so TT wrote xx. By Lemma 1 the version of xx at tt is present. In RAMP-S, the partition of xx looks for the largest timestamp of the set SS of first round timestamps that it has for xx. The timestamp that the reader got for xx itself is in SS and the partition has it, so the largest one exists. □\square

Theorem 1 (RAMP-F is read atomic). Let a RAMP-F read of the items II return the version of xx with timestamp f[x]f[x] for each x∈Ix \in I. If f[x]=t≠⊥f[x] = t \ne \bot and the transaction TT with timestamp tt also writes y∈Iy \in I, then f[y]≥tf[y] \ge t. Also TT is committed.

Proof. Let r[x]r[x] be the timestamp that line L5 returned for xx. After line L7, f[x]=max⁡(r[x],vlatest[x])f[x] = \max(r[x], v_{\mathrm{latest}}[x]), where vlatest[x]v_{\mathrm{latest}}[x] is the largest r[z]r[z] over the items z∈Iz \in I whose first round version names xx in its metadata (⊥\bot if there is none). The metadata of the version of zz at tt is the set of the other items of TT.

Case 1: f[x]=r[x]=tf[x] = r[x] = t. The first round version of xx has the metadata of TT, which contains yy. So line L6 gives vlatest[y]≥tv_{\mathrm{latest}}[y] \ge t and f[y]≥tf[y] \ge t.

Case 2: f[x]=vlatest[x]=t>r[x]f[x] = v_{\mathrm{latest}}[x] = t > r[x]. Then t=r[z]t = r[z] for an item z∈Iz \in I that TT wrote. If z=yz = y, then f[y]≥r[y]=tf[y] \ge r[y] = t. If z≠yz \ne y, the metadata of the version of zz at tt contains yy, so vlatest[y]≥tv_{\mathrm{latest}}[y] \ge t and f[y]≥tf[y] \ge t.

In both cases tt equals r[z]r[z] for some zz, and r[z]r[z] was a value of lastCommit[z]\mathrm{lastCommit}[z], so TT is committed by Lemma 1. ■\blacksquare

A read has a fractured read in the sense of Bailis et al. (2014, Section 3.1) if it returns a version of xx written by TT and a version of yy with a timestamp smaller than that of the version of yy that TT wrote. Theorem 1 says that this never happens, and that a read never returns a version of a transaction that is not committed. This is read atomic isolation. A writer that crashed before line L3 is never committed, and its prepared versions are never returned, because no lastCommit\mathrm{lastCommit} and no metadata of a committed version points to them.

Theorem 2 (RAMP-S is read atomic). The same statement holds for RAMP-S.

Proof. Let SS be the set of the first round timestamps, which are values of lastCommit\mathrm{lastCommit}. The second round returns for xx the largest t′∈St' \in S such that the partition of xx has a version of xx at t′t', so f[x]∈Sf[x] \in S. Let f[x]=t≠⊥f[x] = t \ne \bot and let TT also write y∈Iy \in I. Since t∈St \in S, tt was a value of lastCommit\mathrm{lastCommit} at some partition, and by Lemma 1 the version of yy at tt is present at the partition of yy. So tt is a candidate for yy, and f[y]≥tf[y] \ge t. Also TT is committed by Lemma 1. ■\blacksquare

Theorem 3 (no waiting, rounds and messages). Every operation finishes, whatever the other clients do and even if writers crash. Let a write have ww items and a read rr items, all on different partitions as in the code, which sends one message per item.

  1. A write takes 2 round trips and 4w4w messages.
  2. A RAMP-F read takes 1 or 2 round trips and 2r2r to 4r4r messages. It takes 1 round trip if, for each version that the first round returns, its transaction had committed at each of its other items y∈Iy \in I before the first round GET of yy was served. In particular, it takes 1 round trip when no write runs at the same time as the read.
  3. A RAMP-S read always takes 2 round trips and 4r4r messages.

Proof. A partition handles each message with local work only (lines L9 to L11, and Lemma 2), and answers in the same step. A client waits only for answers from partitions to its own requests, never for another client. Since messages are not lost, each request is answered. A writer sends ww PREPARE messages and gets ww answers (line L2), then ww COMMIT messages and ww answers (line L4). A reader sends rr GET messages and gets rr answers (line L5). RAMP-F sends at most rr more GET messages at line L7; RAMP-S always sends rr more.

For the condition in part 2: if line L6 gives vlatest[x]=tv_{\mathrm{latest}}[x] = t, then tt came from a first round version of an item z≠xz \ne x written by the transaction TT with timestamp tt, and TT also wrote xx. By the condition, TT had committed at xx before the first round GET of xx was served. Line L10 never makes lastCommit[x]\mathrm{lastCommit}[x] smaller, so r[x]≥tr[x] \ge t and line L7 does not ask for xx. ■\blacksquare

One round is not enough. A reader that returns the first round values (the "naive" mode of the code) is not read atomic. Let T1T_1 write xx and yy, and let the COMMIT of T1T_1 reach the partition of xx but not yet the partition of yy. A reader of xx and yy then gets xx from T1T_1 and the initial version of yy. The test file builds this case. RAMP-F sees yy in the metadata of xx and fetches yy at the timestamp of T1T_1 in a second round; RAMP-S fetches it because the timestamp of T1T_1 is in SS.

Complexity

Let kk be the number of items of a transaction, each on a different partition. In round trips and messages (a theorem, part 3 of the proof):

write read, best read, worst metadata per version
RAMP-F 2 round trips, 4k4k messages 1, 2k2k 2, 4k4k the other k−1k - 1 items
RAMP-S 2, 4k4k 2, 4k4k 2, 4k4k none
RAMP-H 2, 4k4k 1, 2k2k 2, 4k4k a Bloom filter

The paper sends one COMMIT per partition, not per item, so a write touches each partition twice. A RAMP-F read needs the second round only when it overlaps a write that has committed at some of its partitions and not yet at others. In the test runs, 128 of 608 RAMP-F reads needed a second round, and 105 of 608 in the runs with crashes; all 608 RAMP-S reads took two rounds (a measurement of this simulation, not of a real system). A RAMP-S second round GET carries the set SS, so its size grows with kk.

Partitions keep old versions until no reader can ask for them, so the space is more than one version per item while writes are in progress. The metadata of RAMP-F is O(k)O(k) items per version.

Bailis et al. measured RAMP on Amazon EC2 cr1.8xlarge instances with YCSB, 95% reads and transactions of 4 operations. The RAMP algorithms had a throughput typically within 8% of a baseline with no concurrency control and never more than 48% below it, and RAMP-F reached slightly under 7.1 million operations per second (1.79 million transactions per second) on 100 servers (a measurement, 2014, Sections 5.2 and 5.4).

Properties

  • RA isolation: no fractured reads, and no reads of data that is not committed (a theorem).
  • Synchronization independence: no client waits for another client, and a slow or crashed writer does not block readers or other writers.
  • Partition independence: a transaction contacts only the partitions of its items, and partitions never talk to each other.
  • No central timestamp server: a timestamp only names a version and orders the versions of one item.
  • Concurrent writers to the same item are not stopped. The version with the larger timestamp wins at each partition (line L10), as in last writer wins.

Variants and improvements

  • RAMP-S and RAMP-H trade metadata size for read round trips, as in the table above.
  • Faster commit detection: if a partition returns a version whose timestamp is above lastCommit\mathrm{lastCommit}, the transaction has committed at some partition, so this partition can mark the version as committed (Section 4.7 of the paper).
  • Cooperative termination: a client that crashes after some COMMIT messages leaves versions committed at some partitions and not at others. A partition that times out asks the other partitions of the transaction, and commits if one of them has committed (Section 4.6). This always finishes the transaction except when every partition has prepared and none has committed.
  • Garbage collection: a partition can remove an overwritten version when no reader will ask for it again. The simple rule is to limit the time a read can take and remove versions after a fixed window, 5 seconds in the experiments of the paper; a slower read is restarted (Sections 4.5 and 5.1).
  • Read-write transactions: a transaction that declares its read set first runs GET_ALL, buffers its writes and sends them with one PUT_ALL at the end. This is still RA, but it can lose concurrent updates (Section 4.5).
  • Replication: each partition can be replicated with any protocol that keeps operations on one item linearizable (Section 3.3).

When to use it

Use RAMP when writes to several partitions must become visible together and transactions do not need to stop concurrent updates of the same item. Typical cases are both directions of a relation, a row and its secondary index entries, and materialized views. Do not use RAMP when a transaction must check a condition and then write, such as "withdraw only if the balance stays positive"; RA allows two withdrawals to run at the same time. Such cases need serializability or a check that the invariant survives merges (invariant confluence).

Pitfalls

  • RA is not snapshot isolation. It does not order transactions against each other, and a read-write transaction built from GET_ALL and PUT_ALL can lose an update.
  • The timestamps must be unique across clients. Two writers with the same timestamp would mix their versions, and RAMP-H would return wrong versions for false positives.
  • If the commit of a crashed client is not finished by a termination protocol, its versions stay visible at some partitions and invisible at others. Readers stay correct, because they fetch the missing siblings, but they pay the second round forever.
  • The proofs need every version that a reader can learn about to stay on its partition until the reader asks. Garbage collection that is too fast breaks this.
  • A one round reader that just reads the last committed versions is not RA. The example above shows the fractured read.

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.

ramp_transactions.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ramp-transactions/. The authors are listed in prov/1YZCSM.jsonl.
"""RAMP-Fast and RAMP-Small read atomic multi-partition transactions.

A small simulation in one thread of the algorithms of Bailis, Fekete,
Hellerstein, Ghodsi and Stoica (SIGMOD 2014). Each key lives on one
partition. A writer prepares a new version of each key it writes, and only
when all partitions have acknowledged does it tell them to commit. A reader
first asks each partition for its last committed version, and then, if the
metadata shows that it missed a version of a sibling write, asks again for
that exact version.

Clients and partitions exchange messages through a network that delivers
them in an order chosen by a seeded random.Random. A writer can crash
after any step; a crashed writer sends nothing more. Every operation that
starts also finishes, because no step waits for another transaction.

mode = "fast"   RAMP-F: versions carry the set of sibling keys.
mode = "small"  RAMP-S: versions carry no metadata; a reader always asks
                again, with the set of timestamps it saw in the first round.
mode = "naive"  one round of reads of the last committed versions; this
                is not read atomic, and the tests show it.
"""

BOTTOM = (0, 0)      # the timestamp of the initial versions


class Partition:
    def __init__(self, keys):
        self.versions = {k: {BOTTOM: (0, frozenset())} for k in keys}   # key -> ts -> (value, md)
        self.last_commit = {k: BOTTOM for k in keys}

    def prepare(self, key, ts, value, md):
        self.versions[key][ts] = (value, md)                  # @line L9

    def commit(self, key, ts):
        if ts > self.last_commit[key]:                        # @line L10
            self.last_commit[key] = ts

    def get(self, key, ts_req):
        if ts_req is None:                                    # @line L11
            ts = self.last_commit[key]
        else:
            ts = ts_req
        value, md = self.versions[key][ts]
        return ts, value, md

    def get_small(self, key, ts_set):
        """RAMP-S second round: the version with the highest timestamp in
        ts_set that this partition has. The timestamp that the reader saw
        here in the first round is in ts_set, so there is one."""
        ts = max(t for t in self.versions[key] if t in ts_set)
        return ts, self.versions[key][ts][0], frozenset()


class Writer:
    def __init__(self, cid, seq, writes):
        self.cid = cid
        self.ts = (seq, cid)                                  # @line L1
        self.writes = dict(writes)
        self.state = "new"           # new, preparing, committing, done, crashed
        self.acks = set()
        self.rounds = 0


class Reader:
    def __init__(self, cid, keys):
        self.cid = cid
        self.keys = sorted(keys)
        self.state = "new"           # new, round1, round2, done
        self.ret = {}
        self.wait = set()
        self.rounds = 0


class RampDB:
    def __init__(self, placement, mode="fast"):
        """placement: {key: partition name}."""
        self.placement = dict(placement)
        self.mode = mode
        names = sorted(set(placement.values()))
        self.parts = {p: Partition([k for k in placement if placement[k] == p]) for p in names}
        self.clients = {}
        self.net = []                # (dst, payload); clients and partitions are named
        self.messages = 0
        self.log = []                # (event, ...) for the tests

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

    # ------------------------------------------------------------ writers
    def put_all(self, cid, seq, writes):
        if cid in self.clients and self.clients[cid].state == "crashed":
            return
        w = Writer(cid, seq, writes)
        self.clients[cid] = w
        w.state = "preparing"
        w.rounds = 1
        for k in sorted(w.writes):                            # @line L2
            md = frozenset(w.writes) - {k} if self.mode == "fast" else frozenset()
            self.send(self.placement[k], ("prepare", cid, k, w.ts, w.writes[k], md))

    def on_prepared(self, w, key):
        if w.state != "preparing":
            return
        w.acks.add(key)
        if w.acks == set(w.writes):                           # @line L3
            w.state = "committing"
            w.rounds = 2
            self.log.append(("commit", w.ts, tuple(sorted(w.writes))))
            w.acks = set()
            for k in sorted(w.writes):                        # @line L4
                self.send(self.placement[k], ("commit", w.cid, k, w.ts))

    def on_committed(self, w, key):
        if w.state != "committing":
            return
        w.acks.add(key)
        if w.acks == set(w.writes):
            w.state = "done"

    def crash(self, cid):
        if cid not in self.clients:          # it crashes before it starts
            self.clients[cid] = Writer(cid, 0, {})
        c = self.clients[cid]
        if c.state != "done":
            c.state = "crashed"
        self.net = [m for m in self.net if not (m[0] == cid)]

    # ------------------------------------------------------------ readers
    def get_all(self, cid, keys):
        r = Reader(cid, keys)
        self.clients[cid] = r
        r.state = "round1"
        r.rounds = 1
        r.wait = set(r.keys)
        for k in r.keys:                                      # @line L5
            self.send(self.placement[k], ("get", cid, k, None))

    def on_value(self, r, key, ts, value, md):
        r.ret[key] = (ts, value, md)
        r.wait.discard(key)
        if r.wait:
            return
        if r.state == "round1" and self.mode == "fast":
            v_latest = {}
            for k in r.keys:                                  # @line L6
                ts_k, _, md_k = r.ret[k]
                for y in md_k:
                    if y in r.ret and ts_k > v_latest.get(y, BOTTOM):
                        v_latest[y] = ts_k
            need = [k for k in r.keys if v_latest.get(k, BOTTOM) > r.ret[k][0]]
            if need:
                r.state, r.rounds, r.wait = "round2", 2, set(need)
                for k in need:                                # @line L7
                    self.send(self.placement[k], ("get", r.cid, k, v_latest[k]))
                return
        elif r.state == "round1" and self.mode == "small":
            ts_set = frozenset(r.ret[k][0] for k in r.keys)
            r.state, r.rounds, r.wait = "round2", 2, set(r.keys)
            for k in r.keys:
                self.send(self.placement[k], ("get_small", r.cid, k, ts_set))
            return
        r.state = "done"                                      # @line L8
        self.log.append(("read", r.cid, {k: r.ret[k][0] for k in r.keys}))

    # ------------------------------------------------------------ network
    def deliver(self, k):
        dst, payload = self.net.pop(k)
        kind, cid = payload[0], payload[1]
        if dst in self.parts:
            part = self.parts[dst]
            if kind == "prepare":
                _, _, key, ts, value, md = payload
                part.prepare(key, ts, value, md)
                self.send(cid, ("prepared", key))
            elif kind == "commit":
                _, _, key, ts = payload
                part.commit(key, ts)
                self.send(cid, ("committed", key))
            elif kind == "get":
                _, _, key, ts_req = payload
                self.send(cid, ("value", key) + part.get(key, ts_req))
            else:
                _, _, key, ts_set = payload
                self.send(cid, ("value", key) + part.get_small(key, ts_set))
            return
        c = self.clients[dst]
        if c.state == "crashed":
            return
        if kind == "prepared":
            self.on_prepared(c, payload[1])
        elif kind == "committed":
            self.on_committed(c, payload[1])
        else:
            self.on_value(c, *payload[1:])

    def run(self, rng, ops, crash_at=()):
        """ops: [(step, "w", cid, seq, writes) or (step, "r", cid, keys)].
        crash_at: [(step, cid)]. Delivers until no message is left."""
        events = sorted([(o[0], 0, o) for o in ops] + [(s, 1, ("crash", c)) for s, c in crash_at],
                        key=lambda e: (e[0], e[1], str(e[2])))
        step = 0
        while events or self.net:
            while events and events[0][0] <= step:
                _, _, o = events.pop(0)
                if o[0] == "crash":
                    self.crash(o[1])
                elif o[1] == "w":
                    self.put_all(o[2], o[3], o[4])
                else:
                    self.get_all(o[2], o[3])
            if self.net:
                self.deliver(rng.randrange(len(self.net)))
            step += 1
test_ramp_transactions.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ramp-transactions/. The authors are listed in prov/1YZCSM.jsonl.
import random
import unittest

from ramp_transactions import BOTTOM, RampDB

PLACEMENT = {"x": "P0", "y": "P1", "z": "P2", "w": "P0"}
KEYS = sorted(PLACEMENT)


def fractured(db):
    """The reads that break read atomicity (Bailis et al. 2014, Section 3.1):
    a reader sees the write of T to one key and an older version of another
    key that T also wrote. Also the reads of a version whose writer never
    finished its prepare round."""
    writes = {ts: set(keys) for ev, ts, keys in db.log if ev == "commit"}
    bad = []
    for ev, cid, got in db.log:
        if ev != "read":
            continue
        for x, t in got.items():
            if t == BOTTOM:
                continue
            if t not in writes:
                bad.append((cid, "uncommitted", x, t))
                continue
            for y in writes[t] & set(got):
                if got[y] < t:
                    bad.append((cid, "fractured", x, y, t, got[y]))
    return bad


def workload(rng, crash=False):
    ops, cid = [], 1
    for seq in range(1, rng.randint(2, 4) + 1):
        keys = rng.sample(KEYS, rng.randint(2, 3))
        ops.append((rng.randrange(12), "w", cid, seq, {k: 10 * seq + i for i, k in enumerate(keys)}))
        cid += 1
    for _ in range(rng.randint(2, 4)):
        ops.append((rng.randrange(16), "r", cid, rng.sample(KEYS, rng.randint(2, 4))))
        cid += 1
    crashes = []
    if crash:
        writers = [o[2] for o in ops if o[1] == "w"]
        crashes = [(rng.randrange(20), rng.choice(writers))]
    return ops, crashes


class TestRamp(unittest.TestCase):
    def check(self, mode, crash):
        reads = 0
        for seed in range(200):
            rng = random.Random(seed)
            db = RampDB(PLACEMENT, mode)
            ops, crashes = workload(rng, crash)
            db.run(rng, ops, crashes)
            self.assertEqual(fractured(db), [], (mode, seed))
            for c in db.clients.values():
                if hasattr(c, "keys"):
                    self.assertEqual(c.state, "done")              # no reader blocks
                    self.assertLessEqual(c.rounds, 2)
                    reads += 1
        self.assertGreater(reads, 400)

    def test_fast_is_read_atomic(self):
        self.check("fast", crash=False)

    def test_fast_with_writer_crashes(self):
        self.check("fast", crash=True)

    def test_small_is_read_atomic(self):
        self.check("small", crash=False)

    def test_small_with_writer_crashes(self):
        self.check("small", crash=True)

    def test_one_round_reads_are_not_atomic(self):
        bad = 0
        for seed in range(200):
            rng = random.Random(seed)
            db = RampDB(PLACEMENT, "naive")
            ops, crashes = workload(rng)
            db.run(rng, ops, crashes)
            bad += bool(fractured(db))
        self.assertGreater(bad, 0)

    def race(self, mode):
        """T1 writes x and y. The commit has reached x only when T1 crashes;
        then client 2 reads x and y."""
        db = RampDB(PLACEMENT, mode)
        db.put_all(1, 1, {"x": 11, "y": 12})
        while db.net:
            db.deliver(0)
            if db.clients[1].state == "committing":
                break
        k = next(i for i, m in enumerate(db.net) if m[1][0] == "commit" and m[1][2] == "x")
        db.deliver(k)
        db.crash(1)
        db.net = [m for m in db.net if m[1][0] != "commit"]   # the commit to y is lost with T1
        before = db.messages
        db.get_all(2, ["x", "y"])
        while db.net:
            db.deliver(0)
        return db, db.messages - before

    def test_second_round_repairs_a_race(self):
        db, msgs = self.race("fast")
        r = db.clients[2]
        self.assertEqual({k: r.ret[k][1] for k in r.ret}, {"x": 11, "y": 12})
        self.assertEqual((r.rounds, msgs), (2, 6))
        self.assertEqual(db.parts["P1"].last_commit["y"], BOTTOM)   # y is still not committed
        db, msgs = self.race("small")
        self.assertEqual({k: v[1] for k, v in db.clients[2].ret.items()}, {"x": 11, "y": 12})
        db, msgs = self.race("naive")
        self.assertEqual({k: v[1] for k, v in db.clients[2].ret.items()}, {"x": 11, "y": 0})
        self.assertTrue(fractured(db))

    def test_round_trips(self):
        # With no concurrent writer, RAMP-F reads in one round trip and
        # RAMP-S in two. A write takes two round trips in both.
        for mode, rounds in (("fast", 1), ("small", 2)):
            db = RampDB(PLACEMENT, mode)
            db.run(random.Random(0), [(0, "w", 1, 1, {"x": 11, "y": 12, "z": 13})])
            self.assertEqual((db.clients[1].rounds, db.messages), (2, 12))
            before = db.messages
            db.run(random.Random(0), [(0, "r", 2, ["x", "y", "z", "w"])])
            self.assertEqual(db.clients[2].rounds, rounds)
            self.assertEqual(db.messages - before, 8 * rounds)
            self.assertEqual({k: v[1] for k, v in db.clients[2].ret.items()},
                             {"x": 11, "y": 12, "z": 13, "w": 0})

    def test_metadata_size(self):
        # RAMP-F stores the other keys of the write set with each version,
        # RAMP-S nothing.
        for mode, size in (("fast", 2), ("small", 0)):
            db = RampDB(PLACEMENT, mode)
            db.run(random.Random(0), [(0, "w", 1, 1, {"x": 1, "y": 2, "z": 3})])
            self.assertEqual(len(db.parts["P0"].versions["x"][(1, 1)][1]), size)


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

History

Bailis, Fekete, Ghodsi, Hellerstein and Stoica introduced RA isolation and RAMP transactions at SIGMOD 2014. They wanted multi-partition updates for systems such as Facebook TAO, LinkedIn Espresso and Yahoo PNUTS, which often gave up transactions across partitions because locking and two-phase commit block under failures and contention. The paper compares RA with the isolation levels of Adya: it is stronger than read committed and weaker than snapshot isolation. RA allows concurrent updates and so stays within what highly available transactions can give, which the same group studied in earlier work.

References

  1. Peter Bailis, Alan Fekete, Ali Ghodsi, Joseph M. Hellerstein and Ion Stoica, Scalable atomic visibility with RAMP transactions, SIGMOD 2014, pages 27 to 38, Section 3.1 (fractured reads and read atomic isolation), Section 3.3 (synchronization and partition independence), Algorithms 1 to 3 and Table 1 in Section 4, Section 5.4 (scale out), and the Appendix (Claims 1 to 6 and Invariant 1)

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.best
  • 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