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
- Evidence
- Proof sketchCode in 1 languages
- 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.
CALVIN▷ sequencer at partition p, for each epoch e (10 ms in Calvin)- 1
collect the transaction requests that clients send to p during epoch e into batch(e, p) - 2
replicate batch(e, p) (Paxos or a master replica), then send it to the scheduler of every partition in each replica ▷ scheduler at partition q, its lock thread- 3
wait until batch(e, p) has arrived from every sequencer p; the order of epoch e is batch(e, 1), batch(e, 2), ... - 4
for each transaction T in this global order: request all locks of T on the items of q, at once - 5
grant the locks on each item strictly in the order of the requests ▷ scheduler at partition q, a worker for T, when T holds all its locks at q- 6
read the items of the read set of T that are stored at q - 7
send these values to every active participant of T (a partition with an item of the write set of T) - 8
if q is not an active participant then release the locks of T at q and stop - 9
wait until the values from every partition of the read set of T have arrived - 10
run the logic of T on these values; every active participant computes the same writes or the same abort - 11
apply 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 is on partition and item on , with and . In epoch 0, sequencer 0 gets : "if , move 10 from to , else abort", and sequencer 1 gets : "set to ". The global order is .
| step | where | what happens |
|---|---|---|
| 1 | L4 at | queue of : (X), (X) |
| 2 | L4 at | queue of : (X), (S) |
| 3 | L6, L7 | holds its locks at both partitions; sends to and sends to |
| 4 | L10, L11 | both partitions compute , , apply their own write and release |
| 5 | L6 to L8 at | gets its S lock on , reads , sends it to , and releases, since is not an active participant of |
| 6 | L9 to L11 at | gets its X lock on after , waits for , sets |
The result , is the result of and then , and it is the same in every replica whatever the message delays. sends 2 messages and sends 1, and nobody sends a commit message. If had been first in the log, every replica would compute and then abort .
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.
- Every scheduler sees the transactions in the same global order (line L3).
- 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).
- By induction on the global order, every transaction finishes: it waits only for earlier transactions, so there is no deadlock.
- 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.
- 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 declares its read set and write set , and its logic is a deterministic function of the values of ; it returns new values for some items of , 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 . The active participants of are the partitions that hold an item of (of if is empty). The serial execution runs 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 only when the batch of every sequencer for has arrived, and it takes the batches in sequencer order. It finishes epoch before it starts . Messages can arrive in any order, but the batches are buffered until line L3 uses them.
Lemma 2 (the lock queues). At each item , the lock queue holds the transactions that access in the global order. An entry of 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.
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 . Suppose finish everywhere. At each partition of , every entry in front of the entries of belongs to an earlier transaction (Lemma 2), so it leaves the queue, and gets all its local locks. Entries behind it never block it. So every partition of 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 , since messages are not lost, and finishes at lines L9 to L11.
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 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 we show that when a partition reads an item at line L6, the value of is its value after in the serial execution, and that writes the same values as in the serial execution.
Let with write . Its X entry on is in front of the entry of and conflicts with it, so by Lemma 2 reads only after has released its lock at . The partition holds , so it is an active participant of , and it releases the lock only after line L11 has stored the writes of . Let with write . Its X entry is behind the entry of , so it is granted only after releases its lock at , and does this after line L6 (at line L8 or after line L11). So when reads , every earlier writer of has stored its value and no later writer has. The writers of also store their values in the global order, by the same argument. By the induction hypothesis each earlier writer stored its serial value, so reads the serial value of .
Each active participant of runs the logic (line L10) on the values from every partition of , that is, on the serial values of all of . 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.
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 messages in phase 3, over the partitions of , where is the set of active participants. If touches partitions, this is at most . There is no commit message. Each sequencer sends one batch message per epoch to each scheduler of each replica.
Proof. Each partition of sends one message at line L7 to each active participant other than itself, and nothing else is sent for . With partitions of reads, active participants and partitions in both sets, the count is and . For a fixed the product is largest when , which gives . This grows with for , so the largest value is at , that is, .
Complexity
For a transaction that touches partitions, phase 3 sends one message from each partition with reads to each other active participant, at most 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.
# 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W0 stub |
|
Tag AX20CH Edit this page History Report an error Markdown