Algorithm Search⌘K

Algorithmresearch

Calvin deterministic transaction protocol

Also called Calvin, deterministic database.

Agree on a global order of transaction inputs first, then execute them deterministically at every replica, so no two-phase commit is needed.

Space
O(p) extra
Counts
messages p(p - 1) worst
Where
p = the number of partitions that one transaction touches
Properties
deterministiciterative
Origin
Alexander Thomson, Thaddeus Diamond, Shu Chun Weng, Kun Ren, Philip Shao, Daniel J. Abadi, 2012

Calvin is a transaction layer for a partitioned and replicated database. It first puts the inputs of all transactions in one global order and replicates this order, and only then executes the transactions. Every replica executes them so that the result is the same as running them one at a time in that order. Execution is deterministic, so two replicas that get the same input reach the same state without talking to each other. A node failure therefore does not force a transaction to abort, and Calvin needs no two-phase commit at the end of a distributed transaction. The cost is that each transaction must declare its read and write sets before it runs.

In plain words

Several kitchens cook the same menu for the same list of orders. Each morning a clerk writes all the orders of the last few minutes in one numbered list and gives a copy to every kitchen. Each kitchen cooks the orders strictly in list order wherever two orders need the same pan, and in parallel where they do not. Since every kitchen follows the same list and the same recipes, all kitchens produce the same dishes. If one kitchen burns down, the others still have everything, and a new kitchen can catch up by cooking the list again from the start.

The kitchens never need to agree on anything at the end of a dish. All the agreement happened once, when the clerk wrote the list.

The problem

A database is split into partitions on a cluster of shared-nothing nodes, and each partition is replicated. Transactions can touch several partitions. The system must give serializability at each replica, keep the replicas consistent with each other (one-copy serializability), and scale with the number of nodes.

The usual design runs two-phase locking and then two-phase commit. A distributed transaction then holds its locks during several network round trips of the commit protocol, and this time, the contention footprint, limits the throughput on hot items. Two-phase commit exists because a node may fail or the transaction logic may decide to abort, and the nodes must agree on the outcome.

The model of the page is the asynchronous model inside a replica: messages take any time and are not lost while the replica is up. Nodes fail by stopping (crash failure). Agreement on the input is done by a consensus protocol such as Paxos, which is outside the scope of the page.

The algorithm

Calvin has three layers on every node: a sequencer, a scheduler with a lock manager and worker threads, and a storage engine with a simple read and write interface.

  1. CALVIN
  2. ▷ sequencer at partition p, for each epoch e (10 ms in Calvin)
  3. 1collect the transaction requests that clients send to p during epoch e into batch(e, p)
  4. 2replicate batch(e, p) (Paxos or a master replica), then send it to the scheduler of every partition in each replica
  5. ▷ scheduler at partition q, its lock thread
  6. 3wait until batch(e, p) has arrived from every sequencer p; the order of epoch e is batch(e, 1), batch(e, 2), ...
  7. 4for each transaction T in this global order: request all locks of T on the items of q, at once
  8. 5grant the locks on each item strictly in the order of the requests
  9. ▷ scheduler at partition q, a worker for T, when T holds all its locks at q
  10. 6read the items of the read set of T that are stored at q
  11. 7send these values to every active participant of T (a partition with an item of the write set of T)
  12. 8if q is not an active participant then release the locks of T at q and stop
  13. 9wait until the values from every partition of the read set of T have arrived
  14. 10run the logic of T on these values; every active participant computes the same writes or the same abort
  15. 11apply the writes to the items stored at q and release the locks of T at q

Lines L4 and L5 are a form of conservative two-phase locking with one extra rule: the locks are requested in the global order by one thread, and granted in request order. This makes the order of conflicting transactions equal to the global order at every partition and every replica. It also prevents deadlock, because a transaction waits only for transactions that come before it in the global order.

There is no commit protocol. A transaction that aborts because of its own logic, for example because a stock level would fall below zero, aborts at every active participant, because each of them runs the same logic on the same values. A transaction does not abort because a node fails: another replica has done the same work and has the same state.

