计算机科学 · 第 5 册 · 本科三年级

University Computer Science — Year 3

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 3 · 本科三年级

25Distributed Systems: Time, Failures and Remote Calls

The threads of the previous chapter shared one memory and one clock. Machines joined by a network share neither: each has its own memory and its own clock, and they learn about each other only from messages, which arrive late, out of step, or not at all. This chapter builds a small simulator of such machines, proves that two of them cannot even agree on a time to act when messages can be lost, makes one machine call a function on another and counts how often the call really runs, replaces the missing shared clock by counters that follow cause and effect, and takes a picture of a whole bank in which no money is lost, although no branch ever stops to have its picture taken.

You already know

A TCP connection carries a stream of bytes, in order and without loss as long as the connection lives; a socket is the program’s end of it, and a server accepts connections on a port of an address such as 127.0.0.1, the machine itself (Year 2 volume). A partial order is a relation that is irreflexive and transitive in its strict form: two elements may be incomparable. A depth-first or breadth-first search reaches every vertex of a connected graph (Year 1 volume).

25.1 No shared clock, no shared memory

Definition 25.1 (Distributed system, synchronous system, asynchronous system)

A distributed system is a set of processes that have no shared memory and no shared clock and communicate only by sending messages over channels. Each process runs a sequence of events: a local step, the sending of a message, or the receiving of one. In a synchronous system, known bounds hold on the time a message takes and on the relative speed of the processes. In an asynchronous system, there is no such bound: a message arrives after a finite but unbounded time, and a process may be slow for as long as it likes.

The difference matters most when something goes wrong. In a synchronous system, a process that waits longer than the bound for an answer knows the other side has failed. In an asynchronous system it knows nothing: the answer may still be on its way. Real networks lie between the two. Most messages arrive within milliseconds, but no fixed bound is guaranteed, and a program that assumes one will, one day, decide wrongly.

Experiments on real networks are hard to repeat: delays change from run to run. The chapter’s programs run instead on a simulator. Each process is an object that reacts to its start, to its messages and to its timers; the simulator keeps a queue of future events ordered by time, and draws every delay and every loss from a random generator with a fixed seed, so a run is the same each time.

    def send(self, src, dst, msg):
        if self.rng.random() < self.loss or (src, dst) in self.cut:
            self.log.append((self.now, "lost", src, dst, msg))
            return
        t = self.now + self.rng.randint(*self.delay)
        if self.fifo:
            t = max(t, self.last.get((src, dst), 0))
            self.last[(src, dst)] = t
        self.log.append((self.now, "send", src, dst, msg))
        self.push(t, ("deliver", src, dst, msg))
Listing 25.1. Sending a message: it may be lost; otherwise it is delivered after a random delay, never before an earlier message on the same channel when channels are FIFO. code/bachelor-3/25-distributed-systems/listings/netsim.py
    def run(self, until=10**9):
        for p in self.procs.values():
            p.on_start()
        while self.queue and self.queue[0][0] <= until:
            self.now, _, ev = heapq.heappop(self.queue)
            if ev[0] == "call":
                ev[1]()
            elif ev[0] == "deliver":
                _, src, dst, msg = ev
                if self.procs[dst].up and (src, dst) not in self.cut:
                    self.log.append((self.now, "recv", src, dst, msg))
                    self.procs[dst].on_message(src, msg)
                else:
                    self.log.append((self.now, "dropped", src, dst, msg))
            elif self.procs[ev[1]].up:
                self.procs[ev[1]].on_timer(ev[2])
        return self
Listing 25.2. The event loop: take the earliest event, deliver it to a process that is up, and log everything. code/bachelor-3/25-distributed-systems/listings/netsim.py

The simulator has no global time that the processes can read: net.now exists only to order the events, and a process that read it would be cheating. The rest of the chapter and the next one build their protocols on it.

25.2 Failures

Definition 25.2 (Crash failure, omission failure, Byzantine failure, failure detector)

A process has a crash failure when it stops and takes no further step; it may later recover, with what it had stored on disk. An omission failure is a message that is sent but never received, lost by the network or dropped by a full buffer. A Byzantine failure is any behaviour at all: a process that sends wrong values, different values to different processes, or messages it was never meant to send. A failure detector is a component that tells each process which other processes it suspects of having crashed.

Between the crash and the Byzantine failure lies the timing failure: a process or a message that is correct but too slow for the bound a synchronous system promised. Each kind contains the one before: a crashed process omits every message it should have sent, and a Byzantine process can behave as if it had crashed. Protocols are designed for a stated kind, and one that survives crashes may be helpless against a single Byzantine process.

A failure detector is usually built on timeouts: each process sends a heartbeat message every second, and a process that has heard nothing for five seconds is suspected. In an asynchronous system such a detector makes mistakes both ways: it suspects a process that is only slow, and it keeps trusting one that crashed until the timeout runs out. The next chapter shows what can still be done with such a detector; this one shows what cannot be done at all when messages can be lost.

Definition 25.3 (Two generals problem)

In the two generals problem, two generals camp on the hills on either side of a valley and can win only if they attack together. They communicate by messengers who cross the valley and may be captured. General A has a plan to attack at dawn. A protocol tells each general which messengers to send and, from the messengers it has received, whether to attack. It solves the problem if, in every run, both generals take the same decision (agreement), and if they attack in the run where no messenger is captured (the plan is not simply dropped).

The problem was first stated, and proved impossible, by Akkoyunlu, Ekanadham and Huber in 1975, with two groups of gangsters in place of the generals; Jim Gray gave it its present name in 1978.

Theorem 25.4 (The two generals)

No protocol in which every run sends finitely many messengers solves the two generals problem, if a general who has received nothing about the plan does not attack.

