Algorithm Search⌘K

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
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:

  1. Each transaction reads a consistent snapshot: all writes of transactions committed before its snapshot timestamp, and no other writes.
  2. Committed update transactions are in a total order given by their commit timestamps.
  3. 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.

  1. CLOCK-SI
  2. ▷ originating partition o of transaction T
  3. 1T.snapshot ← clock(o) − Δ
  4. ▷ partition q serves a read of item k by T
  5. 2if T came from another partition and T.snapshot ≥ clock(q): wait until clock(q) > T.snapshot
  6. 3if a transaction that writes k is committing or prepared at q with a timestamp < T.snapshot: wait until it is committed or aborted
  7. 4return the latest committed version of k with a timestamp < T.snapshot
  8. ▷ commit of T
  9. 5if T wrote nothing: commit at once
  10. 6if T writes one partition q: at q (after the wait of L2), certify; state committing; T.commit ← clock(q); log; install
  11. 7else send PREPARE to each partition q that T writes; q first waits as in L2
  12. 8at 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
  13. 9if every partition replied with a timestamp: T.commit ← the largest prepare timestamp; log the decision; send COMMIT(T.commit)
  14. 10at q on COMMIT: install the writes of T as versions with timestamp T.commit
  15. 11else: send ABORT to every partition that T writes

Line L2 handles a clock that is behind. If the clock of qq has not reached the snapshot, another transaction could still commit at qq with a timestamp below the snapshot, and the reader would miss it. After the wait, every later commit at qq 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.

Δ≥0\Delta \ge 0 lets a transaction read a slightly older snapshot. With a large enough Δ\Delta 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 P0P_0 has a clock 5 ticks ahead of P1P_1. A clock reading at partition pp is 1000⋅(tick+skew)+p1000 \cdot (\text{tick} + \text{skew}) + p, and two readings at one partition differ by at least 10.

tick line what happens
0 L1 T1T_1 starts at P0P_0; T1.snapshot=5000T_1.\mathrm{snapshot} = 5000; it reads b0b_0, which is on P1P_1
1 or 2 L2 the read reaches P1P_1, whose clock is 1001 or 2001, below 5000, so it waits
3 L1, L6 T2T_2 starts at P1P_1 with snapshot 3001, writes b0=200b_0 = 200 and gets the commit timestamp 3011
5 L6 the commit record of T2T_2 is on disk, and its version of b0b_0 at 3011 is installed
5 L2, L4 the clock of P1P_1 is 5001; the read goes on and returns b0=200b_0 = 200 from the version at 3011

T2T_2 committed with a timestamp below the snapshot of T1T_1, so snapshot isolation requires T1T_1 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 T1T_1 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.

  1. After a partition serves a request of TT (after the wait of line L2), every later reading of its clock is above T.snapshotT.\mathrm{snapshot}.
  2. A committed writer WW of kk with commit timestamp below T.snapshotT.\mathrm{snapshot} was certified at the partition of kk before TT read there; otherwise its timestamp there would be above the snapshot by step 1. So when TT reads, WW is pending, and line L3 waits, or it is installed.
  3. So line L4 sees exactly the committed writers below the snapshot.
  4. 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 TT, s(T)s(T) is its snapshot timestamp (line L1). For a committed writer WW, c(W)c(W) 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 kk is a pair (timestamp, value) that line L10 installs. While WW is certified at a partition and not yet installed or aborted there, WW is pending on its keys at that partition with a timestamp pp: its prepare timestamp, or its commit timestamp for a local commit. In both cases p≤c(W)p \le c(W) if WW commits.

Lemma 1 (versions). Line L10 installs a version of kk only for a committed writer WW of kk, with timestamp c(W)c(W). A pending entry of WW is removed only by its install (if WW commits) or by an abort (if WW 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. □\square

Lemma 2 (clocks after a wait). If partition qq serves a request of TT at time τ\tau, then every clock reading at qq after τ\tau is larger than s(T)s(T).

Proof. If qq is not the origin of TT, line L2 serves the request only when the clock of qq is above s(T)s(T), and later readings are larger still. If qq is the origin, s(T)s(T) is a reading at qq minus Δ≥0\Delta \ge 0, taken before τ\tau, and later readings are larger. □\square

Lemma 3 (commit after snapshot). Every committed writer WW has c(W)>s(W)c(W) > s(W).

Proof. Each prepare timestamp and each local commit timestamp is a reading at a partition that has served a request of WW (line L2 applies to prepare and to a remote local commit), so by Lemma 2 it is above s(W)s(W). The commit timestamp is one of these readings or their maximum. □\square

Theorem 1 (consistent snapshot). When partition qq serves a read of kk by TT at line L4, it returns the value written by the committed writer WW of kk with the largest c(W)<s(T)c(W) < s(T) (the initial value if there is none).

Proof. Let WW be any committed writer of kk with c(W)<s(T)c(W) < s(T), and let τ\tau be the time of the read. If WW was certified at qq before τ\tau, then at τ\tau it is installed or still pending with timestamp p≤c(W)<s(T)p \le c(W) < s(T). A pending entry like this makes line L3 wait, so at τ\tau it is installed. If WW was certified at qq after τ\tau, its timestamp at qq is a reading after τ\tau, so it is above s(T)s(T) by Lemma 2. Then c(W)≥p>s(T)c(W) \ge p > s(T), which is false. So every committed writer of kk with commit timestamp below s(T)s(T) has its version on qq at time τ\tau, and by Lemma 1 no other transaction has a version there. Line L4 takes the version with the largest timestamp below s(T)s(T), which is the version of the writer with the largest c(W)<s(T)c(W) < s(T). ■\blacksquare

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 AA and BB both write kk, then c(A)<s(B)c(A) < s(B) or c(B)<s(A)c(B) < s(A).

Proof. Both are certified at the partition qq of kk (line L8), in atomic steps. Say AA is certified first. When BB is certified, AA is pending at qq or installed (Lemma 1, since AA commits). If AA is pending, line L8 rejects BB. So AA is installed with timestamp c(A)c(A), and line L8 accepts BB only if c(A)<s(B)c(A) < s(B). ■\blacksquare

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. ■\blacksquare

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 WW prepare xx on P1P_1 at timestamp 10 and yy on P2P_2 at timestamp 30, and commit with timestamp 10. A reader with snapshot 20 reads yy on P2P_2: the pending entry there has timestamp 30>2030 > 20, so the read does not wait and returns the old yy. It reads xx on P1P_1 after the install and gets the new xx, since 10<2010 < 20. The snapshot has half of WW. The tests find such runs when the maximum is replaced by the minimum.

Theorem 4 (messages). A transaction that reads rr items on partitions other than its origin sends 2r2r 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 pp 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. ■\blacksquare

Complexity

Let rr be the number of items that a transaction reads on other partitions and pp the number of partitions it writes. The reads take 2r2r 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, Δ=6\Delta = 6 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 Δ\Delta per transaction. Δ=0\Delta = 0 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.

clock_si.pyI0RawGitHub
# 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

  1. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of space.extra
  • a full proof of messages.best
  • a full proof of messages.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW0 stub
  • complexity claims in the front matter