Dependent transactions and OLLP. A transaction whose read or write set depends on data, such as an update through a secondary index, cannot declare its sets in advance. Calvin uses optimistic lock location prediction (OLLP). The client first runs a cheap reconnaissance query, with no locks and no replication, which reads the index and predicts the sets. It then sends the real transaction with these sets. At execution the transaction checks the index values again, and if they changed it restarts in the same deterministic way at every replica, and the client sends it again.

The code on this page is a toy. It runs all nodes in one thread, delivers messages in an order chosen by a seeded random generator, and gives the agreed input log to every replica in place of Paxos. It has no storage engine, no disk, no checkpoints and no worker threads. It keeps exactly the parts that make the protocol correct: epochs, the global order, the lock manager, the phases of lines L6 to L11, deterministic aborts, OLLP restarts and replay after a crash.

Example

Item aa is on partition P0P_0 and item bb on P1P_1, with a=30a = 30 and b=0b = 0. In epoch 0, sequencer 0 gets T1T_1: "if a≥10a \ge 10, move 10 from aa to bb, else abort", and sequencer 1 gets T2T_2: "set aa to bb". The global order is T1,T2T_1, T_2.

step where what happens
1 L4 at P0P_0 queue of aa: T1T_1 (X), T2T_2 (X)
2 L4 at P1P_1 queue of bb: T1T_1 (X), T2T_2 (S)
3 L6, L7 T1T_1 holds its locks at both partitions; P0P_0 sends a=30a = 30 to P1P_1 and P1P_1 sends b=0b = 0 to P0P_0
4 L10, L11 both partitions compute a=20a = 20, b=10b = 10, apply their own write and release
5 L6 to L8 at P1P_1 T2T_2 gets its S lock on bb, reads b=10b = 10, sends it to P0P_0, and releases, since P1P_1 is not an active participant of T2T_2
6 L9 to L11 at P0P_0 T2T_2 gets its X lock on aa after T1T_1, waits for bb, sets a=10a = 10

The result a=10a = 10, b=10b = 10 is the result of T1T_1 and then T2T_2, and it is the same in every replica whatever the message delays. T1T_1 sends 2 messages and T2T_2 sends 1, and nobody sends a commit message. If T2T_2 had been first in the log, every replica would compute a=0a = 0 and then abort T1T_1.

Correctness

The proof is in proofs/correctness.md. It is a theorem in the model of the page, given that every replica gets the same input log.

  1. Every scheduler sees the transactions in the same global order (line L3).
  2. At each item the lock queue follows the global order, and a lock is granted only when all earlier conflicting locks are released (lines L4 and L5).
  3. By induction on the global order, every transaction finishes: it waits only for earlier transactions, so there is no deadlock.
  4. By the same induction, each read sees the value written by the last earlier writer of the item. So every transaction reads the serial values, decides the same way as in the serial execution, and writes the same values. The final state equals the state after a serial execution in log order.
  5. Replicas apply the same log, so they reach the same state. A replica rebuilt by replaying the log reaches it too.

The tests check this against a brute force oracle that runs the transactions one at a time in log order. In 300 random runs with 3 to 6 transactions over 6 items on 3 partitions and 2 replicas, every replica has the oracle's final state and every transaction read the oracle's values; 88 of the 1342 transactions aborted by their logic. With a lock manager that grants every request, 273 of the 300 runs differ from the oracle, so the test is sensitive to the lock order. In 150 runs where one replica crashes, the other replica finishes without waiting, and the crashed replica, which was behind in 142 runs, reaches the same state after it replays the log.

Proof: Every Calvin replica executes the input log as if the transactions ran one at a time in log orderfull

We use the line numbers of the pseudocode on the page. The model is the model of the page and of the toy code. Each replica has one scheduler for each partition, and each item lives on one partition. A transaction TT declares its read set R(T)R(T) and write set W(T)W(T), and its logic is a deterministic function of the values of R(T)R(T); it returns new values for some items of W(T)W(T), or an abort. Messages inside a replica arrive in any order and are not lost while the replica is up. The input log, the batch of each sequencer for each epoch, is the same for every replica (in Calvin, Paxos agrees on it; the proof takes it as given).