Proof. Suppose a protocol solves it. Let RR be the run in which no messenger is captured; it has finitely many deliveries, say dd, and both generals attack. Build runs Rd=R,Rd−1,…,R0R_d = R, R_{d-1}, \ldots, R_0: the run Rj−1R_{j-1} is RjR_j in which the last delivered messenger, mm, is captured instead, together with every messenger sent at or after the moment mm arrived. Every other delivery of RjR_j happened before that moment, of a messenger sent before it, so Rj−1R_{j-1} keeps them all and has j−1j - 1 deliveries; and up to that moment both generals receive, and so do, the same in both runs. We show by descending induction on jj that both generals attack in RjR_j. It holds for RdR_d. Assume it for RjR_j, j≥1j \ge 1, and let mm be the last messenger delivered in RjR_j, sent by general XX. In RjR_j, nothing reaches XX after mm arrives, since mm is the last delivery; in Rj−1R_{j-1}, XX receives exactly the same messengers. A general’s decision depends only on the messengers it has received, so XX decides alike in both runs: it attacks in Rj−1R_{j-1}. By agreement, the other general attacks too. In R0R_0, then, both attack; but no messenger reaches anyone in R0R_0, so B has heard nothing of the plan and does not attack. This contradiction proves the theorem. ∎

The proof never used the number of messengers: adding confirmations of confirmations only lengthens the chain of runs. The program below checks the theorem by brute force for the protocol in which messengers shuttle back and forth, each answering the last, up to kk of them. A general’s whole knowledge is then the number of messengers it received, so a protocol is a pair of tables from that number to a decision, and every pair can be tried against every run.

def runs(k):
    """(messengers received by A, by B) when messenger `lost` is captured."""
    for lost in range(1, k + 2):
        delivered = lost - 1
        yield lost, delivered // 2, (delivered + 1) // 2


def rules(views):
    """Every function from range(views) to {False, True}, as a tuple."""
    return product((False, True), repeat=views)


