Algorithmresearch
Clock-SI
Also called clock-based snapshot isolation.
Snapshot isolation for partitioned data that takes snapshot and commit timestamps from loosely synchronized local clocks, with no central timestamp server.
- Space
- O(p) extra
- Counts
- messages 2 r + 3 p worstmessages 2 r best
- Where
- p = the number of partitions written; r = the number of items read on other partitions
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jiaqing Du, Sameh Elnikety, Willy Zwaenepoel, 2013
Clock-SI implements snapshot isolation for a data store that is split into partitions, with no central timestamp server. A transaction takes its snapshot timestamp from the clock of the partition where it starts, and an update transaction takes its commit timestamp from the clocks of the partitions it writes. The clocks are kept close by a protocol such as NTP, but they are never exact. Clock-SI stays correct for any clock skew because a partition delays a read in two cases: when its own clock has not yet reached the snapshot timestamp, and when a transaction that may commit before the snapshot is still committing. The skew changes only how long reads wait.
In plain words
Each partition keeps old versions of each item, labelled with the time of their commit. A transaction reads the clock of the partition where it starts and then reads the version of each item that was committed before that time.
Two things can go wrong. The clock of another partition may be behind, so a transaction there could still commit "before" our time after we have read. And a transaction may have got its commit time but not yet finished its commit. In both cases our reader waits a little: until the slow clock passes our time, or until the commit is finished. After that, nothing can appear below our time, so what we read is a fixed photograph.
The problem
Data is split into partitions, and each partition is on one server with its own clock. Clocks move forward but can differ from each other by an unknown amount. Clients start transactions at some partition, called the originating partition, which runs the reads and writes and talks to other partitions when it needs their items.
The system must give snapshot isolation, as in Section II-B of the paper:
- Each transaction reads a consistent snapshot: all writes of transactions committed before its snapshot timestamp, and no other writes.
- Committed update transactions are in a total order given by their commit timestamps.
- Of two concurrent transactions that write the same item, at most one commits.
Earlier systems, such as Percolator, get both timestamps from a central server. That server is a single point of failure, it adds a round trip at the start and one at the commit, and it can limit throughput. Clock-SI wants the same isolation with timestamps from local clocks. The model is the asynchronous model for safety: no bound on message delay or clock skew is needed for correctness.
The algorithm
Each partition keeps a list of versions for each item, and for each transaction that is committing or prepared there, the keys it writes and its commit or prepare timestamp. Writes are buffered at the originating partition until the commit.
CLOCK-SI▷ originating partition o of transaction T- 1
T.snapshot ← clock(o) − Δ ▷ partition q serves a read of item k by T- 2
if T came from another partition and T.snapshot ≥ clock(q): wait until clock(q) > T.snapshot - 3
if a transaction that writes k is committing or prepared at q with a timestamp < T.snapshot: wait until it is committed or aborted - 4
return the latest committed version of k with a timestamp < T.snapshot ▷ commit of T- 5
if T wrote nothing: commit at once - 6
if T writes one partition q: at q (after the wait of L2), certify; state committing; T.commit ← clock(q); log; install - 7
else send PREPARE to each partition q that T writes; q first waits as in L2 - 8
at q, certify: no other transaction is committing or prepared on the keys, and no version of them is newer than T.snapshot; if so, state prepared, prepare timestamp ← clock(q); reply with it, else reply no - 9
if every partition replied with a timestamp: T.commit ← the largest prepare timestamp; log the decision; send COMMIT(T.commit) - 10
at q on COMMIT: install the writes of T as versions with timestamp T.commit - 11
else: send ABORT to every partition that T writes
Line L2 handles a clock that is behind. If the clock of has not reached the snapshot, another transaction could still commit at with a timestamp below the snapshot, and the reader would miss it. After the wait, every later commit at gets a larger timestamp. The same wait is applied to PREPARE and to a remote local commit, so a commit timestamp is always above the snapshot of its own transaction.
Line L3 handles a commit in progress. A transaction that has a commit or prepare timestamp below the snapshot may still commit, and its versions must be in the snapshot, so the reader waits for the outcome.
Line L9 takes the largest prepare timestamp. A participant that does not delay a reader (because its prepare timestamp is above the snapshot) must also not see the transaction committed below the snapshot, so the commit timestamp must be at least every prepare timestamp. The proof gives a counterexample for the smallest one.
lets a transaction read a slightly older snapshot. With a large enough the waits of lines L2 and L3 almost never happen, at the cost of staler data and a few more aborts.
Example
The test file builds this case. Partition has a clock 5 ticks ahead of . A clock reading at partition is , and two readings at one partition differ by at least 10.
| tick | line | what happens |
|---|---|---|
| 0 | L1 | starts at ; ; it reads , which is on |
| 1 or 2 | L2 | the read reaches , whose clock is 1001 or 2001, below 5000, so it waits |
| 3 | L1, L6 | starts at with snapshot 3001, writes and gets the commit timestamp 3011 |
| 5 | L6 | the commit record of is on disk, and its version of at 3011 is installed |
| 5 | L2, L4 | the clock of is 5001; the read goes on and returns from the version at 3011 |
committed with a timestamp below the snapshot of , so snapshot isolation requires to see it. Without the wait of line L2, the read would run at tick 1 or 2 and return the old value 20, and the snapshot of would miss a write that comes before it in the commit order. The test checks both runs.
Correctness
The proof is in proofs/correctness.md. It is a theorem in the model of the page and does not assume any bound on the clock skew; the paper makes the same point in Section III-D. The main steps are these.
- After a partition serves a request of (after the wait of line L2), every later reading of its clock is above .
- A committed writer of with commit timestamp below was certified at the partition of before read there; otherwise its timestamp there would be above the snapshot by step 1. So when reads, is pending, and line L3 waits, or it is installed.
- So line L4 sees exactly the committed writers below the snapshot.
- Certification at line L8 is atomic at each partition, and it rejects a writer when an overlapping writer of the same item is pending or installed with a newer timestamp. So two concurrent writers of one item cannot both commit.
The tests compare each run with a brute force oracle that knows only the committed writers and their timestamps. It checks every returned read against the committed writer with the largest commit timestamp below the snapshot, checks that overlapping committed writers never share an item, and checks the final versions and that nothing is left pending. Each run has 3 to 6 transactions over 6 items on 3 partitions, clock skews of up to 3 ticks each way and messages of 1 or 2 ticks, all from a seeded generator. Over 300 runs, 561 writers committed and 350 transactions aborted; reads waited 416 times for a clock and 72 times for a pending commit. In 200 more runs a coordinator crashes, before the votes arrive or after it logged the commit, and votes sent to it while it is down are lost. All runs pass. With line L2 removed, 30 of the 300 runs break snapshot isolation; with line L3 removed, 53; with the smallest prepare timestamp at line L9, 44 (measurements of this simulation).
Proof: Clock-SI gives snapshot isolation for any clock skewfull
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 partition has a clock that never goes back, and two readings of the clock at one partition differ; readings at different partitions differ in the partition number (the paper breaks ties by partition id). Nothing is assumed about the skew between clocks. Each step of a partition (serving a read, a certification with its prepare or local commit, an install, an abort) is atomic. Messages to a partition are not lost. A coordinator may crash, but it comes back and reads its log.
For a transaction , is its snapshot timestamp (line L1). For a committed writer , is its commit timestamp: the clock reading at line L6 for a local commit, and the largest prepare timestamp at line L9 for a distributed commit. A version of is a pair (timestamp, value) that line L10 installs. While is certified at a partition and not yet installed or aborted there, is pending on its keys at that partition with a timestamp : its prepare timestamp, or its commit timestamp for a local commit. In both cases if commits.
Lemma 1 (versions). Line L10 installs a version of only for a committed writer of , with timestamp . A pending entry of is removed only by its install (if commits) or by an abort (if aborts).
Proof. Line L10 runs for a local commit after the commit record is on disk, and for a distributed commit when the commit message arrives, which the coordinator sends only after it has logged the decision at line L9. The rest is read from the code.
Lemma 2 (clocks after a wait). If partition serves a request of at time , then every clock reading at after is larger than .
Proof. If is not the origin of , line L2 serves the request only when the clock of is above , and later readings are larger still. If is the origin, is a reading at minus , taken before , and later readings are larger.
Lemma 3 (commit after snapshot). Every committed writer has .
Proof. Each prepare timestamp and each local commit timestamp is a reading at a partition that has served a request of (line L2 applies to prepare and to a remote local commit), so by Lemma 2 it is above . The commit timestamp is one of these readings or their maximum.
Theorem 1 (consistent snapshot). When partition serves a read of by at line L4, it returns the value written by the committed writer of with the largest (the initial value if there is none).
Proof. Let be any committed writer of with , and let be the time of the read. If was certified at before , then at it is installed or still pending with timestamp . A pending entry like this makes line L3 wait, so at it is installed. If was certified at after , its timestamp at is a reading after , so it is above by Lemma 2. Then , which is false. So every committed writer of with commit timestamp below has its version on at time , and by Lemma 1 no other transaction has a version there. Line L4 takes the version with the largest timestamp below , which is the version of the writer with the largest .
The proof uses line L3 only for writers that were already certified and line L2 only for writers that come later. These are the two delays of the paper: a pending commit and a clock that is behind.
Theorem 2 (first committer wins). If committed writers and both write , then or .
Proof. Both are certified at the partition of (line L8), in atomic steps. Say is certified first. When is certified, is pending at or installed (Lemma 1, since commits). If is pending, line L8 rejects . So is installed with timestamp , and line L8 accepts only if .
Theorem 3 (snapshot isolation). The commit timestamps order the committed writers in a total order. Each transaction reads the state made by the writers with commit timestamps below its snapshot timestamp (Theorem 1), each writer commits after its snapshot (Lemma 3), and two committed writers of one item do not overlap (Theorem 2). These are the three rules of snapshot isolation in Section II-B of the paper. The proofs never use a bound on the clock skew, so the skew changes only how long the reads wait.
All or nothing. A distributed writer is committed when its coordinator logs the decision. By Lemma 1 no version is installed before that. If the coordinator crashes before it logs a decision, it aborts when it comes back, and sends the abort to every participant. If it crashes after it logged the commit, it sends the commit messages when it comes back. Messages to partitions are not lost, so in the end every participant installs the writes or drops them, and no pending entry is left.
Progress. A read waits at line L2 until a clock moves past a value, which happens in finite time, or at line L3 until a pending writer is decided. A certification never waits, so a coordinator gets all its votes and decides, unless it is down. A prepared participant whose coordinator is down waits until the coordinator comes back, and so do the reads that need its keys; this is the blocking of two-phase commit, and Clock-SI does not remove it. Waits never form a cycle, because nothing that a read waits for waits for a read.
A counterexample for the smallest prepare timestamp. If line L9 took the smallest prepare timestamp, the argument of Theorem 1 would fail. Let prepare on at timestamp 10 and on at timestamp 30, and commit with timestamp 10. A reader with snapshot 20 reads on : the pending entry there has timestamp , so the read does not wait and returns the old . It reads on after the install and gets the new , since . The snapshot has half of . The tests find such runs when the maximum is replaced by the minimum.
Theorem 4 (messages). A transaction that reads items on partitions other than its origin sends messages for the reads. A writer that writes on one partition other than its origin sends 2 more messages, and a writer that writes on partitions sends 3 messages for each participant other than its origin. No message goes to a timestamp server.
Proof. Each remote read is one request and one reply. A local commit at another partition is one request and one reply. Two-phase commit sends a prepare, a vote and a commit message to each participant; messages to the origin itself are not network messages. The timestamps come from line L1 and from the clocks of the participants.
Complexity
Let be the number of items that a transaction reads on other partitions and the number of partitions it writes. The reads take messages. A commit on one partition takes 2 messages if it is not the origin, and two-phase commit takes 3 messages per participant other than the origin (a theorem, Theorem 4 of the proof). A central timestamp server would add one round trip for a read-only transaction and two for an update transaction; Clock-SI saves these.
The cost is waiting. A wait at line L2 lasts at most the clock skew minus the one-way message delay, and a wait at line L3 at most the time to write a commit record plus, for a distributed commit, a round trip (Section III-A of the paper). These bounds hold only when skew and delays are bounded, so they are a property of the deployment, not a theorem in the asynchronous model. In the simulation, ticks cut the number of waits over 200 runs from 333 to 10.
Du, Elnikety and Zwaenepoel built a partitioned in-memory key-value store in C++ and compared Clock-SI with SI that uses a timestamp server. In a LAN of servers with two Intel Xeon processors each, Linux 3.2.0, Gigabit Ethernet and a SATA disk for the log, short read-only transactions on YCSB had about 50% lower latency on one partition, and throughput improved by up to 50%. On Amazon EC2 with partitions in US West, US East and Europe and the timestamp server in US West, clients in Europe saw about 160 ms less latency per transaction (measurements, 2013, Section V).
Properties
- Snapshot isolation for any clock skew (a theorem); the skew affects only the waits.
- No central timestamp server, so no single point of failure for timestamps and no extra round trips.
- Read-only transactions never abort and take no locks, but they can wait.
- The commit order can differ from real time for independent transactions on different partitions whose commit timestamps are closer than the clock precision (Section III-D). Clock-SI does not give external consistency.
- Not serializable: write skew is possible, as with any snapshot isolation.
- Distributed commits use two-phase commit and keep its blocking when a coordinator fails.
Variants and improvements
- Older snapshots: choose per transaction. gives the freshest data; the paper suggests the larger of the commit time plus a round trip and the clock skew minus the one-way delay, to make waits rare (Section III-C).
- Session consistency: a client keeps the last snapshot or commit timestamp it saw and sends it with the next transaction; the originating partition waits until its clock passes this value (Section III-E).
- In line L3 the paper does not wait for a prepared transaction whose commit timestamp, once known, is above the snapshot; the reader can ask the coordinator for it. The toy waits for every prepared writer with a prepare timestamp below the snapshot, which is simpler and still correct.
- Systems with tight clock bounds, such as TrueTime, make a commit wait out the uncertainty and get external consistency; hybrid logical clocks mix physical time with a logical counter.
When to use it
Use Clock-SI when data is partitioned, snapshot isolation is enough, and a central timestamp server would be a bottleneck or a long way off, as in a store spread over several data centers. It helps most for short transactions, where the round trips to a timestamp server are a large part of the latency. Do not use it if transactions must see each other in real-time order across partitions, or if write skew is not acceptable.
Pitfalls
- The code on this page is a toy. One process simulates the partitions in ticks, clocks are tick counts plus a fixed skew, and the log is a delay; there is no disk, no network and no clock synchronization protocol.
- Every request that reaches a partition from another partition must wait for the clock, not only reads. If PREPARE does not wait, a prepare timestamp can be below the snapshot of its own transaction.
- The commit timestamp must be the largest prepare timestamp. The tests break with the smallest.
- A participant must make a prepared write visible as "pending" to readers, or line L3 cannot see it. The paper does this with a version that no reader may read until the commit finishes.
- Large clock skew does not break correctness, but reads at a partition with a slow clock wait longer.
- A clock that goes back, for example after a bad NTP step, breaks the proof. The model assumes clocks only move forward.
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/clock-si/. The authors are listed in prov/9E7PE4.jsonl.
"""A toy model of Clock-SI (Du, Elnikety and Zwaenepoel, SRDS 2013).
This is not a database. One process simulates a few partitions in steps of
global time called ticks. Each partition has a physical clock that is the
global time plus a fixed skew. A clock reading at partition p is
(tick + skew) * 1000 + p, and two readings at one partition differ by at
least 10, so all timestamps are unique and every clock only moves forward.
Each transaction starts at its originating partition, which is also its
coordinator. It reads first and then writes; the writes stay in a
workspace until commit. A message between partitions takes 1 or 2 ticks,
chosen with a seeded random.Random, so messages can arrive in any order. A
write to stable storage takes log_delay ticks. A coordinator can crash
during two-phase commit. Messages sent to it while it is down are lost.
When it comes back it reads its log: it sends the commit again if it
logged the commit, and else it aborts.
The flags in `checks` turn off parts of the protocol, so that the tests can
show that each part is needed.
"""
STRIDE = 10 # so at most 10 partitions
class Txn:
def __init__(self, tid, origin, reads, writes, start):
"""reads, writes: lists of keys. Each written value is a function of
the values read, so a wrong read shows in the final state too."""
self.tid, self.origin, self.start = tid, origin, start
self.read_keys, self.write_keys = list(reads), list(writes)
self.snapshot = self.commit = None
self.reads, self.writes = {}, {}
self.status = "active" # active, committed, aborted
class Request:
def __init__(self, kind, t, keys=(), ts=None, index=0):
self.kind, self.t, self.keys, self.ts, self.index = kind, t, list(keys), ts, index
self.counted = False # counted as a delay already
class Partition:
def __init__(self, pid, skew):
self.pid, self.skew = pid, skew
self.last = None
self.queue = []
def now(self, tick):
phys = (tick + self.skew) * 1000 + self.pid
return phys if self.last is None else max(phys, self.last)
def read_clock(self, tick):
v = (tick + self.skew) * 1000 + self.pid
if self.last is not None:
v = max(v, self.last + STRIDE)
self.last = v
return v
class ClockSI:
def __init__(self, place, skews, init, rng, delta=0, log_delay=2, checks=None):
"""place: {key: partition}; skews: the skew of each partition, in
ticks; delta: the snapshot age, in ticks."""
self.place, self.rng = dict(place), rng
self.parts = [Partition(p, s) for p, s in enumerate(skews)]
self.delta, self.log_delay = delta * 1000, log_delay
self.checks = {"clock": True, "pending": True, "max": True}
self.checks.update(checks or {})
self.versions = {k: [(-10 ** 9, v, 0)] for k, v in init.items()} # (ts, value, tid)
self.pending = {k: {} for k in init} # key -> tid -> (state, prepare or commit ts)
self.tick = 0
self.net = [] # (tick, seq, destination, payload)
self.seq = 0
self.coord = {} # tid -> [generator, replies needed, replies]
self.down = set()
self.delays = {"clock": 0, "pending": 0}
self.messages = 0
def send(self, src, dst, payload, delay=None):
"""dst is a partition number or ("coord", tid)."""
if delay is None:
here = dst if isinstance(dst, int) else self.txn[dst[1]].origin
delay = 0 if here == src else self.rng.randint(1, 2)
self.messages += here != src
self.seq += 1
self.net.append((self.tick + delay, self.seq, dst, payload))
def reply(self, q, req, value):
self.send(q, ("coord", req.t.tid), ("reply", req.index, value))
# --------------------------------------------------------- partitions
def try_request(self, q, req):
"""Serve one request at partition q. Returns False if it must wait."""
part, t = self.parts[q], req.t
if q != t.origin and req.kind in ("read", "prepare", "local"):
if self.checks["clock"] and t.snapshot >= part.now(self.tick): # @line L2
self.delays["clock"] += not req.counted
req.counted = True
return False
if req.kind == "read":
k = req.keys[0]
if self.checks["pending"] and any(ts < t.snapshot for _, ts in self.pending[k].values()): # @line L3
self.delays["pending"] += not req.counted
req.counted = True
return False
_, v, _ = max(x for x in self.versions[k] if x[0] < t.snapshot) # @line L4
self.reply(q, req, v)
elif req.kind in ("prepare", "local"):
ok = all(not self.pending[k] and max(self.versions[k])[0] < t.snapshot # @line L8
for k in req.keys)
if not ok:
self.reply(q, req, None)
elif req.kind == "prepare":
ts = part.read_clock(self.tick)
for k in req.keys:
self.pending[k][t.tid] = ("prepared", ts)
self.reply(q, req, ts)
else:
ts = part.read_clock(self.tick) # @line L6
for k in req.keys:
self.pending[k][t.tid] = ("committing", ts)
self.send(q, q, Request("logged", t, req.keys, ts, req.index), self.log_delay)
elif req.kind == "logged": # the local commit record is on disk
self.install(t, req.keys, req.ts)
self.reply(q, req, req.ts)
elif req.kind == "commit":
self.install(t, req.keys, req.ts)
elif req.kind == "abort":
for k in req.keys:
self.pending[k].pop(t.tid, None)
return True
def install(self, t, keys, ts):
for k in keys: # @line L10
self.versions[k].append((ts, t.writes[k], t.tid))
self.pending[k].pop(t.tid, None)
# -------------------------------------------------------- coordinator
def coordinator(self, t):
"""A generator. It yields a list of requests and gets their replies,
or yields ("sleep", ticks) or ("down", ticks)."""
o = t.origin
t.snapshot = self.parts[o].read_clock(self.tick) - self.delta # @line L1
for k in t.read_keys:
(v,) = yield [(self.place[k], Request("read", t, [k]))]
t.reads[k] = v
base = sum(t.reads.values())
t.writes = {k: base + 100 * t.tid + i for i, k in enumerate(t.write_keys)}
if not t.writes: # @line L5
t.status = "committed"
return
by_part = {}
for k in t.write_keys:
by_part.setdefault(self.place[k], []).append(k)
if len(by_part) == 1:
(q, keys), = by_part.items()
(ts,) = yield [(q, Request("local", t, keys))]
t.status, t.commit = ("committed", ts) if ts is not None else ("aborted", None)
return
parts = sorted(by_part)
votes = yield [(q, Request("prepare", t, by_part[q])) for q in parts] # @line L7
if votes is not None and None not in votes:
t.commit = (max if self.checks["max"] else min)(votes) # @line L9
yield ("sleep", self.log_delay) # the decision is logged
t.status = "committed"
if self.crash == (t.tid, "decided"):
yield ("down", self.down_ticks)
for q in parts:
self.send(o, q, Request("commit", t, by_part[q], t.commit))
else:
t.status = "aborted" # @line L11
for q in parts:
self.send(o, q, Request("abort", t, by_part[q]))
def resume(self, tid, value):
gen = self.coord[tid][0]
try:
out = gen.send(value)
except StopIteration:
del self.coord[tid]
return
me = ("coord", tid)
if out[0] == "sleep":
self.coord[tid] = [gen, 1, []]
self.send(None, me, ("wake",), out[1])
elif out[0] == "down":
self.coord[tid] = [gen, 1, []]
self.down.add(tid)
self.send(None, me, ("recover",), out[1])
else:
self.coord[tid] = [gen, len(out), [None] * len(out)]
self.coord[tid].append(0)
for i, (q, req) in enumerate(out):
req.index = i
self.send(self.txn[tid].origin, q, req)
if self.crash == (tid, "prepare") and out[0][1].kind == "prepare":
self.down.add(tid) # it crashes before the votes arrive
self.send(None, me, ("recover",), self.down_ticks)
def to_coordinator(self, tid, payload):
if tid not in self.coord:
return
entry = self.coord[tid]
if payload[0] == "recover":
self.down.discard(tid)
# A vote that arrived while it was down is lost, and nothing in
# the log says commit, so the transaction aborts.
self.resume(tid, None)
elif tid in self.down:
return
elif payload[0] == "wake":
self.resume(tid, None)
else:
_, i, value = payload
entry[2][i] = value
entry[3] += 1
if entry[3] == entry[1]:
self.resume(tid, entry[2])
# ---------------------------------------------------------------- run
def run(self, txns, crash=None, down_ticks=6, limit=5000):
"""crash: None, or (tid, "prepare") or (tid, "decided")."""
self.crash, self.down_ticks = crash, down_ticks
self.txn = {t.tid: t for t in txns}
todo = sorted(txns, key=lambda t: (t.start, t.tid))
while todo or self.coord or self.net or any(p.queue for p in self.parts):
while todo and todo[0].start <= self.tick:
t = todo.pop(0)
self.coord[t.tid] = [self.coordinator(t)]
self.resume(t.tid, None)
progress = True
while progress:
progress = False
due = sorted((m for m in self.net if m[0] <= self.tick), key=lambda m: m[1])
self.net = [m for m in self.net if m[0] > self.tick]
for _, _, dst, payload in due:
progress = True
if isinstance(dst, tuple):
self.to_coordinator(dst[1], payload)
else:
self.parts[dst].queue.append(payload)
for part in self.parts:
waiting = []
for req in part.queue:
if self.try_request(part.pid, req):
progress = True
else:
waiting.append(req)
part.queue = waiting
self.tick += 1
assert self.tick < limit, "no progress"
return self.tick
def state(self):
return {k: max(vs)[1] for k, vs in self.versions.items()}
test_clock_si.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/clock-si/. The authors are listed in prov/9E7PE4.jsonl.
import itertools
import random
import unittest
from clock_si import ClockSI, Txn
PLACE = {"a0": 0, "a1": 0, "b0": 1, "b1": 1, "c0": 2, "c1": 2}
KEYS = sorted(PLACE)
INIT = {k: 10 * i for i, k in enumerate(KEYS)}
def workload(rng):
txns = []
for tid in range(1, rng.randint(3, 6) + 1):
reads = rng.sample(KEYS, rng.randint(1, 3))
writes = rng.sample(KEYS, rng.randint(1, 3)) if rng.random() < 0.7 else []
txns.append(Txn(tid, rng.randrange(3), reads, writes, rng.randrange(10)))
return txns
def make(rng, **kw):
skews = [rng.randint(-3, 3) for _ in range(3)]
return ClockSI(PLACE, skews, INIT, rng, **kw)
def violations(db, txns):
"""The brute force oracle for snapshot isolation. It knows only the
committed writers and their timestamps, and lists every rule that the
run breaks."""
bad = []
writers = [t for t in txns if t.status == "committed" and t.writes]
def value_at(k, ts):
ws = [w for w in writers if k in w.writes and w.commit < ts]
return max(ws, key=lambda w: w.commit).writes[k] if ws else INIT[k]
for t in txns:
if len(t.reads) == len(t.read_keys):
for k, v in t.reads.items():
if v != value_at(k, t.snapshot):
bad.append(("read", t.tid, k))
for a, b in itertools.combinations(writers, 2):
if set(a.writes) & set(b.writes) and not (a.commit < b.snapshot or b.commit < a.snapshot):
bad.append(("write-write", a.tid, b.tid))
for w in writers:
if not w.commit > w.snapshot:
bad.append(("commit before snapshot", w.tid))
if db.state() != {k: value_at(k, float("inf")) for k in KEYS}:
bad.append(("final state",))
for k in KEYS: # only committed writers left versions, nothing is pending
if {tid for _, _, tid in db.versions[k]} != {0} | {w.tid for w in writers if k in w.writes}:
bad.append(("versions", k))
if db.pending[k]:
bad.append(("pending", k))
return bad
class TestClockSI(unittest.TestCase):
def test_snapshot_isolation(self):
stats = {"commit": 0, "abort": 0, "clock": 0, "pending": 0}
for seed in range(300):
rng = random.Random(seed)
db = make(rng)
txns = workload(rng)
db.run(txns)
self.assertEqual(violations(db, txns), [], seed)
stats["commit"] += sum(t.status == "committed" and bool(t.writes) for t in txns)
stats["abort"] += sum(t.status == "aborted" for t in txns)
stats["clock"] += db.delays["clock"]
stats["pending"] += db.delays["pending"]
self.assertGreater(stats["abort"], 20)
self.assertGreater(stats["clock"], 20)
self.assertGreater(stats["pending"], 20)
def test_coordinator_crash(self):
for seed in range(200):
rng = random.Random(1000 + seed)
db = make(rng)
txns = workload(rng)
victim = rng.choice(txns).tid
db.run(txns, crash=(victim, "prepare" if seed % 2 else "decided"))
self.assertEqual(violations(db, txns), [], seed)
def test_each_rule_is_needed(self):
for flag in ("clock", "pending", "max"):
broken = 0
for seed in range(300):
rng = random.Random(seed)
db = make(rng, checks={flag: False})
txns = workload(rng)
db.run(txns)
broken += bool(violations(db, txns))
self.assertGreater(broken, 0, flag)
def test_older_snapshots_wait_less(self):
delays = []
for delta in (0, 6):
total = 0
for seed in range(200):
rng = random.Random(seed)
db = make(rng, delta=delta)
txns = workload(rng)
db.run(txns)
self.assertEqual(violations(db, txns), [])
total += db.delays["clock"] + db.delays["pending"]
delays.append(total)
self.assertLess(delays[1], delays[0] / 2)
def test_messages(self):
# A read-only transaction with r remote reads sends 2 r messages; a
# distributed commit over p remote participants sends 3 p more. No
# message goes to a timestamp server.
for r in range(4):
for parts in ([1], [1, 2]):
db = ClockSI(PLACE, [0, 0, 0], INIT, random.Random(0))
reads = ["b0", "c0", "b1"][:r]
writes = ["b0", "c0"][:len(parts)]
t = Txn(1, 0, reads, writes, 0)
db.run([t])
self.assertEqual(t.status, "committed")
commit = 2 if len(parts) == 1 else 3 * len(parts)
self.assertEqual(db.messages, 2 * r + commit)
def test_clock_skew_delay(self):
# P0 is 5 ticks ahead of P1. T1 starts at P0 at tick 0 and reads b0
# on P1; the read arrives by tick 2 and waits until P1's clock passes
# the snapshot. T2 commits b0 on P1 at tick 3 with a smaller
# timestamp, so T1 must see it.
db = ClockSI(PLACE, [5, 0, 0], INIT, random.Random(0))
t1 = Txn(1, 0, ["b0"], [], 0)
t2 = Txn(2, 1, [], ["b0"], 3)
db.run([t1, t2])
self.assertEqual((t1.snapshot, t2.snapshot, t2.commit), (5000, 3001, 3011))
self.assertEqual(t1.reads["b0"], t2.writes["b0"])
self.assertEqual(db.delays["clock"], 1)
db = ClockSI(PLACE, [5, 0, 0], INIT, random.Random(0), checks={"clock": False})
t1, t2 = Txn(1, 0, ["b0"], [], 0), Txn(2, 1, [], ["b0"], 3)
db.run([t1, t2])
self.assertEqual(violations(db, [t1, t2]), [("read", 1, "b0")])
if __name__ == "__main__":
unittest.main()
History
Earlier partitioned SI systems got timestamps from a central authority. Du, Elnikety and Zwaenepoel built on work that orders events with physical clocks and showed at SRDS 2013 how to read a consistent snapshot from loosely synchronized clocks, with an analytical model of the waits and aborts that older snapshots cause, checked against their prototype.
References
- Jiaqing Du, Sameh Elnikety and Willy Zwaenepoel, Clock-SI, snapshot isolation for partitioned data stores using loosely synchronized clocks, SRDS 2013, pages 173 to 184, Section II (the model, the definition of SI and the two examples of unavailable snapshots), Section III with Algorithms 1 and 2 (read and commit protocols, older snapshots, the correctness argument), Section V (evaluation)
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 9E7PE4 Edit this page History Report an error Markdown