The global order is the order of the log: epoch by epoch, and inside an epoch the batch of sequencer 1, then the batch of sequencer 2, and so on, each batch in its own order. Write it T1,T2,…T_1, T_2, \dots. The active participants of TT are the partitions that hold an item of W(T)W(T) (of R(T)R(T) if W(T)W(T) is empty). The serial execution runs T1,T2,…T_1, T_2, \dots one at a time on the initial state.

Lemma 1 (the same order everywhere). At every scheduler, line L4 handles the transactions that touch its partition in the global order.

Proof. Line L3 starts epoch ee only when the batch of every sequencer for ee has arrived, and it takes the batches in sequencer order. It finishes epoch ee before it starts e+1e + 1. Messages can arrive in any order, but the batches are buffered until line L3 uses them. □\square

Lemma 2 (the lock queues). At each item kk, the lock queue holds the transactions that access kk in the global order. An entry of TiT_i is granted only when every earlier entry that conflicts with it (one of the two is an X lock) has left the queue.

Proof. Line L4 adds all locks of a transaction at once, in the order of Lemma 1. Line L5 grants an entry only if every entry in front of it is compatible with it. An entry leaves the queue only when its transaction releases its locks at that partition. □\square

Lemma 3 (progress). If the replica stays up, every transaction finishes at every partition it touches, and no transaction waits for a later one.

Proof. By induction on ii. Suppose T1,…,Ti−1T_1, \dots, T_{i-1} finish everywhere. At each partition qq of TiT_i, every entry in front of the entries of TiT_i belongs to an earlier transaction (Lemma 2), so it leaves the queue, and TiT_i gets all its local locks. Entries behind it never block it. So every partition of TiT_i reaches line L6 and sends its local reads to the active participants (line L7). A partition that is not an active participant releases at once (line L8). Each active participant gets the reads of every partition of R(Ti)R(T_i), since messages are not lost, and finishes at lines L9 to L11. □\square

Lemma 3 shows that the toy has no deadlock: every wait is for an earlier transaction in the global order, so the waits cannot form a cycle.

Theorem 1 (serial equivalence). At every replica that stays up, each transaction TiT_i reads the same values as in the serial execution, makes the same decision (commit with the same writes, or abort), and the final state equals the final state of the serial execution.

Proof. By induction on ii we show that when a partition qq reads an item k∈R(Ti)k \in R(T_i) at line L6, the value of kk is its value after T1,…,Ti−1T_1, \dots, T_{i-1} in the serial execution, and that TiT_i writes the same values as in the serial execution.

Let TjT_j with j<ij < i write kk. Its X entry on kk is in front of the entry of TiT_i and conflicts with it, so by Lemma 2 TiT_i reads kk only after TjT_j has released its lock at qq. The partition qq holds k∈W(Tj)k \in W(T_j), so it is an active participant of TjT_j, and it releases the lock only after line L11 has stored the writes of TjT_j. Let TmT_m with m>im > i write kk. Its X entry is behind the entry of TiT_i, so it is granted only after TiT_i releases its lock at qq, and qq does this after line L6 (at line L8 or after line L11). So when TiT_i reads kk, every earlier writer of kk has stored its value and no later writer has. The writers of kk also store their values in the global order, by the same argument. By the induction hypothesis each earlier writer stored its serial value, so TiT_i reads the serial value of kk.

Each active participant of TiT_i runs the logic (line L10) on the values from every partition of R(Ti)R(T_i), that is, on the serial values of all of R(Ti)R(T_i). The logic is deterministic, so each of them computes the serial decision and the serial writes, and each stores the writes to its own items (line L11). This finishes the induction. By Lemma 3 every transaction finishes, and the last writer of each item in the global order stores the last value, as in the serial execution. ■\blacksquare

Consequences. Two replicas that apply the same log reach the same state, with no message between them; this is why Calvin needs no two-phase commit. An abort caused by the logic is decided by every active participant from the same values, so no vote is needed. A replica that crashed is rebuilt by running the log again from the initial state (or from a checkpoint taken at a point of the global order). The rebuilt replica satisfies Theorem 1, so it reaches the same state as the others. A replica that is down does not stop the others, because no step of one replica waits for a message from another replica.

