Algorithmresearch
Percolator transaction protocol
Also called Percolator.
Snapshot isolation over a key-value store that has only single-row transactions, using a timestamp oracle, a primary lock per transaction and lazy cleanup by readers.
- Space
- O(w) extra
- Counts
- messages 2 r + 4 w + 4 best
- Where
- r = the number of items that a transaction reads; w = the number of items that it writes
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel Peng, Frank Dabek, 2010
Percolator is the transaction protocol that Google built on top of Bigtable, a key-value store that can change only one row atomically. It gives multi-row transactions with snapshot isolation. A central timestamp oracle gives each transaction a start timestamp and a commit timestamp. A writer first locks every cell it writes and stores the new data, and then commits with a form of two-phase commit in which the client is the coordinator and one of its locks, the primary, holds the decision. There is no lock server and no recovery process. If a client crashes, the next reader that finds one of its locks looks at the primary and either finishes the commit or erases the transaction.
In plain words
Each cell keeps its old versions, labelled by time. A transaction reads the versions committed before it started, so it sees a fixed photograph of the table.
To write, a transaction puts a "locked by me" note next to the new value of every cell it changes. One note is the main note, and the others say "ask the main note". The transaction then gets a commit time and replaces the main note by a record "my value is valid from this time". That one change commits the transaction. Then it replaces the other notes in the same way.
A reader that finds a note waits. If the writer seems dead, the reader looks at the main note. If it has become a commit record, the reader finishes the job. If it is still a note, the reader erases it, and the writer can never commit.
The problem
A table is split over many servers. Each cell has many versions, each with a timestamp, and the store can read and change the cells of one row in one atomic step (a row transaction). Clients run transactions that read some cells and then write some cells. The model is the asynchronous model for safety, and clients can fail by stopping (crash failure).
The protocol must give snapshot isolation:
- Each transaction reads the last committed version of each item as of its start timestamp.
- If two transactions write the same item, one of them commits before the other starts (first committer wins).
- All writes of a transaction become visible together or not at all.
There is no separate transaction manager that could recover the work of a crashed client. The data in the table must be enough to finish or erase every transaction.
The algorithm
Each cell has three columns, each indexed by timestamp. is the value written by the transaction with start timestamp . is a lock of that transaction, and it holds the name of the primary cell. is a write record: the transaction with start timestamp committed with commit timestamp , and its value is . The timestamp oracle hands out strictly increasing timestamps. Each step on one cell (GET, PREWRITE, and each commit and cleanup step) is one row transaction.
PERCOLATOR▷ client: transaction T- 1
T.start ← a timestamp from the oracle - 2
for each item x that T reads: v[x] ← GET(T, x) - 3
compute the writes W from v; primary ← the first item of W; the other items of W are secondaries - 4
for each x in W, primary first: if not PREWRITE(T, x, primary) then erase the locks of T and abort - 5
T.commit ← a timestamp from the oracle - 6
on the primary, in one row transaction: if lock[primary][T.start] is gone then abort; write[primary][T.commit] ← T.start; erase the lock ▷ the commit point - 7
for each secondary x: write[x][T.commit] ← T.start; erase lock[x][T.start] ▷ GET(T, x), one row transaction- 8
if x has a lock with a timestamp s ≤ T.start: if its owner seems dead then CLEANUP(x, s); wait and go back to L8 - 9
c ← the largest write timestamp of x with c ≤ T.start; return data[x][write[x][c]] ▷ PREWRITE(T, x, p), one row transaction- 10
if x has a write record with timestamp ≥ T.start, or a lock with any timestamp, then return false - 11
data[x][T.start] ← W[x]; lock[x][T.start] ← p; return true ▷ CLEANUP(x, s)- 12
if the primary of s has a write record that points to s then roll forward: write the same record on x and erase lock[x][s]; else erase the lock and data of s at the primary, then at x
Line L10 is the write-write conflict check. A write record after the start of means that a concurrent transaction has already committed . A lock means that another transaction is in the middle of a commit. In both cases aborts at once, so writers never wait for each other.
Line L8 is the reason that the oracle makes reads correct. A writer locks all its cells before it asks for its commit timestamp, so if its commit timestamp is below the start timestamp of a reader, its locks or its write records are already in place when the reader looks.
The decision of a transaction is in one cell. Line L6 checks that the primary lock is still there and replaces it by the write record in the same row transaction. A cleanup at line L12 erases the primary lock first. So a writer and a cleanup cannot both succeed: either the record is there and every later cleanup rolls forward, or the lock is gone and line L6 fails for ever.
Example
The test file builds this case. Items and were written by a loader with timestamps 1 and 2. Transaction writes and , so is its primary. It crashes right after its commit point. Then reads and .
| step | line | what happens |
|---|---|---|
| 1 | L1 | |
| 2 | L11 | , |
| 3 | L11 | , |
| 4 | L5 | |
| 5 | L6 | , the lock on is erased; is committed, then its client crashes |
| 6 | L1 | |
| 7 | L9 | has no lock; its largest write timestamp up to 5 is 4, so reads |
| 8 | L8 | has the lock , and its owner is dead |
| 9 | L12 | the primary has the record , so writes and erases the lock |
| 10 | L9 | reads |
sees both writes of . If crashes one step earlier, after step 4, the primary still has its lock. Then at step 7 finds the lock on , rolls it back, and reads ; on it rolls back again and reads . Neither write of is ever visible, and can no longer commit.
Correctness
The proof is in proofs/correctness.md. It is a theorem in the model of the page, and it extends the argument of Section 2.3 of the paper. The main steps are these.
- Every write record belongs to a committed transaction, because the record of a secondary is written only after the record of the primary.
- The commit point is final. Line L6 and the roll back of line L12 both work on the primary lock in one row transaction, so exactly one of them succeeds.
- Snapshot reads: a writer with commit timestamp below the start timestamp of a reader locked its cells before it got , and the reader got after . So the reader sees the lock and waits, or sees the write record.
- First committer wins: of two overlapping writers of , the one that runs line L10 second sees the lock or the newer write record of the other and aborts.
- All or nothing: a reader that meets a lock of a dead client rolls it forward if the primary committed and back if not, so no transaction is ever half visible.
Cleanup is safe even when the owner is alive, because of step 2. The owner then fails at line L6 and aborts. So the test of liveness (a token in the Chubby lock service and a wall time in the lock, in the paper) affects only performance, not correctness.
The tests compare each run with a brute force oracle that knows only the committed writers and their timestamps. It checks that every read returns the value of the committed writer with the largest commit timestamp below the start of the reader, that no two committed writers of the same item overlap, and that after a final read of every item no lock is left, every committed writer has its record on each of its items, and no data of an uncommitted writer is left. Each run has 3 to 5 transactions over 4 items, and the scheduler interleaves the row transactions with a seeded generator. Over 300 runs with no crash, 362 of 1186 transactions aborted at line L10 and 569 writers committed. Over 300 runs with one client crash, half of them at the commit point, readers rolled 36 locks forward and 23 back. In 200 runs where a reader also cleans up live clients with probability 0.3, 46 live writers lost their primary lock and aborted at line L6. All runs passed the oracle (a measurement of this simulation). The same tests fail when line L8, the check of line L6 or the write check of line L10 is removed.
Proof: Percolator gives snapshot isolation, and lazy cleanup keeps each transaction all or nothingfull
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 step of a client or of a cleanup is one row transaction: it reads and changes the columns of one cell atomically. (The toy does the two row transactions of a cleanup in one step; the argument below does not need this, see the remark after Lemma 2.) The timestamp oracle returns strictly increasing timestamps, so no two calls return the same value. Clients can crash at any time, and a reader may clean up the lock of any client, dead or alive.
Each cell has a lock column, a data column and a write column, all indexed by timestamp. A write record says that the transaction with start timestamp wrote with commit timestamp . We say a transaction with writes is committed when its primary cell has a write record that points to . A transaction with no writes is committed when it returns from its last read.
Lemma 1 (write records). Every write record belongs to a committed transaction with and , and is in the write set of .
Proof. A write record is made at three places. Line L6 makes the record of the primary, and this step makes committed. Line L7 makes the record of a secondary, and the client runs it only after line L6 has succeeded. Line L12 makes a record on only when it finds the record of the primary of , so is already committed, and it copies the commit timestamp of that record. Write records are never removed.
Lemma 2 (the commit point is final). If is committed, then no step ever removes a lock of without putting the write record of in its place, and no step removes data of . If is not committed when a roll back of removes the primary lock, then never commits.
Proof. Locks of are removed at four places: line L6 and line L7 (which write the record in the same step), the roll forward of line L12 (the same), and a roll back, by the client after an abort or by a cleanup at line L12. The client rolls back only after line L4 or line L6 failed, and then is not committed. A cleanup rolls back only when the primary has no record of , and it removes the primary lock first. Line L6 commits only if the primary lock of is still there, in the same row transaction as the check. So once the primary lock is gone without a record, line L6 fails for ever, and is never committed. In the other order, once line L6 has made the record, every later cleanup of finds it and rolls forward. Data is removed only by a roll back.
Remark. If a cleanup runs as two row transactions, first on the primary and then on , Lemma 2 still holds. The decision is made in the step on the primary, and the step on only repeats it: a roll forward writes the same record that line L7 writes, and a roll back of follows a roll back of the primary, after which cannot commit.
Theorem 1 (snapshot reads). Let read at line L9 with start timestamp . The value it returns is the value that has in the committed writer of with the largest commit timestamp below .
Proof. Let be any committed writer of with . wrote its lock on (line L11) before it asked the oracle for (line L5), and got (line L1) after the oracle gave out , because . reads only after it has . So when reads , the lock of on is there, or it has been removed. Its start timestamp is below , so if it is there, line L8 sees it and waits. If it has been removed, Lemma 2 says the record is there. So line L9 runs only when every committed writer of with commit timestamp below has its record on . By Lemma 1 every record on belongs to a committed writer of . Hence the largest record below is the record of with the largest commit timestamp below . Its data is still there by Lemma 2. (No commit timestamp equals , because timestamps are unique.)
Theorem 2 (first committer wins). If two committed transactions and both write , then or .
Proof. Suppose not. The timestamps are distinct, so with no loss of generality . Both ran line L11 on . Look at the one that ran line L10 on second.
If it is : the lock of on is still there, and line L10 aborts ; or the lock is gone, and since commits, Lemma 2 puts the record in its place, with , and line L10 aborts .
If it is : the lock of is still there, and line L10 aborts ; or it is gone, and the record is there, with , and line L10 aborts .
In each case one of them does not commit, which is a contradiction.
Theorems 1 and 2 are the two rules of snapshot isolation: each transaction reads the committed state at its start timestamp, and two concurrent transactions do not both write an item. The commit timestamps order the committed transactions, and each one acts as if it read at its start timestamp and wrote at its commit timestamp.
Theorem 3 (all or nothing). For a committed writer , every item of its write set eventually has the record of if some reader with a later start timestamp reads it. For a writer that is not committed, no item ever has a record of , and after a reader with a later start timestamp has read every item of , no lock or data of is left.
Proof. The first part: the reader at line L8 sees the lock of on (start timestamp below its own) until the lock is replaced, and by Lemma 2 a lock of a committed is only replaced by its record. If the client of crashed, the reader runs line L12, finds the record of the primary and rolls forward. The second part: by Lemma 1 a record of exists only if is committed. A reader that meets a lock of a dead that is not committed runs line L12, finds no record on the primary, and removes the lock and data. After a roll back of the primary, cannot commit (Lemma 2), so the decision does not change later.
Progress in the toy. A reader waits only at line L8, for the lock of a writer. A writer holds locks only after its reads and never waits after that: lines L4 to L7 either succeed or abort at once. So a live writer always finishes, and the reader then goes on. A lock of a crashed writer is cleaned up by the first reader that meets it. So no client waits for ever, and there is no deadlock. In Percolator, a reader must first decide that the owner is dead (from its Chubby token or the wall time in the lock), which needs time-outs; safety does not depend on this decision, by Lemma 2.
Theorem 4 (requests). A transaction that runs alone, reads items and writes items makes requests: two to the oracle, reads, prewrites and commits. Each request has one reply, so this is messages.
Proof. With no other client there is no lock to wait for at line L8 and no conflict at line L10. The client asks the oracle at lines L1 and L5, reads each item once at line L9, prewrites each item once at line L11, and commits the primary at line L6 and each of the secondaries at line L7.
Snapshot isolation is not serializability. Let and let two transactions each read and and, if , set one of them to 0: sets and sets . If both start before either commits, both read , their write sets do not meet, and Theorem 2 lets both commit. The result is not the result of then (which gives ) or of then . This is write skew, and Percolator allows it.
Complexity
A transaction that runs alone and reads items and writes items makes requests: two to the oracle, reads, prewrites and commits, so messages with the replies (a theorem, Theorem 4 of the proof). The prewrites of the secondaries can go in parallel after the primary, and so can the commits of the secondaries, so the latency is a few round trips, not of them. Each prewrite is a read and a write on the cell, so a one-cell write costs a check for locks, a write of the lock and a second write to erase it, beyond the write of the data. Peng and Dabek measured about four times the cost of a raw Bigtable write for a transaction that writes one cell (a measurement, 2010, Section 3.2).
The extra space is one lock per written cell while the transaction runs, , and the old versions of each cell until they are garbage collected. Under contention the cost has no bound: a writer that meets a lock aborts, and a reader that meets a lock waits.
Peng and Dabek ran the system on servers in a Google data center, x86 machines with Linux and commodity SATA drives. Moving the indexing system from MapReduce to Percolator cut the average processing latency of a document by a factor of 100. The oracle served about 2 million timestamps per second from one machine, with batching of requests (Section 2.3). On a benchmark based on TPC-E, Percolator ran 11,200 transactions per second on 15,000 cores, with an average latency of 2 to 5 seconds, and it scaled almost linearly from 11 to 15,000 cores. The fastest commercial TPC-E system then ran 3,183 tpsE on one machine with 64 Nehalem cores, and the authors estimate that Percolator used about 30 times more CPU per transaction (all measurements, 2010, Section 3).
Properties
- Snapshot isolation (a theorem): reads see the committed state at the start timestamp, and concurrent writers of one item cannot both commit.
- Reads take no locks. A reader waits only when it meets a lock of a writer that is in the middle of its commit.
- No central lock manager and no recovery process. The state of every transaction is in the table, and readers clean up lazily.
- A single commit point, the primary lock, which holds the decision for all cells of the transaction.
- A central timestamp oracle that every transaction calls twice. It is a single point of failure and a limit on throughput.
- Not serializable: write skew is possible.
Variants and improvements
- Batching at the oracle: each worker keeps only one request to the oracle open, and the oracle allocates ranges of timestamps on stable storage, so it can restart without going back in time (Section 2.3).
- Clock-SI removes the oracle and takes snapshot timestamps from the loosely synchronized clocks of the partitions.
- Notifications and observers: Percolator runs user code when an observed column changes, each run in its own transaction, and at most one observer transaction commits for each change of the column (Section 2.4). This is the part of Percolator that drives incremental processing.
- To get serializability on top of the same storage, a system can add the read checks of serializable snapshot isolation or use locks on reads. Calvin and systems with TrueTime take other routes.
When to use it
Use Percolator when the storage already gives atomic single-row changes and multi-version cells, and you need multi-row transactions with snapshot isolation without a separate transaction manager. It suits workloads that tolerate latency of seconds and have few conflicts, such as incremental processing of a large data set, which was its purpose. It is a poor fit for interactive OLTP with tight latency targets or hot items: conflicting writers abort and retry, and readers can wait behind slow writers.
Pitfalls
- The code on this page is a toy. One process runs all clients, the table is a dict, each method stands for a row transaction, and there is no network, no Chubby, no time-outs and no garbage collection.
- Snapshot isolation is not serializable. The write skew test in the test file commits two transactions that each keep but together set .
- The primary must be locked first and committed first. If a secondary could commit before the primary, a cleanup could roll the primary back after part of the transaction was visible.
- The oracle must never go back in time, also after a restart. If it gives out a timestamp twice or out of order, the argument of Section 2.3 fails and a reader can miss a committed write.
- A reader must not ignore a lock with a timestamp below its start, even if the owner seems slow. The tests fail if line L8 is removed.
- Locks of a dead client stay until a reader or writer finds them, and writers abort at line L10 when they meet such a lock. A writer that never reads the cell keeps aborting until some reader cleans it up.
- A cleanup that rolls back a live client costs that client its transaction. The liveness check matters for performance.
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/percolator-transactions/. The authors are listed in prov/FVBYZN.jsonl.
"""A toy model of Percolator transactions (Peng and Dabek, OSDI 2010).
This is not Percolator. There is no Bigtable, no network and no observer
framework. A dict of cells stands for the table, and each method of the
class Table that changes cells is one atomic step, as a Bigtable row
transaction is. A counter stands for the timestamp oracle.
Each cell x has the three columns of the paper:
data[x] start_ts -> value
lock[x] start_ts -> the key of the primary cell
write[x] commit_ts -> start_ts (a pointer to the data)
Clients run as Python generators. Each next() does one row transaction or
one call to the oracle, and the scheduler picks the next client with a
seeded random.Random. A client can crash between any two steps. A reader
that finds the lock of a client that seems dead cleans it up through the
primary lock, as in the paper. A reader can also suspect live clients with
some probability, to show that cleanup is safe even when it is wrong.
"""
class Cell:
def __init__(self):
self.data = {}
self.lock = {}
self.write = {}
class Txn:
def __init__(self, tid, read_keys, logic):
"""logic(reads) -> {key: value}, the writes, computed from the reads."""
self.tid = tid
self.read_keys = list(read_keys)
self.logic = logic
self.start = None
self.commit = None
self.reads = {}
self.writes = {}
self.status = "new" # new, reading, prewriting, committed, done, aborted
self.abort_reason = None
class Table:
def __init__(self, init, rng, suspect=0.0):
"""init: {key: value}, written by a loader transaction with tid 0."""
self.cells = {k: Cell() for k in init}
self.rng = rng
self.suspect = suspect
self.ts = 0
self.owner = {} # start_ts -> Txn
self.crashed = set()
self.rolled_forward = 0
self.rolled_back = 0
loader = Txn(0, [], None)
loader.start, loader.commit = self.timestamp(), self.timestamp()
loader.writes = dict(init)
loader.status = "done"
for k, v in init.items():
self.cells[k].data[loader.start] = v
self.cells[k].write[loader.commit] = loader.start
self.loader = loader
self.rpcs = 0
def timestamp(self):
"""The timestamp oracle: strictly increasing."""
self.rpcs = getattr(self, "rpcs", 0) + 1
self.ts += 1
return self.ts
# ------------------------------------------------------------ reads
def get(self, t, x):
"""One row transaction. Returns (True, value), or (False, None) if the
reader must wait and try again."""
self.rpcs += 1
c = self.cells[x]
locks = [s for s in c.lock if s <= t.start]
if locks: # @line L8
s = min(locks)
if self.owner[s].tid in self.crashed or self.rng.random() < self.suspect:
self.cleanup(x, s)
return False, None
latest = max(ct for ct in c.write if ct <= t.start) # @line L9
return True, c.data[c.write[latest]]
def cleanup(self, x, s):
"""Percolator does this with a row transaction on the primary and
then one on x. The toy does both in one step. That is safe: after
a roll back the owner can no longer commit, and a roll forward
writes the same record that the owner would write."""
self.rpcs += 2
p = self.cells[x].lock[s]
pc = self.cells[p]
done = [ct for ct, st in pc.write.items() if st == s]
if done: # @line L12
self.cells[x].write[done[0]] = s # roll forward
del self.cells[x].lock[s]
self.rolled_forward += 1
else:
pc.lock.pop(s, None) # roll back, primary first
pc.data.pop(s, None)
self.cells[x].lock.pop(s, None)
self.cells[x].data.pop(s, None)
self.rolled_back += 1
# ----------------------------------------------------------- writes
def prewrite(self, t, x, primary):
self.rpcs += 1
c = self.cells[x]
if any(ct >= t.start for ct in c.write) or c.lock: # @line L10
return False
c.data[t.start] = t.writes[x] # @line L11
c.lock[t.start] = primary
return True
def commit_primary(self, t, p):
"""The commit point."""
self.rpcs += 1
c = self.cells[p]
if t.start not in c.lock: # @line L6
return False
c.write[t.commit] = t.start
del c.lock[t.start]
return True
def commit_secondary(self, t, x):
self.rpcs += 1
c = self.cells[x]
c.write[t.commit] = t.start # @line L7
c.lock.pop(t.start, None)
def rollback(self, t, keys):
"""The client erases its own locks after an abort, primary first."""
for x in keys:
self.rpcs += 1
self.cells[x].lock.pop(t.start, None)
self.cells[x].data.pop(t.start, None)
def is_committed(self, t):
"""A writer is committed if its primary has its write record."""
if not t.writes:
return t.status == "done"
return t.start in self.cells[min(t.writes)].write.values()
# ----------------------------------------------------------- client
def steps(self, t):
t.start = self.timestamp() # @line L1
self.owner[t.start] = t
t.status = "reading"
yield
for x in t.read_keys: # @line L2
while True:
ok, v = self.get(t, x)
yield
if ok:
t.reads[x] = v
break
t.writes = t.logic(dict(t.reads)) if t.logic else {}
if not t.writes:
t.status = "done"
return
keys = sorted(t.writes) # @line L3
primary = keys[0]
t.status = "prewriting"
for i, x in enumerate(keys): # @line L4
if not self.prewrite(t, x, primary):
self.rollback(t, keys[:i])
t.status, t.abort_reason = "aborted", "conflict"
return
yield
t.commit = self.timestamp() # @line L5
yield
if not self.commit_primary(t, primary):
self.rollback(t, keys)
t.status, t.abort_reason = "aborted", "cleaned up"
return
t.status = "committed"
yield
for x in keys[1:]:
self.commit_secondary(t, x)
yield
t.status = "done"
def run(self, rng, txns, crash=None, limit=100000):
"""crash: None, (step, tid), or ("commit point", tid) for a crash just
after the client has committed its primary. Runs until every client
that did not crash has finished, and returns the number of steps."""
gens = {t.tid: self.steps(t) for t in txns}
by_tid = {t.tid: t for t in txns}
step = 0
while gens:
if crash and step == crash[0] and crash[1] in gens:
del gens[crash[1]]
self.crashed.add(crash[1])
if not gens:
break
tid = rng.choice(sorted(gens))
try:
next(gens[tid])
if crash and crash == ("commit point", tid) and by_tid[tid].status == "committed":
del gens[tid]
self.crashed.add(tid)
except StopIteration:
del gens[tid]
step += 1
assert step < limit, "no progress"
return step
def snapshot(self, rng):
"""A final read-only transaction over every key. It also cleans up
the locks that crashed clients left behind."""
t = Txn(-1, sorted(self.cells), None)
self.run(rng, [t])
return t.reads
test_percolator_transactions.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/percolator-transactions/. The authors are listed in prov/FVBYZN.jsonl.
import itertools
import random
import unittest
from percolator_transactions import Table, Txn
INIT = {"a": 0, "b": 10, "c": 20, "d": 30}
KEYS = sorted(INIT)
def make_logic(tid, writes):
return lambda vals: {k: sum(vals.values()) + 100 * tid + i for i, k in enumerate(writes)}
def workload(rng):
txns = []
for tid in range(1, rng.randint(3, 5) + 1):
reads = rng.sample(KEYS, rng.randint(1, 3))
writes = rng.sample(KEYS, rng.randint(1, 2)) if rng.random() < 0.8 else []
txns.append(Txn(tid, reads, make_logic(tid, writes) if writes else None))
return txns
def drive(table, txns, order):
"""Advance the clients in the given order of tids, then finish them."""
gens = {t.tid: table.steps(t) for t in txns}
for tid in order + sorted(gens) * 50:
if tid in gens:
try:
next(gens[tid])
except StopIteration:
del gens[tid]
return gens
class TestPercolator(unittest.TestCase):
def check_si(self, table, txns, rng):
"""The brute force oracle. It computes from the committed writers
alone what each read and the final state must be under snapshot
isolation, and compares."""
writers = [table.loader] + [t for t in txns if t.writes and table.is_committed(t)]
def value_at(x, ts):
ws = [w for w in writers if x in w.writes and w.commit < ts]
return max(ws, key=lambda w: w.commit).writes[x]
for t in txns:
if len(t.reads) == len(t.read_keys): # every read that returned
for x, v in t.reads.items():
self.assertEqual(v, value_at(x, t.start), (t.tid, x))
for a, b in itertools.combinations(writers, 2): # first committer wins
if set(a.writes) & set(b.writes):
self.assertTrue(a.commit < b.start or b.commit < a.start, (a.tid, b.tid))
for w in writers[1:]:
self.assertEqual(w.writes, w.logic(dict(w.reads)))
final = table.snapshot(rng)
self.assertEqual(final, {x: value_at(x, table.ts + 1) for x in KEYS})
for c in table.cells.values(): # cleanup left nothing behind
self.assertEqual(c.lock, {})
committed = {w.start for w in writers}
for x, c in table.cells.items(): # atomic: all or nothing
self.assertEqual(set(c.data), {s for s in committed if x in table.owner.get(s, table.loader).writes})
for w in writers:
if x in w.writes:
self.assertEqual(c.write.get(w.commit), w.start)
return len(writers) - 1
def test_snapshot_isolation_without_crashes(self):
aborts = commits = 0
for seed in range(300):
rng = random.Random(seed)
table = Table(INIT, rng)
txns = workload(rng)
table.run(rng, txns)
commits += self.check_si(table, txns, rng)
aborts += sum(1 for t in txns if t.status == "aborted")
self.assertEqual(table.rolled_back + table.rolled_forward, 0)
self.assertGreater(aborts, 30)
self.assertGreater(commits, 300)
def test_crashes_and_lazy_cleanup(self):
forward = back = 0
for seed in range(300):
rng = random.Random(1000 + seed)
table = Table(INIT, rng)
txns = workload(rng)
when = rng.randrange(25) if seed % 2 else "commit point"
table.run(rng, txns, crash=(when, rng.randint(1, len(txns))))
self.check_si(table, txns, rng)
forward += table.rolled_forward
back += table.rolled_back
self.assertGreater(forward, 20)
self.assertGreater(back, 10)
def test_wrong_suspicion_is_safe(self):
cleaned = 0
for seed in range(200):
rng = random.Random(5000 + seed)
table = Table(INIT, rng, suspect=0.3)
txns = workload(rng)
table.run(rng, txns, crash=(rng.randrange(25), rng.randint(1, len(txns))))
self.check_si(table, txns, rng)
cleaned += sum(1 for t in txns if t.abort_reason == "cleaned up")
self.assertGreater(cleaned, 5)
def test_lost_update_is_prevented(self):
rng = random.Random(0)
table = Table(INIT, rng)
t1 = Txn(1, ["a"], lambda v: {"a": v["a"] + 1})
t2 = Txn(2, ["a"], lambda v: {"a": v["a"] + 1})
drive(table, [t1, t2], [1, 2, 1, 2, 1, 2]) # both read a = 0, T1 locks a first
self.assertEqual((t1.status, t2.status, t2.abort_reason), ("done", "aborted", "conflict"))
self.assertEqual(table.snapshot(rng)["a"], 1)
def test_write_skew_is_allowed(self):
# The rule is x + y >= 1. Each transaction checks it in its snapshot
# and sets one of the two to 0. Snapshot isolation commits both.
init = {"x": 1, "y": 1}
rng = random.Random(0)
table = Table(init, rng)
def guard(key):
return lambda v: {key: 0} if v["x"] + v["y"] >= 2 else {}
t1, t2 = Txn(1, ["x", "y"], guard("x")), Txn(2, ["x", "y"], guard("y"))
drive(table, [t1, t2], [1, 2, 1, 1, 2, 2])
self.assertEqual((t1.status, t2.status), ("done", "done"))
final = table.snapshot(rng)
self.assertEqual(final, {"x": 0, "y": 0})
for order in itertools.permutations([guard("x"), guard("y")]): # no serial order gives this
s = dict(init)
for logic in order:
s.update(logic(dict(s)))
self.assertNotEqual(s, final)
def test_roll_forward_and_roll_back(self):
for crash_after, want, forward, back in [(5, {"a": 5, "b": 6}, 1, 0), (4, {"a": 0, "b": 10}, 0, 2)]:
rng = random.Random(0)
table = Table(INIT, rng)
t1 = Txn(1, [], lambda v: {"a": 5, "b": 6})
gen = table.steps(t1)
for _ in range(crash_after): # 5 steps end at the commit point, 4 just before it
next(gen)
table.crashed.add(1)
t2 = Txn(2, ["a", "b"], None)
table.run(rng, [t2])
self.assertEqual(t2.reads, want)
self.assertEqual((table.rolled_forward, table.rolled_back), (forward, back))
self.check_si(table, [t1, t2], rng)
def test_requests_of_a_transaction_alone(self):
rng = random.Random(0)
for r in range(4):
for w in range(1, 4):
table = Table(INIT, rng)
t = Txn(1, KEYS[:r], make_logic(1, KEYS[:w]))
table.run(rng, [t])
self.assertEqual(table.rpcs, r + 2 * w + 2)
if __name__ == "__main__":
unittest.main()
History
Google built its web search index with a series of 100 MapReduce jobs over the whole repository, so a new document had to wait for a full pass. To add new documents with low latency, Daniel Peng and Frank Dabek designed Percolator, which adds multi-row transactions and notifications to Bigtable, and presented it at OSDI 2010. With Caffeine, the indexing system built on it, the average age of a document in a search result dropped by nearly 50 percent (Section 1). The design uses the definition of snapshot isolation of Berenson et al. (SIGMOD 1995) and runs two-phase commit on the client, with the decision stored in the data itself.
References
- Daniel Peng and Frank Dabek, Large-scale incremental processing using distributed transactions and notifications, OSDI 2010, pages 251 to 264, Section 2.2 (transactions, the lock, data and write columns, cleanup, and the pseudocode in Figure 6), Section 2.3 (the timestamp oracle and the proof that Get sees all earlier commits), Sections 3.2 and 3.3 (overhead against Bigtable and the TPC-E-like benchmark)
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 FVBYZN Edit this page History Report an error Markdown