def check(k):
    agree_always = useful = 0
    for a, b in product(rules(k // 2 + 1), rules((k + 1) // 2 + 1)):
        if b[0]:  # B attacks without having heard of the plan
            continue
        ok = all(a[ra] == b[rb] for _, ra, rb in runs(k))
        attack_if_all_arrive = a[k // 2] and b[(k + 1) // 2]
        agree_always += ok
        useful += ok and attack_if_all_arrive
    return agree_always, useful
Listing 25.3. The runs of the shuttle with kk messengers, one for each first captured messenger, and every pair of decision tables tried against them. code/bachelor-3/25-distributed-systems/listings/generals.py
$ python generals.py
 k  protocols  always agree  and attack when no messenger is lost
 1          4             1               0
 2          8             1               0
 3         16             1               0
 4         32             1               0
 5         64             1               0
 6        128             1               0
 7        256             1               0
 8        512             1               0
Output 25.1. Among all the protocols of the shuttle, one always agrees: never attack. None also attacks when every messenger gets through.

TCP does not escape the theorem. Its closing handshake can leave one side unsure whether its last acknowledgement arrived, and the protocol settles for waiting a while and giving up. What real systems do is weaken the problem: they accept a small probability of disagreement, or a protocol that may wait forever, or both.

25.3 Remote procedure calls

Definition 25.5 (Remote procedure call, stub, marshalling, idempotent operation, at-most-once and at-least-once semantics)

A remote procedure call (RPC) runs a function in another process, usually on another machine, as if it were a local call. The caller calls a stub, a local function with the same signature, which turns the name of the function and its arguments into a message, sends it, waits for the reply and returns its result; on the server, another stub does the opposite. Turning values into a sequence of bytes that can travel is marshalling, and the reverse unmarshalling. An operation is an idempotent operation if running it twice has the same effect as running it once. A call has at-least-once semantics if, when the caller gets a reply, the function ran one or more times, and at-most-once semantics if it never runs twice for one call.

Bruce Jay Nelson is generally credited with the term, in his thesis of 1981, and Birrell and Nelson’s paper of 1984 described an implementation at Xerox PARC. A local call either returns or raises an exception; a remote one has a third outcome, silence. When no reply comes, the caller cannot tell whether the request was lost, the server crashed before running the function, after running it, or the reply was lost. Retrying covers the first case and harms the others: the function may run twice. Reading a balance is idempotent and can be retried freely; adding 10 to it is not.

The town’s bank serves deposits over TCP. A request and its reply are each one line of JSON, and every request carries an identifier, the client’s name and a counter. A server that remembers the reply to each identifier can answer a repeated request from memory.

class Handler(socketserver.StreamRequestHandler):
    def handle(self):
        srv = self.server
        for line in self.rfile:
            req = json.loads(line)  # unmarshal
            with srv.lock:
                if srv.at_most_once and req["id"] in srv.replies:
                    result = srv.replies[req["id"]]  # a duplicate: not executed again
                else:
                    result = getattr(srv.bank, req["method"])(*req["args"])
                    srv.replies[req["id"]] = result
            reply = json.dumps({"id": req["id"], "result": result}) + "\n"
            self.wfile.write(reply.encode())  # marshal
Listing 25.4. The server’s side: unmarshal a request, run it unless it is a duplicate the server remembers, marshal the reply. code/bachelor-3/25-distributed-systems/listings/rpc_server.py
    def __getattr__(self, method):
        def call(*args):
            self.n += 1
            req = {"id": f"{self.name}-{self.n}", "method": method, "args": list(args)}
            line = (json.dumps(req) + "\n").encode()  # marshal
            for attempt in range(1, self.retries + 1):
                print(f"  send {req['id']} {method}{tuple(args)} (attempt {attempt})")
                self.sock.sendall(line)
                try:
                    reply = json.loads(self.readline())  # unmarshal
                    while reply["id"] != req["id"]:  # a late reply to an earlier try
                        reply = json.loads(self.readline())
                except TimeoutError:
                    print(f"  no reply to {req['id']} in time")
                    continue
                print(f"  reply {reply['id']}: {reply['result']}")
                return reply["result"]
            raise TimeoutError(f"{req['id']}: no reply after {self.retries} attempts")

        return call
Listing 25.5. The client stub: any method name becomes a call that sends a request with a fresh identifier and retries it after half a second without a reply. code/bachelor-3/25-distributed-systems/listings/rpc_client.py

To make a reply go missing on demand, the demonstration puts a proxy between the client and the server, on 127.0.0.1:45102, which forwards everything except the second reply. The client makes three deposits of 10.

$ python rpc_demo.py
-- at-least-once server
  send c-1 deposit('bakery', 10) (attempt 1)
  reply c-1: 10
  send c-2 deposit('bakery', 10) (attempt 1)
  no reply to c-2 in time
  send c-2 deposit('bakery', 10) (attempt 2)
  reply c-2: 30
  send c-3 deposit('bakery', 10) (attempt 1)
  reply c-3: 40
deposits executed: 4, balance: 40
-- at-most-once server
  send c-1 deposit('bakery', 10) (attempt 1)
  reply c-1: 10
  send c-2 deposit('bakery', 10) (attempt 1)
  no reply to c-2 in time
  send c-2 deposit('bakery', 10) (attempt 2)
  reply c-2: 20
  send c-3 deposit('bakery', 10) (attempt 1)
  reply c-3: 30
deposits executed: 3, balance: 30
Output 25.2. Three deposits through a proxy that loses the second reply. The at-least-once server runs the retried deposit twice; the at-most-once server answers the retry from its memory.

The client’s retry is identical in both cases. Against the first server, the second deposit runs twice and the client is told the balance is 30 after two deposits; against the second, the server recognises c-2, returns the reply it had sent, 20, and the deposit runs once. At-most-once is not exactly-once: if the server crashes and loses its memory of replies, a retry runs again, and if the server never comes back, the caller never learns whether the deposit happened. Exercise 25.12 stores the memory on disk and finds what still fails.

25.4 Logical clocks

The machines’ clocks drift apart, and no message can correct them exactly, since its own delay is unknown. Leslie Lamport observed in 1978 that most programs need less than the time: they need to know which events could have influenced which.

Definition 25.6 (Happened-before relation, concurrent events, Lamport clock, vector clock)

The happened-before relation →\to on the events of a run is the smallest transitive relation such that e→fe \to f if ee comes before ff in the same process, or ee sends a message that ff receives. Two distinct events are concurrent events, written e∥fe \parallel f, if neither e→fe \to f nor f→ef \to e. A Lamport clock is a counter in each process: before each event the process adds 1 to it, a message carries the sender’s counter, and a receive first sets the counter to the larger of its own and the message’s. The value L(e)L(e) after the event is its timestamp. A vector clock keeps, in each of nn processes, a vector of nn counters: before each event, process ii adds 1 to entry ii; a message carries the sender’s vector, and a receive first takes the entrywise maximum of its own and the message’s. V(e)V(e) is the vector after the event. For vectors, u≤vu \le v means uk≤vku_k \le v_k for every kk, and u<vu < v means u≤vu \le v and u≠vu \ne v.

Happened-before is irreflexive: a run cannot contain a cycle, since a message is received after it is sent. It is a strict partial order on the events, and the events it leaves incomparable are the concurrent ones: no message chain links them, so neither could have influenced the other. The run recorded in lamport.py has three processes, eleven events and four messages.

def lamport(run):
    clock, stamp, carried = {}, {}, {}
    for e, p, kind, m in run:
        c = clock.get(p, 0)
        if kind == "recv":
            c = max(c, carried[m])
        clock[p] = stamp[e] = c + 1
        if kind == "send":
            carried[m] = stamp[e]
    return stamp
Listing 25.6. A Lamport clock replayed on a recorded run: tick at every event, and jump past the timestamp a message carries. code/bachelor-3/25-distributed-systems/listings/lamport.py
$ python lamport.py
P1 a1:1  a2:2  a3:7  a4:8
P2 b1:3  b2:4  b3:5  b4:6
P3 c1:1  c2:5  c3:9
43 pairs e -> f, and L(e) < L(f) for all of them: True
10 pairs have L(e) < L(f) without e -> f, such as c1:1 a2:2, c1:1 b1:3, c1:1 b2:4
Output 25.3. The timestamps of the run. Every pair ordered by happened-before has increasing timestamps; ten pairs have increasing timestamps although nothing links them.
A space–time diagram of the run of lamport.py: time runs to the right on each process’s line, and each arrow is a message. Each event shows its Lamport timestamp. c1 has the smaller timestamp than a2, yet no chain of messages leads from one to the other.
A space–time diagram of the run of lamport.py: time runs to the right on each process’s line, and each arrow is a message. Each event shows its Lamport timestamp. c1 has the smaller timestamp than a2, yet no chain of messages leads from one to the other.

Theorem 25.7 (Clock condition)

If e→fe \to f, then L(e)<L(f)L(e) < L(f).

Proof. Since →\to is the transitive closure of the two direct cases and << is transitive, it suffices to check them. If ee comes just before ff in the same process, the process’s counter after ee is L(e)L(e), and before ff it is at least L(e)L(e): it adds 1, possibly after raising it at a receive, so L(f)≥L(e)+1L(f) \ge L(e) + 1. Events further apart in the same process follow by induction. If ee sends a message that ff receives, the message carries L(e)L(e), and the receiver sets its counter to at least L(e)L(e) before adding 1, so L(f)≥L(e)+1L(f) \ge L(e) + 1. ∎

The converse is false, and Output 25.3 counts ten pairs that break it: L(c1)=1<L(a2)=2L(\mathrm{c1}) = 1 < L(\mathrm{a2}) = 2 although c1 and a2 are concurrent. A Lamport timestamp can say that ee did not happen after ff, never that it happened before. Vector clocks remove this gap at the price of nn counters per message; Colin Fidge and Friedemann Mattern are canonically cited for them, both in 1988, though the idea was found several times independently.

def vector_clocks(run):
    clock = {p: [0] * len(PROCS) for p in PROCS}
    stamp, carried = {}, {}
    for e, p, kind, m in run:
        v = clock[p]
        if kind == "recv":
            v = [max(x, y) for x, y in zip(v, carried[m])]
        v = v.copy()
        v[PROCS.index(p)] += 1
        clock[p] = stamp[e] = v
        if kind == "send":
            carried[m] = v
    return stamp


def before(u, v):
    """u < v: no entry larger, and the vectors differ."""
    return all(x <= y for x, y in zip(u, v)) and u != v
Listing 25.7. Vector clocks: on a receive, take the entrywise maximum, then count the event in the process’s own entry. Comparing two vectors is comparing every entry. code/bachelor-3/25-distributed-systems/listings/vclock.py
$ python vclock.py
P1 a1:[1, 0, 0]  a2:[2, 0, 0]  a3:[3, 4, 0]  a4:[4, 4, 0]
P2 b1:[2, 1, 0]  b2:[2, 2, 0]  b3:[2, 3, 0]  b4:[2, 4, 0]
P3 c1:[0, 0, 1]  c2:[2, 2, 2]  c3:[4, 4, 3]
V(e) < V(f) exactly when e -> f, over all 121 pairs: True
12 concurrent pairs: a1||c1 c1||a2 c1||b1 c1||b2 c1||b3 c1||b4 c1||a3 c1||a4 c2||b3 c2||b4 c2||a3 c2||a4
Output 25.4. The vectors of the same run. Comparing them gives happened-before exactly, and twelve pairs of events are concurrent.
The same run with vector clocks, each vector written as its three entries, (220) for [2, 2, 0]. The circled events c2 = [2, 2, 2] and b3 = [2, 3, 0] are concurrent: each vector has an entry larger than the other’s.
The same run with vector clocks, each vector written as its three entries, (220) for [2,2,0][2, 2, 0]. The circled events c2 =[2,2,2]= [2, 2, 2] and b3 =[2,3,0]= [2, 3, 0] are concurrent: each vector has an entry larger than the other’s.

Theorem 25.8 (Vector clocks characterise happened-before)

For any two events of a run, e→fe \to f if and only if V(e)<V(f)V(e) < V(f).

Proof. Facts used: the definition of →\to and of the update rule. Lemma. For every event ff and every process kk, V(f)kV(f)_k is the number of events of process kk that are →f\to f or equal to ff. By induction along the run: process kk’s own entry counts its own events, one per event. At a receive, the events that precede ff are those that precede or equal the previous event of ff’s process, together with those that precede or equal the send; their counts per process are the two vectors, and since each process’s past is a prefix of its events, the count for the union is the maximum. Then ff itself is added to its own entry. The lemma follows.

(⇒\Rightarrow) If e→fe \to f, every event that precedes or equals ee precedes ff, so V(e)≤V(f)V(e) \le V(f) by the lemma. They differ: let jj be ff’s process; ff is counted in V(f)jV(f)_j but not in V(e)jV(e)_j, since f→ef \to e would make a cycle with e→fe \to f. (⇐\Leftarrow) Suppose V(e)<V(f)V(e) < V(f). Let ii be ee’s process and ee the cc-th event of process ii, so V(e)i=cV(e)_i = c. Then V(f)i≥cV(f)_i \ge c: at least cc events of process ii precede or equal ff, and since they are a prefix, the cc-th one, ee, precedes or equals ff. It is not ff, since V(e)≠V(f)V(e) \ne V(f), so e→fe \to f. ∎

A process can use the vectors to deliver messages in an order that respects cause and effect, even when the network reorders them.

Definition 25.9 (Causal delivery)

A broadcast protocol has causal delivery if, whenever the broadcast of mm happened before the broadcast of m′m', every process delivers mm before m′m'.

The rule is short. Each process keeps a vector vv whose entry kk counts the broadcasts of process kk it has delivered, and stamps each of its own broadcasts with its vector after adding 1 to its own entry. A message from process jj stamped ww is delivered once wj=vj+1w_j = v_j + 1, the next broadcast of jj, and wk≤vkw_k \le v_k for every other kk, every broadcast the sender had delivered when it sent. Until then it waits in a buffer. Without the rule, a reply can reach a third process before the question it answers; exercise 25.6 implements it on the simulator.

25.5 Consistent snapshots

The bank of the weekend problem has five branches that send each other money. Its auditors want the total: the balances of all the branches plus the money in transit, at one instant. There is no instant to ask about, since there is no shared clock; asking each branch in turn mixes balances from different moments, and a transfer may be counted at neither end, or at both.

Definition 25.10 (Cut, consistent cut, global snapshot, channel state)

A cut of a run is a set of its events that contains, with each event, every earlier event of the same process: a prefix of each process’s events. It is a consistent cut if it also contains, with each event, every event that happened before it; equivalently, no message is received inside the cut and sent outside it. The channel state of a channel at a cut is the sequence of messages sent on it inside the cut and received outside it, the messages in transit. A global snapshot is the state of every process at a consistent cut together with the state of every channel.

Two cuts of the run, each containing the events to the left of its line. C_1 is consistent: m2 crosses it from inside to outside and is in transit. C_2 is not: b1 is inside, but a2, which sent the message b1 received, is outside.
Two cuts of the run, each containing the events to the left of its line. C1C_1 is consistent: m2 crosses it from inside to outside and is in transit. C2C_2 is not: b1 is inside, but a2, which sent the message b1 received, is outside.

A consistent cut is a state the system could have been in: the events inside it can be replayed in some order respecting →\to, and the run could have paused there. The algorithm of Chandy and Lamport, published in 1985, records one while the system runs, under two assumptions: channels are FIFO and lose nothing.

Definition 25.11 (Chandy–Lamport algorithm)

In the Chandy–Lamport algorithm, a process starts a snapshot by recording its own state and sending a special message, a marker, on each of its outgoing channels. When a process receives a marker on a channel: if it has not yet recorded its state, it records it, records the channel the marker came on as empty, sends a marker on each outgoing channel, and starts recording every other incoming channel; if it had already recorded its state, it stops recording that channel, whose state is the messages it received on it since it recorded its own state. The snapshot is complete when every process has received a marker on every incoming channel.

Theorem 25.12 (Chandy and Lamport)

On FIFO channels that lose nothing, between processes whose channels connect every process to every other, the algorithm terminates; the recorded process states lie on a consistent cut, and the recorded state of each channel is its channel state at that cut.

Proof. Facts used: FIFO order; graph search. Termination. The initiator records. A process that records sends a marker on every outgoing channel, and markers are not lost, so every neighbour of a recorded process receives a marker and records, at the latest then; since every process is reachable from the initiator, every process records, by induction along a search from the initiator. Each process then receives one marker on each incoming channel, which closes it. Consistency. Let the cut contain, for each process, the events before it recorded. Suppose a message mm from pp to qq is received inside the cut and sent outside it: qq received mm before recording, and pp sent mm after recording. When pp recorded, it sent a marker to qq before mm; by FIFO, the marker reached qq before mm, and qq recorded at the latest on receiving it, so before receiving mm, a contradiction. Channels. qq records the channel from pp between its own recording and the arrival of pp’s marker (empty if the marker caused qq to record). A message received in that window was received outside the cut, and, arriving before the marker, was sent before it by FIFO, so inside the cut: it is in transit. Conversely, a message in transit was sent before pp’s marker, so arrives before it, and was received after qq recorded: it falls in the window. ∎

For the bank, the theorem says more: the snapshot’s money is the bank’s total. At a consistent cut, a transfer sent inside the cut is either received inside it, and counted in the receiving branch’s balance, or not, and counted in the channel; one sent outside the cut is counted nowhere, since it was not yet taken from its sender, and it cannot have been received inside the cut. Every unit is counted exactly once.

Chandy–Lamport on three branches. B1 starts; the squares are the moments the branches record their balances, shown beside them, and markers are dashed. The transfer of 20, sent before B1 recorded and received before B3 did, is in B3’s recorded balance. The transfer of 30 left B2 before B2 recorded and reached B1 in the shaded stretch, after B1 recorded and before B2’s marker: it is the recorded state of the channel from B2 to B1.
Chandy–Lamport on three branches. B1 starts; the squares are the moments the branches record their balances, shown beside them, and markers are dashed. The transfer of 20, sent before B1 recorded and received before B3 did, is in B3’s recorded balance. The transfer of 30 left B2 before B2 recorded and reached B1 in the shaded stretch, after B1 recorded and before B2’s marker: it is the recorded state of the channel from B2 to B1.

The bank’s program runs 1,000 transfers of random amounts between its five branches, and starts a snapshot every five time units, 100 in all, from the branches in turn. In parallel, a naive auditor asks the branches for their balances at the same moments and adds the answers.

    def record(self, sid):
        """Record the balance, start recording every incoming channel, send markers."""
        self.snaps[sid] = {
            "balance": self.balance,
            "open": set(self.others()),
            "channels": 0,
        }
        for p in self.others():
            self.send(p, ("marker", sid))

    def on_message(self, src, msg):
        kind, x = msg
        if kind == "money":
            self.balance += x
            for s in self.snaps.values():  # money in transit when the snapshot passed
                if src in s["open"]:
                    s["channels"] += x
        elif kind == "marker":
            if x not in self.snaps:
                self.record(x)
            self.snaps[x]["open"].discard(src)  # the channel from src is now recorded
        elif kind == "report?":
            self.send(src, ("report", (x, self.balance)))
        elif kind == "report":
            self.bank.naive.setdefault(x[0], []).append(x[1])
Listing 25.8. A branch’s part of the algorithm: record and send markers; on a transfer, count it in every snapshot still recording that channel; on a marker, record if needed and close the channel. code/bachelor-3/25-distributed-systems/listings/snapshot.py
$ python snapshot.py
1000 transfers; total at the end: 5000
snapshot  0: balances [1000, 936, 931, 918, 990], in transit 225, sum 5000
snapshot 50: balances [394, 1473, 229, 893, 1766], in transit 245, sum 5000
snapshot 99: balances [181, 1529, 1203, 272, 1604], in transit 211, sum 5000
Chandy-Lamport: 100 of 100 snapshots sum to 5000; 2000 markers sent
naive: 100 of 100 are wrong, from 4320 to 4855
Output 25.5. Every Chandy–Lamport snapshot adds up to the bank’s 5,000, with 225, 245 and 211 in transit in the three printed; every naive one is short.

The naive auditor can err both ways: it counts twice a transfer that left a branch already asked and reached one asked later, and misses one that left a branch asked later and reached one asked earlier. Here the money in transit, which it never sees, outweighs both. A snapshot is of no use for knowing the balance of a branch at a given moment, since it describes a state that may never have existed all at once; it is exactly what is needed for a stable property, one that stays true once it is true, such as “every branch is idle and no transfer is in transit”, or a deadlock: a cycle of processes each waiting for the next. Exercise 25.11 proves that a snapshot sees such a property if it held when the snapshot started.

25.6 Exercises

Exercise 25.1 ★

Three processes run seven events, in this order: x1, P1 sends n1 to P2; y1, a local step of P2; z1, P3 sends n3 to P1; y2, P2 receives n1; y3, P2 sends n2 to P3; x2, P1 receives n3; z2, P3 receives n2. Draw the space–time diagram and give the Lamport timestamp of every event. Find two events whose timestamps are equal, and a pair of events with increasing timestamps that are not related by →\to.

Solution

Solution of Exercise 25.1.

P1 has x1 (send n1) then x2 (receive n3); P2 has y1, y2 (receive n1), y3 (send n2); P3 has z1 (send n3) then z2 (receive n2). Timestamps: x1, y1 and z1 are each the first event of their process, with no receive: 1. y2 receives n1 stamped 1, after y1 at 1: max⁡(1,1)+1=2\max(1, 1) + 1 = 2. y3: 3. x2 receives n3 stamped 1 after x1 at 1: 2. z2 receives n2 stamped 3 after z1 at 1: 4. Equal timestamps: x1, y1 and z1 (all 1), and y2 and x2 (both 2). y1 has 1 and x2 has 2, yet no chain of messages leads from y1 to P1: they are not related by →\to.

Exercise 25.2 ★

Give the vector clocks of the run of exercise 25.1. For each pair, say whether one happened before the other, or whether they are concurrent: (x1, z2), (x2, z2), (z1, x2), (y1, x2).

Solution

Solution of Exercise 25.2.

x1 =[1,0,0]= [1, 0, 0], y1 =[0,1,0]= [0, 1, 0], z1 =[0,0,1]= [0, 0, 1], y2 =max⁡([0,1,0],[1,0,0])= \max([0, 1, 0], [1, 0, 0]) plus 1 in entry 2 =[1,2,0]= [1, 2, 0], y3 =[1,3,0]= [1, 3, 0], x2 =max⁡([1,0,0],[0,0,1])= \max([1, 0, 0], [0, 0, 1]) plus 1 in entry 1 =[2,0,1]= [2, 0, 1], z2 =max⁡([0,0,1],[1,3,0])= \max([0, 0, 1], [1, 3, 0]) plus 1 in entry 3 =[1,3,2]= [1, 3, 2]. By Theorem 25.8: [1,0,0]<[1,3,2][1, 0, 0] < [1, 3, 2], so x1 →\to z2 (through n1 and n2); [2,0,1][2, 0, 1] and [1,3,2][1, 3, 2] are incomparable (2 > 1 in the first entry, 0 < 3 in the second), so x2 ∥\parallel z2; [0,0,1]<[2,0,1][0, 0, 1] < [2, 0, 1], so z1 →\to x2 (through n3); [0,1,0][0, 1, 0] and [2,0,1][2, 0, 1] are incomparable, so y1 ∥\parallel x2. A test checks every value.

Exercise 25.3 ★

A cut of the run of lamport.py is given by the number of events it contains on P1, P2 and P3. Which of (2,2,1)(2, 2, 1), (1,1,1)(1, 1, 1), (3,3,2)(3, 3, 2) and (4,4,2)(4, 4, 2) are consistent? For each consistent one, which messages are in transit?

Solution

Solution of Exercise 25.3.

(2,2,1)(2, 2, 1) contains a1, a2, b1, b2, c1. Its only receive, b1, receives m1 sent by a2, inside: consistent. m2 is sent inside (b2) and received outside (c2): in transit. (1,1,1)(1, 1, 1) contains b1, which receives m1 from a2, outside: inconsistent. (3,3,2)(3, 3, 2) contains a3, which receives m3 from b4, outside: inconsistent. (4,4,2)(4, 4, 2) contains everything but c3; its receives b1, c2 and a3 have their sends inside: consistent, with m4 in transit. A test checks all four.

Exercise 25.4 ★

The proxy of Output 25.2 is changed to lose the second and the third replies. Predict, for each server, how many deposits run and the final balance, and what the client is told at each call.

Solution

Solution of Exercise 25.4.

The proxy counts the replies it carries, so the lost ones are the second and third reply lines. At-least-once: c-1 runs and the client is told 10. c-2 runs (20), its reply is lost; the retry runs it again (30), its reply is lost too; the third attempt runs it a third time (40) and the client is told 40. c-3 runs: 50. Five deposits, balance 50, and the client was told 10, 40, 50. At-most-once: c-1, 10. c-2 runs once (20); both retries are answered from memory, the first answer lost, the second delivered: the client is told 20. c-3: 30. Three deposits, balance 30. A test runs both on other ports.

Exercise 25.5 ★★

vector_clocks_buggy in exercises/ex5_vclock_bug.py merges the vectors at a receive but does not add 1 to its own entry there. Find two events of the run of lamport.py to which it gives the same vector, explain why the comparison of Listing 25.7 then fails, and fix it.

Solution

Solution of Exercise 25.5.

The buggy version gives a2 and b1 the same vector, [2,0,0][2, 0, 0]: b1’s own clock is [0,0,0][0, 0, 0], the message carries [2,0,0][2, 0, 0], and nothing counts the receive. Yet a2 →\to b1, and before requires the vectors to differ, so it calls them concurrent; the lemma of Theorem 25.8 fails because b1 is not counted in P2’s entry. The fix, vector_clocks_fixed, adds 1 to the process’s own entry at every event, after the merge for a receive. A test checks that the buggy version misclassifies some pair of the run and the fixed one none.

Exercise 25.6 ★★

Implement causal broadcast on netsim with the delivery rule given after Definition 25.9, on channels that may reorder messages. P1 broadcasts three messages; P2 answers the first as soon as it delivers it. Check over 200 seeds that P3 never delivers the answer before the question, and that without the rule it sometimes does.

Solution

Solution of Exercise 25.6.

exercises/ex6_causal.py: each member keeps vv, the number of broadcasts of each member it has delivered. To broadcast, it adds 1 to its own entry, delivers its message to itself, and sends the message with a copy of vv to every other member. A received message from member jj with vector ww goes into a buffer; after each arrival, the member delivers every buffered message with wj=vj+1w_j = v_j + 1 and wk≤vkw_k \le v_k for k≠jk \ne j, adding 1 to vjv_j each time, until none qualifies. P2 is a member that broadcasts its answer as soon as it has delivered P1’s first message, so the answer carries [1,1,0][1, 1, 0], and P3 holds it until it has delivered P1’s first message. The network delays are 1 to 12 time units with FIFO order off. Over 200 seeds, P3 sees the answer before the question in 20 runs without the rule and in none with it; in 50 runs a test also checks that every member delivers all four messages.

Exercise 25.7 ★★

Order the events of a run by their Lamport timestamps, and break ties by the number of the process. Prove that this is a total order on the events, and that it extends →\to: if e→fe \to f, ee comes first. Why is it useful that every process can compute it alike?

Solution

Solution of Exercise 25.7.

Facts used: Theorem 25.7; within one process, timestamps increase strictly. Compare events by the pair (L(e),i)(L(e), i), ii the number of ee’s process, first by LL, then by ii. This is lexicographic order on pairs, a strict total order on pairs; it is total on events because distinct events have distinct pairs: on different processes the second components differ, on the same process the timestamps differ. If e→fe \to f, then L(e)<L(f)L(e) < L(f) by the clock condition, so ee comes first: the order extends →\to. Every process that knows the timestamps and process numbers of a set of events sorts them identically, with no message exchanged to agree on the order: requests for a shared resource can be served in this order by every process alike.

Exercise 25.8 ★★

Let ee and ff be distinct events and ii the process of ee. Prove that e→fe \to f if and only if V(e)i≤V(f)iV(e)_i \le V(f)_i. How many integers must be compared, instead of nn?

Solution

Solution of Exercise 25.8.

Facts used: the lemma in the proof of Theorem 25.8. (⇒\Rightarrow) If e→fe \to f, then V(e)<V(f)V(e) < V(f), so in particular V(e)i≤V(f)iV(e)_i \le V(f)_i. (⇐\Leftarrow) Let ee be the cc-th event of process ii; then V(e)i=cV(e)_i = c, and V(f)i≥cV(f)_i \ge c means at least cc events of process ii precede or equal ff. They form a prefix of process ii’s events, so the cc-th, ee, precedes or equals ff; since e≠fe \ne f, e→fe \to f. Knowing the process of ee, one comparison of two integers replaces nn. A test checks the equivalence on 200 random runs.

Exercise 25.9 ★★

How many markers does one Chandy–Lamport snapshot send among nn processes whose channels connect every process to every other? Among processes joined by cc one-way channels? Check the count printed by Output 25.5.

Solution

Solution of Exercise 25.9.

Every process records exactly once, and when it does it sends one marker on each of its outgoing channels; no other marker is sent. So a snapshot sends one marker per channel: cc markers on cc one-way channels, and n(n−1)n(n - 1) when every process has a channel to every other. For the bank, 5×4=205 \times 4 = 20 per snapshot and 2,0002{,}000 for 100 snapshots, the count printed.

Exercise 25.10 ★★★

Show, with two processes, that the Chandy–Lamport algorithm can record an inconsistent cut when a channel may reorder messages. exercises/ex10_nonfifo.py repairs it: every transfer carries the set of snapshots its sender has recorded, a process that receives a transfer tagged with a snapshot it has not recorded records before applying it, and each marker carries the number of transfers sent on its channel before the sender recorded. Prove that the repaired algorithm records a consistent cut and the right channel states, and run the file.

Solution

Solution of Exercise 25.10.

Counterexample. P starts a snapshot: it records its balance, 100, sends a marker to Q, then sends 10 to Q. The channel reorders them: the 10 arrives first, Q’s balance becomes 60 from 50, then the marker arrives and Q records 60. P recorded 100, before sending the 10; Q recorded 60, after receiving it. The recorded total is 160, against 150: the 10 is counted twice, and the cut is inconsistent, since the receive is inside it and the send outside. On the bank, ex10_nonfifo.py finds 98 of 100 snapshots wrong when channels reorder.

Repair. Facts used: channels lose nothing; every transfer carries the set of snapshots its sender had recorded when it sent it. Consistency. Suppose qq receives a transfer mm before recording snapshot ss, and pp sent mm after recording ss. Then mm carries ss, and qq, receiving a tag it has not recorded, records ss before applying mm: mm is received after qq recorded, a contradiction. Channels. The transfers from pp to qq sent before pp recorded are exactly those without the tag ss, and pp’s marker tells qq how many there are, say cc. Any of them received before qq recorded is received inside the cut; qq counts these when it records, and from then on counts every untagged transfer from pp into the channel’s state, and closes the channel once it has received cc untagged transfers in all. Since nothing is lost, all cc arrive, so the channel closes, and the recorded transfers are exactly the untagged ones received after qq recorded: sent inside the cut, received outside it. A transfer tagged with ss is never recorded, as it was sent outside the cut. The file finds 0 of 100 snapshots wrong and no channel left open, and a test repeats it on five other seeds.

Exercise 25.11 ★★★

Let SS be the global state recorded by a Chandy–Lamport snapshot, S0S_0 the state when it started and S1S_1 the state when it completed. Prove that the run’s events can be reordered, respecting →\to, into a run that passes from S0S_0 through SS to S1S_1. Deduce that if a stable property held in S0S_0, it holds in SS, and if it holds in SS, it holds in S1S_1.

Solution

Solution of Exercise 25.11.

Facts used: Theorem 25.12. Call an event pre if it happens at its process before that process records, and post otherwise. Every event before the snapshot started is pre, since every process records at or after the start; every event after it completed is post. Take the events between S0S_0 and S1S_1, and reorder them: all the pre events first, in their original order, then all the post events, in their original order. This is a valid run. Each process runs its events in the same order, since its pre events all precede its post events. A receive that is pre has a pre send, by consistency, which comes earlier in the original order and so earlier in the new run; a receive that is post has its send either pre, so earlier in the new run, or post, earlier in the original order and so in the new run. The new run starts from S0S_0 and, having run the same events, ends in S1S_1. After its pre events, each process is in the state it recorded, and each channel holds the messages sent by pre events and not yet received by pre events, which is the recorded channel state: the new run passes through SS. A stable property, once true, stays true along every run. If it held in S0S_0, it holds in SS, reached from S0S_0 in the new run; if it holds in SS, it holds in S1S_1.

Exercise 25.12 ★★★

exercises/ex12_exactly_once.py keeps the balances and the reply of every request in an SQLite file, so that the memory of replies survives a crash, and can crash before running a deposit, after running it, or after storing its reply. Run it with the deposit and the reply stored in two transactions, then in one, and explain each count. Does the second version give exactly-once semantics? Say what still fails.

Solution

Solution of Exercise 25.12.

With two transactions: a crash before running the deposit changes nothing and the retry runs it once; a crash after storing the reply is answered from the stored reply, once; but a crash after the deposit is committed and before its reply is stored leaves no trace of the request, and the retry runs the deposit again: twice. With one transaction, the deposit and its reply are committed together; a crash before the commit rolls back both, and the retry runs it once. Every case runs once. This is exactly-once for this server under three conditions. The server must come back: if it never does, the client can only give up, without knowing whether the deposit happened. The client must keep its request identifier across its own crash: a client that restarts and sends the deposit again under a new identifier gets it twice. And the effect must live in the same database as the reply: a deposit that sent money to another bank, or printed a receipt, cannot be rolled back with the transaction. The stored replies also grow without end unless clients tell the server which replies they have received.

25.7 Weekend problem

Problem 25.1

Weekend problem — The five branches of the Brenmoor savings bank

The Brenmoor savings bank has five branches, B1 to B5, each starting with 1,000. They send each other money all day, and the bank’s total, 5,000, never changes. The auditors want a picture of all the money at once, taken while the transfers go on. Listing 25.8 and Output 25.5 are the bank’s program and one day of it.

Part I — Transfers as messages.

  1. What are the processes, the messages and the channels of the bank’s system? Is it synchronous or asynchronous in the simulator?
  2. At snapshot 0, what is the sum of the five recorded balances? Where is the rest?
  3. A transfer leaves its branch at time 10 and arrives at time 14. At time 12, which balance holds it?
  4. Why does the simulator take a transfer out of the sender’s balance as soon as it is sent?
  5. With channels that lose messages, what would happen to the bank’s total? Which kind of failure is that?
  6. Could the bank make a transfer reliable over a lossy channel by retrying, and what must the receiving branch then do to avoid crediting it twice?

Part II — Clocks.

  1. Read the run of lamport.py as three branches and four transfers. Which events of P2 happened before c3?
  2. Which of P2’s events can a transfer received at c2 have been caused by?
  3. Give the Lamport timestamps of P3’s events and show a pair of events that the timestamps order but nothing links.
  4. Using the vectors of Output 25.4, decide whether b3 happened before a4.
  5. How many pairs of events of the run are concurrent, and how many are ordered?
  6. Could the auditors use Lamport timestamps alone to pick a set of states, one per branch, that is consistent? Explain.

Part III — Snapshots during the day.

  1. How many markers does the day’s run send, and how many per snapshot?
  2. How does the number of markers compare with the number of transfers, and why?
  3. At snapshot 50, what is in transit, and what is the sum?
  4. By how much are the naive totals short, at least and at most?
  5. Why is no Chandy–Lamport total short?
  6. Give a scenario in which the naive auditor counts a transfer twice.

Part IV — What a snapshot can tell.

  1. Snapshot 99 records 1,529 for B2. Did B2 hold 1,529 at the moment snapshot 99 started? Could it never have held it while the other branches held their recorded balances?
  2. Is “the total is 5,000” a stable property? Is “B2 holds more than 1,000”?
  3. At the end of the day every branch stops sending. Which stable property describes the end, and how can repeated snapshots detect it?
  4. In a system of processes that wait for each other’s messages, why is a deadlock a stable property?
  5. What does a snapshot cost the bank in messages, and does it stop any transfer?
  6. Sum up: what does the day’s run show about the two ways of auditing, and which assumption of the theorem made the difference?
Solution

Solution of Problem 25.1.

1. The processes are the five branches, the messages are the transfers (and the markers), and the channels are the 20 one-way channels between ordered pairs of branches. In the simulator every delay is between 1 and 6 time units, so the system is in fact synchronous; but nothing in the bank’s program or in the algorithm uses that bound.

2. 1,000+936+931+918+990=4,7751{,}000 + 936 + 931 + 918 + 990 = 4{,}775. The remaining 225 is in transit, recorded in the channels.

3. Neither: the money has left the sender and not yet reached the receiver. It is in the channel.

4. So that at every moment the total is the balances plus the money in transit, each unit in exactly one place, as in a bank where a transfer leaves the sending account at once.

5. A lost transfer would leave the system: the total would fall below 5,000. This is an omission failure.

6. Yes, if each transfer carries an identifier and the receiving branch remembers the identifiers it has credited, ignoring a repeated one: at-most-once on the receiving side with retries on the sending side. The sender keeps retrying until the receiver acknowledges.

7. All four, b1 to b4: b4 sends m3, received at a3, which comes before a4, which sends m4, received at c3.

8. The transfer received at c2 is m2, sent at b2: it can have been caused by b1 and b2, and through m1 by a1 and a2.

9. c1, c2, c3 have 1, 5 and 9. L(c1)=1<L(a2)=2L(\mathrm{c1}) = 1 < L(\mathrm{a2}) = 2, yet c1 and a2 are concurrent.

10. V(b3)=[2,3,0]<[4,4,0]=V(a4)V(\mathrm{b3}) = [2, 3, 0] < [4, 4, 0] = V(\mathrm{a4}), so b3 happened before a4.

11. 12 of the 55 pairs are concurrent and 43 are ordered.

12. Yes, by the clock condition: the set of events with timestamp at most tt is a consistent cut, since every event that happened before one of them has a smaller timestamp. Each branch records its state just before its clock first passes tt (a receive may jump past tt), and the transfers sent with a timestamp at most tt and received at an event with a larger one are in transit. But the branches must keep their clocks running, and an auditor cannot know when every branch has passed tt.

13. 2,0002{,}000 markers, 20 per snapshot.

14. Twice as many markers as transfers: each snapshot costs 5×4=205 \times 4 = 20 markers, and the auditors take one every 5 time units: four markers per time unit, while the 1,000 transfers spread over about 510 time units make about two per time unit.

15. 245 in transit, and the sum is 5,000.

16. Short by 145 at least and 680 at most: the naive totals range from 4,320 to 4,855.

17. By Theorem 25.12, the recorded balances lie on a consistent cut and the channels hold exactly the money in transit at that cut, so each unit is counted once.

18. The question reaches B2 first: B2 reports a balance that includes 50, then sends the 50 to B3. The question reaches B3 after the 50 has arrived, and B3’s balance includes it too. Here B2 reports from inside the cut and B3’s report includes a receive whose send is outside it.

19. B2 held 1,529 when it recorded, which was at the start only if B2 started snapshot 99, and the run starts snapshot 99 at B5. The recorded balances may never have been held all at once: the snapshot is a state the bank could have passed through, by exercise 25.11, not one it is known to have passed through.

20. The total, counting the channels, is always 5,000: it is true in every state, so it is stable. “B2 holds more than 1,000” is not stable: B2 can send money away.

21. “Every branch is idle and no transfer is in transit” is stable: nothing can then start a transfer. A snapshot sees it if it held when the snapshot started (exercise 25.11); the auditors repeat snapshots until one shows every branch idle and every channel empty, and then the property holds at the end, by the same exercise.

22. Each process of the cycle waits for a message from the next one, which sends nothing while it waits: no process of the cycle ever moves again.

23. 20 markers per snapshot, and memory for the channels being recorded. No transfer is stopped or delayed: the branches record while the transfers go on.

24. All 100 Chandy–Lamport snapshots add up to 5,000 exactly; all 100 naive audits are short, by 145 to 680. The difference comes from recording the channels and from FIFO order: exercise 25.10 finds 98 of 100 snapshots wrong on channels that reorder.

本章定义的术语

在术语表中查看全部 1050 个术语