OLLP. A dependent transaction runs first a reconnaissance read with no locks, and declares the read and write sets that this read predicts. Its logic reads the items that the prediction used again, and returns RESTART if they changed. RESTART is a deterministic decision with no writes, so Theorem 1 holds for the log that contains the failed attempt, and every replica decides the same restart. The client then sends a new attempt, which is a new transaction in a later position of the log.

Theorem 2 (messages). In each replica, a transaction sends ∑s∣A(T)∖{s}∣\sum_{s} |A(T) \setminus \{s\}| messages in phase 3, over the partitions ss of R(T)R(T), where A(T)A(T) is the set of active participants. If TT touches pp partitions, this is at most p(p−1)p(p - 1). There is no commit message. Each sequencer sends one batch message per epoch to each scheduler of each replica.

Proof. Each partition of R(T)R(T) sends one message at line L7 to each active participant other than itself, and nothing else is sent for TT. With a=∣R(T)∣a = |R(T)| partitions of reads, b=∣A(T)∣b = |A(T)| active participants and cc partitions in both sets, the count is ab−cab - c and a+b−c≤pa + b - c \le p. For a fixed cc the product is largest when a=b=(p+c)/2a = b = (p + c)/2, which gives (p+c)2/4−c(p + c)^2/4 - c. This grows with cc for p+c≥2p + c \ge 2, so the largest value is at c=pc = p, that is, p2−pp^2 - p. ■\blacksquare

Complexity

For a transaction that touches pp partitions, phase 3 sends one message from each partition with reads to each other active participant, at most p(p−1)p(p - 1) messages per replica, and there is no commit round (a theorem, in the proof). Each sequencer also sends one batch message per epoch to each scheduler. The latency of a transaction includes the wait for the end of its epoch and the replication of the batch.

The lock manager holds the locks of a transaction from line L4 until the transaction finishes at that partition, but a transaction holds no lock while the batch is replicated, so slow replication across data centers adds latency but not contention.

Thomson et al. measured Calvin on Amazon EC2 High-CPU Extra-Large instances (7 GB of memory, 8 virtual cores) with a TPC-C workload of New Order transactions only, 10 warehouses per partition and about 10% of transactions on two partitions. Calvin ran about 5000 transactions per second per node on clusters of more than 10 nodes, and nearly half a million transactions per second on 100 nodes (a measurement, 2012, Section 6.1). They also report that the throughput did not change when they replicated the input with Paxos across three data centers, while the latency grew (Section 3.1.1).

Properties

  • Serializable, and equivalent to the serial order of the log, at every replica (a theorem).
  • Deterministic: the state of a replica depends only on the input log.
  • No two-phase commit, no deadlock, and no abort because of a node failure.
  • Logging is logical: only the input is logged, and recovery replays it from a checkpoint.
  • Read and write sets must be known before execution; dependent transactions need OLLP.
  • A slow node delays every later transaction that conflicts with its transactions, because nobody can skip ahead in the global order.

Variants and improvements

  • Replication of the input: asynchronous, with a master replica that forwards batches, or synchronous with Paxos among the replicas of a partition. The Calvin implementation used ZooKeeper for this.
  • Disk-based storage: when a sequencer gets a transaction that may wait for the disk, it delays the transaction before it enters the scheduling layer and asks the storage to bring the records into memory, so that the transaction does not hold locks during a disk read (Section 4).
  • Checkpointing: a naive mode that freezes one replica, an asynchronous variant of the Zig-Zag algorithm of Cao et al., and a snapshot mode when the storage keeps multiple versions (Section 5).

When to use it

Calvin fits workloads with many short distributed transactions on hot items, where the time locks are held during two-phase commit limits throughput, and where read and write sets are known or cheap to predict. It fits less well when transactions are interactive, when the read set depends on many reads, or when latency must be below the epoch length plus the time to replicate a batch.

Pitfalls

  • The transaction logic must be deterministic. A call to a clock, a random number generator or an external service gives different results at different replicas.
  • The order of epochs is the commit order, so a client sees a delay of at least one epoch (10 ms in Calvin) plus replication.
  • An OLLP prediction that is often wrong causes repeated restarts. Calvin expects this to be rare because indexes on fields that change often are rare.
  • Every replica must apply exactly the same log. A replica that misses or reorders one batch diverges silently.

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.

calvin_deterministic_transactions.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/calvin-deterministic-transactions/. The authors are listed in prov/AX20CH.jsonl.
"""A toy model of Calvin (Thomson et al., SIGMOD 2012) in one thread.

This is not a database. It keeps only the parts of Calvin that make the
protocol correct: sequencers that cut the input into epochs, a global order
of the batches, a scheduler per partition that requests all locks of each
transaction in that order and grants them in request order, and the five
phases of execution, in which partitions send their local reads to the
active participants and every active participant runs the same logic.

Each replica holds every partition. The input log is the same for all
replicas; in Calvin, Paxos agrees on each batch, and here the batch is given
to everyone. Messages between nodes are delivered in an order chosen by a
seeded random.Random. A whole replica can crash and later rebuild its state
by replaying the input log.

A transaction declares its read set and write set, and its logic is a
function of the values it reads. The logic returns a dict of writes, None
for a deterministic abort, or RESTART when an OLLP prediction of the read
and write sets was wrong.
"""

RESTART = "restart"


class Txn:
    def __init__(self, tid, reads, writes, logic):
        self.tid = tid
        self.reads = frozenset(reads)
        self.writes = frozenset(writes)
        self.logic = logic


def run_logic(t, vals):
    out = t.logic(dict(vals))
    if isinstance(out, dict):
        assert set(out) <= t.writes, (t.tid, out)
        return "commit", out
    return ("abort" if out is None else RESTART), {}


class Scheduler:
    """The scheduler, lock manager and workers of one partition of one replica."""

    def __init__(self, db, replica, part, store):
        self.db, self.r, self.q = db, replica, part
        self.store = dict(store)
        self.batches = {}            # (epoch, sequencer) -> transactions that touch this partition
        self.next_epoch = 0
        self.locks = {}              # key -> [(tid, mode)] in request order
        self.txn = {}                # tid -> (txn, local keys)
        self.order = []              # tids in global order
        self.started = set()
        self.reads = {}              # tid -> ({key: value}, set of partitions that sent)
        self.finished = set()
        self.results = {}            # tid -> (outcome, values read), at active participants
        self.down = False

    # ------------------------------------------------------- lock thread
    def on_batch(self, e, p, txns):
        self.batches[(e, p)] = txns
        n = self.db.nparts
        while all((self.next_epoch, s) in self.batches for s in range(n)):     # @line L3
            for s in range(n):
                for t in self.batches.pop((self.next_epoch, s)):
                    self.lock_all(t)
            self.next_epoch += 1
        self.work()

    def lock_all(self, t):
        keys = sorted(k for k in t.reads | t.writes if self.db.place[k] == self.q)
        self.txn[t.tid] = (t, keys)
        self.order.append(t.tid)
        for k in keys:                                                        # @line L4
            self.locks.setdefault(k, []).append((t.tid, "X" if k in t.writes else "S"))

    def granted(self, tid, k):
        queue = self.locks[k]
        mine = next(m for o, m in queue if o == tid)
        for other, mode in queue:                                             # @line L5
            if other == tid:
                return True
            if mode == "X" or mine == "X":
                return False

    def release(self, tid):
        _, keys = self.txn[tid]
        for k in keys:
            self.locks[k] = [e for e in self.locks[k] if e[0] != tid]
        self.finished.add(tid)

    # ----------------------------------------------------------- workers
    def work(self):
        changed = True
        while changed:
            changed = False
            for tid in self.order:
                if tid in self.finished:
                    continue
                t, keys = self.txn[tid]
                if tid not in self.started and all(self.granted(tid, k) for k in keys):
                    self.start(t, keys)
                    changed = True
                elif tid in self.started and self.q in self.db.active(t):
                    vals, senders = self.reads.get(tid, ({}, set()))
                    if senders >= self.db.read_parts(t):                      # @line L9
                        self.finish(t, vals)
                        changed = True

    def start(self, t, keys):
        self.started.add(t.tid)
        if self.q in self.db.read_parts(t):
            vals = {k: self.store[k] for k in keys if k in t.reads}           # @line L6
            for a in sorted(self.db.active(t)):                               # @line L7
                if a == self.q:
                    self.on_reads(t.tid, self.q, vals)
                else:
                    self.db.send((self.r, a), ("reads", t.tid, self.q, vals), True)
        if self.q not in self.db.active(t):                                   # @line L8
            self.release(t.tid)

    def on_reads(self, tid, sender, vals):
        got, senders = self.reads.setdefault(tid, ({}, set()))
        got.update(vals)
        senders.add(sender)

    def finish(self, t, vals):
        outcome, writes = run_logic(t, vals)                                  # @line L10
        for k, v in writes.items():                                           # @line L11
            if self.db.place[k] == self.q:
                self.store[k] = v
        self.results[t.tid] = (outcome, dict(vals))
        self.release(t.tid)
        if outcome == RESTART and self.r == 0 and self.q == min(self.db.active(t)):
            self.db.restart(t.tid)


class Calvin:
    def __init__(self, place, replicas=2, init=None):
        """place: {key: partition number}. init: {key: value}, default 0."""
        self.place = dict(place)
        self.nparts = max(place.values()) + 1
        self.replicas = replicas
        self.init = {k: 0 for k in place}
        self.init.update(init or {})
        self.sched = {(r, q): self.new_scheduler(r, q) for r in range(replicas) for q in range(self.nparts)}
        self.net = []
        self.read_messages = 0       # messages of phase 3, between partitions
        self.batch_messages = 0      # messages from sequencers to schedulers
        self.log = {}                # (epoch, sequencer) -> the agreed batch
        self.pending = {}            # sequencer -> requests of the open epoch
        self.epoch = 0
        self.recon = {}              # tid -> function(read) -> new Txn, for OLLP
        self.next_tid = 1000

    def new_scheduler(self, r, q):
        return Scheduler(self, r, q, {k: v for k, v in self.init.items() if self.place[k] == q})

    def parts(self, t):
        return {self.place[k] for k in t.reads | t.writes}

    def read_parts(self, t):
        return {self.place[k] for k in t.reads}

    def active(self, t):
        return {self.place[k] for k in (t.writes or t.reads)}

    def send(self, dst, payload, read=False):
        if read:
            self.read_messages += 1
        else:
            self.batch_messages += 1
        self.net.append((dst, payload))

    # --------------------------------------------------------- sequencers
    def submit(self, p, t):
        self.pending.setdefault(p, []).append(t)                              # @line L1

    def end_epoch(self):
        e = self.epoch
        for p in range(self.nparts):
            batch = self.pending.pop(p, [])
            self.log[(e, p)] = batch                                          # @line L2
            for (r, q) in sorted(self.sched):
                self.send((r, q), ("batch", e, p, [t for t in batch if q in self.parts(t)]))
        self.epoch += 1

    def global_order(self):
        return [t for key in sorted(self.log) for t in self.log[key]]

    # --------------------------------------------------------------- OLLP
    def read_no_lock(self, k):
        """A reconnaissance read: no locks, from replica 0."""
        return self.sched[(0, self.place[k])].store[k]

    def restart(self, tid):
        make = self.recon[tid]
        self.next_tid += 1
        t = make(self.next_tid, self.read_no_lock)
        self.recon[t.tid] = make
        self.submit(0, t)

    # ------------------------------------------------------------ network
    def deliver(self, k):
        dst, payload = self.net.pop(k)
        s = self.sched[dst]
        if s.down:
            return
        if payload[0] == "batch":
            s.on_batch(*payload[1:])
        else:
            _, tid, sender, vals = payload
            s.on_reads(tid, sender, vals)
            s.work()

    def crash(self, r):
        for q in range(self.nparts):
            self.sched[(r, q)].down = True

    def recover(self, r):
        """Rebuild replica r from the initial state by replaying the input log."""
        self.net = [m for m in self.net if m[0][0] != r]
        for q in range(self.nparts):
            self.sched[(r, q)] = self.new_scheduler(r, q)
        for (e, p) in sorted(self.log):
            for q in range(self.nparts):
                self.send((r, q), ("batch", e, p, [t for t in self.log[(e, p)] if q in self.parts(t)]))

    def drain(self, rng):
        while self.net:
            self.deliver(rng.randrange(len(self.net)))

    def run(self, rng, requests, per_epoch=8, crash=None):
        """requests: [(epoch, sequencer, txn)]. crash: (epoch, replica) or None.
        Each epoch delivers up to per_epoch messages, then closes."""
        by_epoch = {}
        for e, p, t in requests:
            by_epoch.setdefault(e, []).append((p, t))
        last = max(by_epoch, default=0)
        while True:
            if self.epoch <= last or any(self.pending.values()):
                if crash and crash[0] == self.epoch:
                    self.crash(crash[1])
                for p, t in by_epoch.get(self.epoch, []):
                    self.submit(p, t)
                for _ in range(per_epoch):
                    if self.net:
                        self.deliver(rng.randrange(len(self.net)))
                self.end_epoch()
            elif self.net:
                self.deliver(rng.randrange(len(self.net)))
            else:
                return

    def state(self, r):
        out = {}
        for q in range(self.nparts):
            out.update(self.sched[(r, q)].store)
        return out

    def results(self, r):
        out = {}
        for q in range(self.nparts):
            out.update(self.sched[(r, q)].results)
        return out


def serial(init, order):
    """The brute force oracle: run the transactions one at a time in order."""
    db = dict(init)
    results = {}
    for t in order:
        vals = {k: db[k] for k in t.reads}
        outcome, writes = run_logic(t, vals)
        db.update(writes)
        results[t.tid] = (outcome, vals)
    return db, results
test_calvin_deterministic_transactions.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/calvin-deterministic-transactions/. The authors are listed in prov/AX20CH.jsonl.
import random
import unittest

from calvin_deterministic_transactions import RESTART, Calvin, Txn, serial

PLACE = {"a0": 0, "a1": 0, "b0": 1, "b1": 1, "c0": 2, "c1": 2}
KEYS = sorted(PLACE)


def make_logic(tid, writes):
    def logic(vals):
        s = sum(vals.values())
        if s % 7 == 3:
            return None                  # a deterministic abort, such as "stock below zero"
        return {k: s + tid for k in writes}
    return logic


def workload(rng):
    reqs = []
    for tid in range(1, rng.randint(3, 6) + 1):
        reads = rng.sample(KEYS, rng.randint(0, 3))
        writes = rng.sample(KEYS, rng.randint(1, 2))
        reqs.append((rng.randrange(3), rng.randrange(3), Txn(tid, reads, writes, make_logic(tid, writes))))
    return reqs


def expected_read_messages(db, order):
    """Phase 3 messages per replica: each partition with reads sends to each
    other active participant."""
    return sum(len(db.active(t) - {s}) for t in order for s in db.read_parts(t))


def dependent(tid, read):
    """OLLP: the reconnaissance read of the index i predicts which account
    the transaction will change."""
    j = read("i")
    key = "b%d" % j

    def logic(vals):
        if vals["i"] != j:
            return RESTART               # the prediction is out of date
        return {key: vals[key] + 1}
    return Txn(tid, {"i", key}, {key}, logic)


class TestCalvin(unittest.TestCase):
    def check_run(self, db, reqs, r):
        order = db.global_order()
        want_state, want_results = serial(db.init, order)
        self.assertEqual(db.state(r), want_state)
        self.assertEqual(db.results(r), want_results)
        for (rr, q), s in db.sched.items():
            if rr == r:                  # no transaction is stuck at any partition
                self.assertEqual(s.finished, {t.tid for t in order if q in db.parts(t)})

    def test_every_replica_equals_the_serial_order(self):
        aborts = 0
        for seed in range(300):
            rng = random.Random(seed)
            db = Calvin(PLACE, replicas=2)
            reqs = workload(rng)
            db.run(rng, reqs)
            self.assertEqual(len(db.global_order()), len(reqs))
            for r in range(2):
                self.check_run(db, reqs, r)
            self.assertEqual(db.read_messages, 2 * expected_read_messages(db, db.global_order()))
            aborts += sum(1 for o, _ in db.results(0).values() if o == "abort")
        self.assertGreater(aborts, 10)

    def test_the_order_is_epoch_then_sequencer(self):
        db = Calvin(PLACE, replicas=1)
        t = [Txn(i, [], ["a0"], (lambda i: lambda v: {"a0": i})(i)) for i in range(4)]
        db.run(random.Random(0), [(1, 0, t[0]), (0, 2, t[1]), (0, 1, t[2]), (1, 0, t[3])])
        self.assertEqual([x.tid for x in db.global_order()], [2, 1, 0, 3])
        self.assertEqual(db.state(0)["a0"], 3)

    def test_crossing_transactions_never_deadlock(self):
        # T1 and T2 lock a0 and b0 in different program orders. The locks
        # are requested in the global order at each partition, so a later
        # transaction only waits for an earlier one.
        for seed in range(200):
            rng = random.Random(seed)
            db = Calvin(PLACE, replicas=1)
            t1 = Txn(1, ["a0", "b0"], ["a0", "b0"], lambda v: {"a0": v["b0"] + 1, "b0": v["a0"] + 1})
            t2 = Txn(2, ["b0", "a0"], ["b0", "a0"], lambda v: {"b0": v["a0"] * 2, "a0": v["b0"] * 2})
            db.run(rng, [(0, rng.randrange(3), t1), (0, rng.randrange(3), t2)])
            self.check_run(db, None, 0)

    def test_deterministic_abort_needs_no_vote(self):
        # Both active participants see the same values and abort alone.
        db = Calvin(PLACE, replicas=2, init={"a0": 5, "b0": 0})
        t = Txn(1, ["a0", "b0"], ["a0", "b0"],
                lambda v: None if v["a0"] < 10 else {"a0": v["a0"] - 10, "b0": v["b0"] + 10})
        db.run(random.Random(1), [(0, 0, t)])
        for r in range(2):
            self.assertEqual((db.state(r)["a0"], db.state(r)["b0"]), (5, 0))
            self.assertEqual(db.results(r)[1][0], "abort")
        self.assertEqual(db.read_messages, 2 * 2)     # a0 to P1 and b0 to P0, in each replica

    def test_crash_and_replay_of_the_input_log(self):
        replayed = 0
        for seed in range(150):
            rng = random.Random(seed)
            db = Calvin(PLACE, replicas=2)
            reqs = workload(rng)
            db.run(rng, reqs, crash=(rng.randrange(3), 1))
            self.check_run(db, reqs, 0)            # replica 0 did not wait for replica 1
            if db.state(1) != db.state(0):
                replayed += 1
            db.recover(1)
            db.drain(rng)
            self.check_run(db, reqs, 1)
        self.assertGreater(replayed, 50)

    def test_ollp_restart(self):
        place = {"i": 0, "b0": 1, "b1": 1}
        for seed in range(50):
            rng = random.Random(seed)
            db = Calvin(place, replicas=2)
            t1 = Txn(1, [], ["i"], lambda v: {"i": 1})     # moves the index to b1
            t2 = dependent(2, db.read_no_lock)              # predicts b0
            db.recon[2] = dependent
            db.run(rng, [(0, 0, t1), (0, 1, t2)])
            order = db.global_order()
            self.assertEqual([t.tid for t in order], [1, 2, 1001])
            for r in range(2):
                self.assertEqual(db.results(r)[2][0], RESTART)
                self.assertEqual(db.results(r)[1001][0], "commit")
                self.assertEqual(db.state(r), {"i": 1, "b0": 0, "b1": 1})
                self.check_run(db, None, r)


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

History

Thomson and Abadi argued in 2010 that a database that executes a given input in a fixed order can replace two-phase commit with replication of the input. Their earlier prototype used a single sequencer, which limited throughput and was a single point of failure. Calvin, presented at SIGMOD 2012 by Thomson, Diamond, Weng, Ren, Shao and Abadi, distributed the sequencer over all nodes with 10 ms epochs, added OLLP, disk support and checkpointing, and ran on a cluster of 100 commodity machines.

References

  1. Alexander Thomson, Thaddeus Diamond, Shu-Chun Weng, Kun Ren, Philip Shao and Daniel J. Abadi, Calvin, fast distributed transactions for partitioned database systems, SIGMOD 2012, pages 1 to 12, Section 2 (deterministic database systems), Section 3.1 (sequencer, 10 ms epochs and replication), Section 3.2 (the deterministic lock manager and the five phases of execution), Section 3.2.1 (OLLP), Section 5 (checkpointing) and Section 6.1 (TPC-C)

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