Algorithmadvanced
Chandy-Misra-Haas edge chasing
Also called edge chasing, probe-based distributed deadlock detection.
Detects a deadlock spread over sites by sending small probes along the wait-for edges between sites. A probe that comes back to its initiator shows a cycle of waiting processes.
- Solves
- Cycle detection
- Space
- O(n p) extra
- Counts
- messages e(e + 1) worst
- Where
- e = the number of wait-for edges between processes at different sites; n = the number of processes at one site; p = the number of processes in the system
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- K. Mani Chandy, Jayadev Misra, Laura M. Haas, 1983
The Chandy-Misra-Haas algorithm finds deadlocks in a distributed database without building the global wait-for graph anywhere. Each site knows only its own lock table. When a process has waited for some time, its site starts a probe computation: it sends a short fixed-size message, a probe, along each wait-for edge that leaves the site. A site that gets a probe for a process that still waits passes it on along the edges that leave that site. If a probe comes back to the process that started it, the process is on a cycle of waiting processes, and it is deadlocked. The method is also called edge chasing, because the probes chase the edges of the graph. The paper proves that, if no transaction aborts while probes are in flight, the algorithm reports every deadlock and no false one.
In plain words
People wait in queues at several offices, and each person can wait for a person in another office. Nobody can see all the queues. If you have waited for a long time, you write your name on a card and give it to the person you wait for. That person, if still waiting, passes your card to the person they wait for, and so on. A person who is not waiting throws the card away. If your own card comes back to you, there is a ring of people who all wait for each other, and none of them will ever move.
Each card is small and the same size, and each person needs to remember only whose cards they have passed on.
The problem
The model is the resource model of Chandy, Misra and Haas (1983), Section 2.1. Each site has a controller that manages the resources at the site with exclusive locks. A transaction has a home process at its home site and at most one agent at each other site . For a resource at another site, the home controller sends the request to the agent, which asks its own controller and replies when it has the resource. Channels between sites are first in, first out, and messages are not lost, as in the asynchronous model with FIFO delivery.
A process is idle while it waits. The wait-for edges are:
- a local edge when waits at for a resource that holds at ;
- a remote edge when the home process waits for the reply of the agent at ;
- a remote edge when the agent holds resources at and waits for its home process to tell it to release them.
The paper defines to be dependent on when a chain of idle processes leads from to , each waiting for the next, and locally dependent when the whole chain is at one controller. A process is deadlocked when it is on a cycle of such waits, or depends on a process that is. The task is to declare a process deadlocked if and only if it is on a cycle, with only local knowledge at each controller. Let be the set of processes that reaches by local edges, with itself.
The third kind of edge is not spelled out in the paper. The code adds it, because without it a cycle can pass through an agent that holds a resource and seems to be executing, and then the detector misses a real deadlock.
The algorithm
INITIATE(i) ▷ at the controller of an idle process P_i- 1
if P_i is on a cycle of local edges then declare P_i deadlocked and stop - 2
m_i ← m_i + 1 ▷ the number of this computation - 3
for each P_a in LD*(P_i) and each P_b at another site such that P_a waits for P_b do - 4
send probe(i, m_i, a, b) to the controller of P_b RECEIVE-PROBE(i, m, j, k) ▷ at the controller of P_k- 5
if P_k is idle and P_k has not answered P_j and dependent_k(i) < m then - 6
dependent_k(i) ← m - 7
if P_i is in LD*(P_k) then declare P_i deadlocked - 8
else for each P_a in LD*(P_k) and each P_b at another site such that P_a waits for P_b do - 9
send probe(i, m, a, b) to the controller of P_b WHEN P_k STOPS BEING IDLE- 10
clear dependent_k
A probe belongs to computation number of the initiator , and goes from at one site to at another. The flag dependent means that the controller of knows that depends on . A probe that fails the test of line L5 is dropped. The test "has not answered " is condition (iii) of the paper: if is an agent, the request of its home is still waiting; if is a home process, it has not sent a new request to the agent , which would answer the wait of the agent.
The code differs from Section 3.1 of the paper in two places, and the page shows why:
- The declaration test. The paper declares when . Line L7 also declares when is in , that is, when the probe comes back to the site of through a remote edge that ends at another process. The option literal=True of the code uses the test of the paper.
- Numbered computations. The paper keeps a Boolean flag. The code keeps the number of the last computation, as the query computations of Section 4 of the paper do.
The paper does not say when to start a computation. Section 5 suggests starting one only for a process that has been idle for some time . The code starts one when a process becomes idle, at a random later step, and again for every idle process when no message is in transit.
Example
Two sites, and the test . Transaction 1 has its home at and holds there. Transaction 2 has its home at and holds there. Then 1 asks for and 2 asks for . The cycle is
with remote edges from each home process to its agent and local edges from each agent to the home process of the other transaction. starts a computation for . It sends probe to . There the agent waits for , held by , which waits for its agent at , so sends probe back to . The probe arrives at , not at . With line L7, sees that is in and declares it deadlocked after 2 probes. With the test , passes the probe on along the edge from to again, and drops it because the flag is set: 3 probes and no declaration. A computation for , the end of a remote edge, finds the cycle with either test.
Three sites, and the numbers. Transaction has its home at and holds a resource there. Transaction 1 asks for the resource of 2, and 2 asks for the resource of 3, while 3 is still running. A computation for sets flags at and , and stops, because is not idle. Then 3 asks for the resource of 1, and the cycle closes. A second computation for with Boolean flags is dropped at , and the deadlock is never reported for . With numbers, the second computation passes and declares .
Correctness
The proofs are on the proof page. They assume, as the paper does in Section 3, that no transaction aborts while a computation runs.
- No false deadlocks (theorem). When a process is declared, it is on a cycle of the true wait-for graph. The key facts are that the target of a wait edge must stop being idle before the edge can go away, so chains of waits ending at an idle process are stable, and that first in, first out channels keep a probe behind the request or the reply that it follows.
- Every cycle is found (theorem). If a computation for starts while is on a cycle, is declared by it or by a later computation. With the test , this holds only when the edge of the cycle that enters is a remote edge.
- Measurements. The tests compare every declaration with a global wait-for graph built from all controllers at once. In 150 random runs on 3 sites with 3 to 5 transactions, while other transactions still move and change the graph, all 652 declarations were of processes on a cycle, and each of the 95 runs that ended in a deadlock had a declared process on each cycle. In 739 single computations on frozen graphs, a process was declared exactly when it was on a cycle (405 times).
Proof: Edge chasing declares only processes on a wait cycle, and finds every cyclefull
We use the line numbers of the pseudocode on the page, the rule of line L7 with the extension (declare when ), and numbered computations. The model is the resource model of the page, as in the code.
The model. Each site has a controller. A transaction has a home process and at most one agent at each other site . The home process asks for one resource at a time. Channels are first in, first out, and messages are not lost. No transaction aborts while a probe computation runs; this is the assumption of Section 3 of Chandy, Misra and Haas (1983), and the page discusses what happens without it. The true wait-for graph at a moment has a node for each idle process and these edges between idle processes:
- if waits at for a resource that holds at (a local edge);
- if the home process has a request to that is not yet answered (a remote edge);
- if the agent holds resources at , waits for none, and no request from the home to is in transit or waiting (a remote edge).
A process is idle when it has an out-edge in this sense: a waiting agent, a home process with an open request, or an agent that holds resources and has nothing to do. depends on if has a path from to . is the set of processes that reaches by local edges, with . The controller of computes it from its own lock table.
Lemma 1 (stability). If is an edge of , the edge stays in while stays idle. So a path of stays in while stays idle, and a cycle of stays forever.
Proof. Look at what removes each kind of edge. A local edge goes away only when releases the resource at , which happens when the home of commits or when the agent gets the release from its home; in both cases stops being idle in that step. An edge goes away when the reply of the agent arrives, and the agent sent it when it got the resource, so it stopped waiting before. An edge goes away when the home sends a release, a new request or an abort to , and the home is executing when it does this. So the target of an edge always leaves the idle state first. The path claim follows by induction from the end of the path: stays while is idle, so stays idle, and so on. On a cycle every node is the target of an edge, so no node can be the first to leave.
Lemma 2 (a probe carries a true dependency). Let the controller of send probe at time , at a moment when depends on or equals , and is idle. If the controller of accepts it at time (line L5), then at the edge is in , has been idle since , and depends on .
Proof. There are two cases for the edge that the controller of saw.
From a home to an agent. At the home has an open request to the site of . The probe goes on the same channel as the request and after it. Line L5 accepts only if waits at its controller. That wait is for this request: a later request needs a reply first, the reply needs the grant, and a later request would be behind the probe on the channel. So the request was open during the whole interval , was idle, and at the edge is in .
From an agent to its home. At the agent holds resources and waits for none. Line L5 accepts only if the home is idle and has no open request to the site of . Suppose the home sent a request to that site at some time before and after the last reply of . If the request is still open at , the probe is dropped. If it was answered, the answer came after the request reached ; if the request reached after , the answer is behind the probe on the channel and cannot have arrived; if it reached before , then was not free at , a contradiction. So no request went from to in , did not commit or abort (it is idle), and held its resources and waited for during the whole interval. At the edge is in .
In both cases stayed idle from to . By Lemma 1, the path from to that existed at is still in at . With the edge , depends on .
Lemma 3 (the flags). At all times, if the controller of holds dependent, then is idle and depends on .
Proof. The flag is set only at line L6, where is idle and, by Lemma 2, depends on . While stays idle the path stays, by Lemma 1. When leaves the idle state, line L10 clears all its flags. For the probes that forwards at line L9: they start at some , so depends on , and is idle; this is the premise of Lemma 2 for the next step. The probes of line L4 satisfy it because .
Theorem 1 (no false deadlocks). If a process is declared deadlocked, then at that moment is on a cycle of . With no aborts, it then stays deadlocked forever.
Proof. At line L1 the controller sees a cycle of local edges through . At line L7, the flag dependent was just set, so depends on by Lemma 3, and gives a path back from to . The literal rule is the special case . The cycle stays by Lemma 1.
Theorem 2 (every cycle is found). If a computation for starts (line L2) while is on a cycle of , then is declared deadlocked, by this computation or by a later computation for .
Proof. If the cycle has no remote edge, line L1 declares . Otherwise write the cycle as , where each is a remote edge and each is a path of local edges. The cycle stays forever by Lemma 1, so each is in (with ) at all later times, and each controller sees the edge .
We show by induction on that the flag dependent is set to or to a larger number at some time, and that at the moment it is set to some number , the controller of checks line L7 and, if it does not declare, sends probe. For this is line L3. For the step, the probe arrives at . The process is idle forever, and the remote edge stays, so the condition on replies in line L5 holds. If the flag of is less than , the probe is accepted. If it is already at least , it was set by a probe of a computation numbered at least , and the claim holds for that number. Flags of are never cleared, because never leaves the idle state.
For : when the flag of is set, , so line L7 declares .
With the literal rule , the last step needs , that is, the edge of the cycle that enters must be a remote edge. If it is a local edge, the probes go round the cycle and are dropped at , whose flag is already set; the test file has such a case with two sites. A computation for , the end of any remote edge on the cycle, still finds the cycle with the literal rule. So if the system starts a computation for every idle process, as the code does when no message is in transit, both rules find every cycle.
Without numbers. If the flag is a Boolean, as in the paper, Theorem 2 needs the flag of to be false when the computation starts. A computation for that ran before the cycle closed can leave a flag at a process that stays idle, and this flag stops every later probe for at that process. The test file has such a case with three sites. The numbers of line L2 remove the problem, and they do not change Lemma 3.
Theorem 3 (messages). Suppose that the wait-for graph does not change while a computation runs, and let be the number of remote edges that start at idle processes. Then the computation sends at most probes, and each probe has four fields.
Proof. A probe is accepted at its target, the end of a remote edge, and a target accepts a computation at most once, because its flag keeps the number and is not cleared. So at most processes accept, and each of them, and the initiator, sends at most one probe for each remote edge that starts in its set , at most probes.
Complexity
- Messages. If the graph does not change during a computation, each process accepts the computation at most once, so at most processes and the initiator forward probes, each at most one per remote edge: at most probes. The paper, Section 5, states a bound of probes, where is the number of pairs of processes that communicate. In the code, two processes at one site can forward the same probe, and on frozen graphs a computation sent at most 7 probes and at most 1.5 times the number of remote edges.
- Message size. A probe has four fields, the initiator, the number, the sender and the receiver, whatever the size of the graph.
- Space. A controller keeps, for each of its processes, a number per initiator: . It also keeps the number of the last computation of each of its own processes.
- Time. A probe moves one remote edge per message delay, so a computation that finds a cycle with remote edges takes delays.
Properties
- No central site. No controller builds the global graph. Each one answers a probe from its own lock table.
- Work only when processes wait. Probes are sent only for idle processes, and a running process drops them. Section 5 of the paper points out that the cost of detection falls on idle processes.
- Many initiators per cycle. Every process on a cycle can start a computation, and each can declare itself. If each declaration aborts a victim, one cycle can lose several transactions.
- Phantom deadlocks with aborts. The proofs assume no aborts during a computation. With victims, a probe that is in flight when a victim aborts can still close a cycle that no longer exists. In 150 random runs with victims, 58 of 232 declarations were of a process that was no longer on a cycle. Every such case came after an earlier declaration in the same run, no transaction stayed waiting, and 387 transactions committed.
Variants and improvements
- The communication model. Section 4 of the paper handles processes that wait for a message from any one process of a set, as in CSP. Deadlock is then a knot, not a cycle, and the algorithm uses query and reply messages, in the style of the Dijkstra-Scholten algorithm for termination detection.
- Probes sent once. A controller that remembers which probes of a computation it has already sent can skip duplicates, and then a computation on a frozen graph sends at most one probe per remote edge.
- One initiator per cycle. If the transactions have priorities and a site passes on only the probes of initiators with a higher priority than the process that the probe reaches, only the process with the highest priority on a cycle can complete a computation. Then each cycle gives one declaration. This idea is a heuristic: with aborts during a computation, phantoms can still occur.
- Path pushing. Obermarck (1982), cited by the paper, sends whole paths of the wait-for graph between sites instead of fixed-size probes. The messages are larger, and the sites can see which transactions form the cycle.
- Avoiding detection. Timestamp rules such as wait-die and wound-wait prevent cycles, at the cost of some aborts that are not needed. Many systems also use timeouts.
When to use it
Use edge chasing when locks are kept by many sites, as in primary copy locking or read-one write-all, deadlocks are rare, and you do not want a central detector that collects the lock tables. Start computations only for processes that have waited for some time, so that short waits cost nothing. If deadlocks are frequent, or if a wrong abort is expensive, a central detector or a prevention rule can be simpler.
Pitfalls
- The declaration test. With the test alone, a computation for a process whose cycle comes back through a local edge never reports it. Either check as in line L7, or start computations for every waiting process.
- Stale flags. Boolean flags that stay set at a process that stays idle can stop a later computation for the same initiator. Number the computations.
- Hidden waits. An agent that holds a resource for its transaction looks busy at its own site, but it cannot release the resource until its home tells it to. Leaving out this wait hides real deadlocks.
- Channels that reorder. Lemma 2 of the proof needs a probe to stay behind the request or the reply that it follows on the same channel. On a network that reorders messages, a probe can arrive before the request it is about and be dropped, or arrive after a reply and close a cycle that is gone.
- Aborts during a computation. Probes in flight can name a cycle that an abort has broken. Treat a declaration as a reason to abort only if the transaction is still waiting, and expect some victims that were not needed.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chandy-misra-haas/. The authors are listed in prov/H4QN6P.jsonl.
"""Chandy-Misra-Haas edge chasing for the resource model.
A small simulation in one thread of the resource model of Chandy, Misra and
Haas (1983), Section 2.1. Each site has a controller that manages the
resources at the site. A transaction t has a home site h and at most one
process per site; the process (t, s) is named by the pair. The home process
asks for resources one at a time. A resource at the home site is asked of
the home controller. For a resource at another site m, the home controller
sends the request to the process (t, m), which asks its own controller, and
which replies when it gets the resource. All locks are exclusive, and the
queue of each resource is first in, first out.
Wait edges:
local (u, s) -> (h, s) the process (u, s) waits for a resource that the
transaction h holds at s;
remote (t, h) -> (t, m) the home process waits for the reply of (t, m);
remote (t, m) -> (t, h) the agent (t, m) has replied and holds resources
at m, and it waits for the home process to tell
it to release them.
A process is idle while it waits. The home process is executing between
two requests, and it stops waiting when it commits or aborts. Without the
third kind of edge, a cycle can pass through an agent that holds a resource
and looks executing, and the detector misses a real deadlock.
The probe computation is that of Section 3.1, with two changes that the
page explains: each computation has a number, so that a later computation
by the same process is not stopped by the flags of an earlier one, and with
literal=False a controller also declares P_i deadlocked when P_i is locally
dependent on the process that the probe reaches.
The network delivers messages in an order chosen by a seeded random.Random,
first in, first out on each channel (one ordered pair of sites).
"""
class Controller:
def __init__(self, sid):
self.sid = sid
self.holder = {} # resource -> transaction that holds it
self.queue = {} # resource -> [transaction] waiting, in order
self.waiting = {} # transaction -> resource its process here waits for
self.held = {} # transaction -> set of resources held here
self.dependent = {} # process (t, sid) -> {initiator: computation number}
self.aborted = set()
class Txn:
def __init__(self, tid, home, plan):
self.tid = tid
self.home = home
self.plan = list(plan) # [(resource, site)]
self.i = 0
self.status = "active" # active, committed, aborted
self.outstanding = None # site of the remote request not yet answered
self.contacted = set()
class CMH:
def __init__(self, sites, literal=False, numbered=True, resolve=True, timers=True):
self.ctl = {s: Controller(s) for s in sites}
self.literal = literal
self.numbered = numbered
self.resolve = resolve
self.timers = timers
self.txns = {}
self.net = [] # (src, dst, payload)
self.seq = {} # initiator -> number of its last computation
self.messages = 0
self.probes = 0
self.declared = [] # processes declared deadlocked, in order
self.on_declare = None # test hook, called with the process
# ------------------------------------------------------------ network
def send(self, src, dst, payload):
if src != dst:
self.messages += 1
if payload[0] == "probe":
self.probes += 1
self.net.append((src, dst, payload))
def deliver(self, k):
chan = self.net[k][:2]
k = next(j for j, m in enumerate(self.net) if m[:2] == chan) # FIFO per channel
src, dst, payload = self.net.pop(k)
getattr(self, "on_" + payload[0])(self.ctl[dst], src, *payload[1:])
def drain(self, rng, hold=lambda msg: False):
"""Deliver messages in a random order until none is left, or all
that are left are held by the caller."""
while True:
heads, seen = [], set()
for k, m in enumerate(self.net):
if m[:2] not in seen: # the first message of each channel
seen.add(m[:2])
if not hold(m):
heads.append(k)
if not heads:
return
self.deliver(heads[rng.randrange(len(heads))])
# ------------------------------------------------------ process state
def idle(self, p):
# Only the state of the controller of p: its waiting table, and for
# a home process the request that it has sent and not seen answered.
t, s = p
c = self.ctl[s]
if t in c.waiting:
return True
tx = self.txns.get(t)
if tx is None:
return False
if s == tx.home:
return tx.status == "active" and tx.outstanding is not None
return bool(c.held.get(t)) # it has replied and waits for the release
def local_reach(self, k):
"""LD*(k): the idle processes that k reaches by local wait edges,
with k itself. Uses only the state of the controller of k."""
s = k[1]
c = self.ctl[s]
seen, stack = [k], [k]
while stack:
u = stack.pop()[0]
if u in c.waiting:
h = (c.holder[c.waiting[u]], s)
if self.idle(h) and h not in seen:
seen.append(h)
stack.append(h)
return seen
def on_local_cycle(self, i):
s = i[1]
c = self.ctl[s]
u = i[0]
if u not in c.waiting:
return False
h = (c.holder[c.waiting[u]], s)
return self.idle(h) and i in self.local_reach(h)
def remote_edges(self, procs):
out = []
for a in procs:
t = self.txns[a[0]]
c = self.ctl[a[1]]
if a[1] == t.home:
if t.status == "active" and t.outstanding is not None:
out.append((a, (a[0], t.outstanding)))
elif a[0] not in c.waiting and c.held.get(a[0]):
out.append((a, (a[0], t.home)))
return out
def became_executing(self, p):
self.ctl[p[1]].dependent.pop(p, None) # @line L10
def became_idle(self, p):
if self.timers:
self.send(p[1], p[1], ("timer", p))
# ----------------------------------------------------- probe computation
def initiate(self, i):
if not self.idle(i):
return
if self.on_local_cycle(i): # @line L1
self.declare(i)
return
m = self.seq.get(i, 0) + 1 # @line L2
self.seq[i] = m
for a, b in self.remote_edges(self.local_reach(i)): # @line L3
self.send(i[1], b[1], ("probe", i, m, a, b)) # @line L4
def on_probe(self, ctl, src, i, m, j, k):
dep = ctl.dependent.setdefault(k, {})
fresh = dep.get(i, 0) < m if self.numbered else i not in dep
# (iii): k has not replied to j. If k is an agent, j is its home and
# the request of j still waits here. If k is the home, j is an agent
# that waits for the home; a new request to j answers that wait, so
# the probe is stale if k has a request out to the site of j.
t = self.txns[k[0]]
if k[1] == t.home:
unanswered = t.outstanding != j[1]
else:
unanswered = k[0] in ctl.waiting
if not (self.idle(k) and unanswered and fresh): # @line L5
return
dep[i] = m # @line L6
reach = self.local_reach(k)
if k == i or (not self.literal and i in reach): # @line L7
self.declare(i)
return
for a, b in self.remote_edges(reach): # @line L8
self.send(k[1], b[1], ("probe", i, m, a, b)) # @line L9
def declare(self, i):
self.declared.append(i)
if self.on_declare:
self.on_declare(i)
if self.resolve:
t = self.txns[i[0]]
self.send(i[1], t.home, ("abort", t.tid))
def on_timer(self, ctl, src, p):
self.initiate(p)
# --------------------------------------------------- the transactions
def start(self, tid, home, plan):
t = Txn(tid, home, plan)
self.txns[tid] = t
self.step(t)
def step(self, t):
if t.i == len(t.plan):
self.commit(t)
return
res, s = t.plan[t.i]
if s == t.home:
self.lock(self.ctl[s], t.tid, res)
else:
t.outstanding = s
t.contacted.add(s)
self.send(t.home, s, ("request", t.tid, res))
self.became_idle((t.tid, t.home))
def lock(self, ctl, tid, res):
"""The process (tid, ctl.sid) asks its controller for res."""
if ctl.holder.get(res) is None:
self.grant(ctl, tid, res)
else:
ctl.queue.setdefault(res, []).append(tid)
ctl.waiting[tid] = res
self.became_idle((tid, ctl.sid))
def grant(self, ctl, tid, res):
ctl.holder[res] = tid
ctl.held.setdefault(tid, set()).add(res)
ctl.waiting.pop(tid, None)
self.became_executing((tid, ctl.sid))
t = self.txns[tid]
if ctl.sid == t.home:
self.send(ctl.sid, ctl.sid, ("next", tid))
else:
self.send(ctl.sid, t.home, ("granted", tid, res))
def unlock_all(self, ctl, tid):
ctl.waiting.pop(tid, None)
for res in list(ctl.queue):
ctl.queue[res] = [u for u in ctl.queue[res] if u != tid]
for res in sorted(ctl.held.pop(tid, ())):
ctl.holder[res] = None
if ctl.queue.get(res):
self.grant(ctl, ctl.queue[res].pop(0), res)
self.became_executing((tid, ctl.sid))
def on_request(self, ctl, src, tid, res):
if tid in ctl.aborted:
return
self.lock(ctl, tid, res)
def on_granted(self, ctl, src, tid, res):
t = self.txns[tid]
if t.status != "active":
return
t.outstanding = None
self.became_executing((tid, t.home))
self.send(ctl.sid, ctl.sid, ("next", tid))
def on_next(self, ctl, src, tid):
t = self.txns[tid]
if t.status != "active":
return
t.i += 1
self.step(t)
def commit(self, t):
t.status = "committed"
self.unlock_all(self.ctl[t.home], t.tid)
for s in sorted(t.contacted):
self.send(t.home, s, ("release", t.tid))
def on_release(self, ctl, src, tid):
self.unlock_all(ctl, tid)
def on_abort(self, ctl, src, tid):
t = self.txns[tid]
if ctl.sid == t.home:
if t.status != "active":
return
t.status = "aborted"
t.outstanding = None
self.unlock_all(ctl, tid)
for s in sorted(t.contacted):
self.send(t.home, s, ("abort", tid))
else:
ctl.aborted.add(tid)
self.unlock_all(ctl, tid)
# ---------------------------------------------------------------- run
def run(self, rng, txns, auto=True):
"""txns: {tid: (home, plan)}. Start all, deliver until quiet. When
nothing is in transit and auto is set, start a probe computation
for every idle process, and go on while this finds deadlocks.
Returns the transactions that are still active at the end."""
for tid in sorted(txns):
self.start(tid, *txns[tid])
while True:
self.drain(rng)
stuck = sorted(p for t in self.txns.values() for p in self.processes(t) if self.idle(p))
if not stuck or not auto:
break
before = len(self.declared)
for p in stuck:
self.initiate(p)
self.drain(rng)
if len(self.declared) == before or not self.resolve:
break
return sorted(t.tid for t in self.txns.values() if t.status == "active")
def processes(self, t):
return [(t.tid, s) for s in sorted({t.home} | t.contacted)]
test_chandy_misra_haas.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chandy-misra-haas/. The authors are listed in prov/H4QN6P.jsonl.
import random
import unittest
from chandy_misra_haas import CMH
SITES = ["S1", "S2", "S3"]
def wait_graph(db):
"""The global wait-for graph of idle processes, built from the raw
state of all controllers at once. The algorithm never sees this."""
idle = set()
for s, c in db.ctl.items():
for t in c.waiting:
idle.add((t, s))
for t, held in c.held.items():
tx = db.txns[t]
if held and s != tx.home and t not in c.waiting and tx.outstanding != s:
idle.add((t, s)) # an agent waiting for its home
for t in db.txns.values():
if t.status == "active" and t.outstanding is not None:
idle.add((t.tid, t.home))
edges = {p: [] for p in idle}
for t, s in idle:
c, tx = db.ctl[s], db.txns[t]
if t in c.waiting:
nxt = (c.holder[c.waiting[t]], s)
elif s == tx.home:
nxt = (t, tx.outstanding)
else:
nxt = (t, tx.home)
if nxt in idle:
edges[(t, s)].append(nxt)
return edges
def on_cycle(edges, p):
if p not in edges:
return False
seen, stack = set(), list(edges[p])
while stack:
u = stack.pop()
if u == p:
return True
if u not in seen:
seen.add(u)
stack.extend(edges[u])
return False
def reaches(edges, p, q):
seen, stack = set(), [p]
while stack:
u = stack.pop()
if u == q:
return True
if u not in seen:
seen.add(u)
stack.extend(edges[u])
return False
def remote_edge_count(db):
"""Wait edges between controllers that start at an idle process."""
e = sum(1 for t in db.txns.values() if t.status == "active" and t.outstanding is not None)
for s, c in db.ctl.items():
e += sum(1 for t, held in c.held.items()
if held and t not in c.waiting and s != db.txns[t].home)
return e
def random_txns(rng):
where = {"r%d" % j: rng.choice(SITES) for j in range(5)}
txns = {}
for tid in range(1, rng.randint(3, 5) + 1):
plan = [(r, where[r]) for r in rng.sample(sorted(where), rng.randint(2, 3))]
txns[tid] = (rng.choice(SITES), plan)
return txns
def cross_cycle():
"""T1 at S1 holds a, T2 at S2 holds b, T1 asks for b and T2 asks for a.
The cycle is (1,S1) -> (1,S2) -> (2,S2) -> (2,S1) -> (1,S1), and the
edge into (1,S1) is local."""
return {1: ("S1", [("a", "S1"), ("b", "S2")]),
2: ("S2", [("b", "S2"), ("a", "S1")])}
class TestCMH(unittest.TestCase):
def check_sound(self, literal):
# No victims: a deadlock stays, and the other transactions go on and
# change the wait-for graph while probes are in flight. Every
# declaration must be a process on a cycle at that moment, and every
# cycle left at the end must have a declared process.
found = 0
for seed in range(150):
rng = random.Random(seed)
db = CMH(SITES, literal=literal, resolve=False)
def hook(p, db=db):
self.assertTrue(on_cycle(wait_graph(db), p), (seed, p))
db.on_declare = hook
db.run(rng, random_txns(rng))
edges = wait_graph(db)
for p in edges:
if on_cycle(edges, p):
comp = {q for q in edges if on_cycle(edges, q) and reaches(edges, p, q)}
self.assertTrue(comp & set(db.declared), (seed, p))
found += len(db.declared)
self.assertGreater(found, 100)
def test_no_false_deadlocks_and_every_cycle_found(self):
self.check_sound(literal=False)
def test_literal_rule_with_every_idle_process_initiating(self):
self.check_sound(literal=True)
def test_with_victims(self):
# The process declared deadlocked loses its transaction. Then no
# transaction is left waiting, but probes that were in flight when
# a victim aborted can declare a process whose cycle is gone.
phantom = 0
for seed in range(150):
rng = random.Random(seed)
db = CMH(SITES)
def hook(p, db=db):
nonlocal phantom
if not on_cycle(wait_graph(db), p):
self.assertGreater(len(db.declared), 1, seed) # an abort came first
phantom += 1
db.on_declare = hook
self.assertEqual(db.run(rng, random_txns(rng)), [], seed)
self.assertGreater(phantom, 0)
def test_each_computation_against_the_global_graph(self):
# Let the system come to rest with no detector, then start one
# computation at a time: P is declared exactly when P is on a cycle.
cycles = 0
for seed in range(150):
rng = random.Random(seed)
db = CMH(SITES, resolve=False, timers=False)
db.run(rng, random_txns(rng), auto=False)
edges = wait_graph(db)
e = remote_edge_count(db)
for p in sorted(edges):
before, sent = len(db.declared), db.probes
db.initiate(p)
db.drain(rng)
self.assertEqual(p in db.declared[before:], on_cycle(edges, p), (seed, p))
self.assertLessEqual(db.probes - sent, e * (e + 1))
cycles += on_cycle(edges, p)
self.assertGreater(cycles, 20)
def test_literal_rule_misses_a_local_closing_edge(self):
# With the literal rule the probe goes round once more and is
# dropped at (1,S2), whose flag is already set.
for literal, declared, probes in ((True, [], 3), (False, [(1, "S1")], 2)):
db = CMH(["S1", "S2"], literal=literal, resolve=False, timers=False)
db.run(random.Random(0), cross_cycle(), auto=False)
self.assertTrue(on_cycle(wait_graph(db), (1, "S1")))
db.initiate((1, "S1"))
db.drain(random.Random(0))
self.assertEqual(db.declared, declared)
self.assertEqual(db.probes, probes)
# The computation of (2,S1), the end of the remote edge, finds it.
db = CMH(["S1", "S2"], literal=True, resolve=False, timers=False)
db.run(random.Random(0), cross_cycle(), auto=False)
db.initiate((2, "S1"))
db.drain(random.Random(0))
self.assertEqual(db.declared, [(2, "S1")])
def test_numbered_computations(self):
# The first computation of (1,S1) runs before T3 closes the cycle
# and leaves flags at (1,S2) and (2,S3). Without numbers they stop
# the second computation.
txns = {1: ("S1", [("a", "S1"), ("b", "S2")]),
2: ("S2", [("b", "S2"), ("c", "S3")]),
3: ("S3", [("c", "S3"), ("a", "S1")])}
for numbered in (True, False):
rng = random.Random(0)
db = CMH(SITES, numbered=numbered, resolve=False, timers=False)
for tid in sorted(txns):
db.start(tid, *txns[tid])
db.drain(rng, hold=lambda m: m[2] == ("next", 3))
db.initiate((1, "S1"))
db.drain(rng, hold=lambda m: m[2] == ("next", 3))
self.assertEqual(db.declared, [])
self.assertFalse(on_cycle(wait_graph(db), (1, "S1")))
db.drain(rng)
self.assertTrue(on_cycle(wait_graph(db), (1, "S1")))
db.initiate((1, "S1"))
db.drain(rng)
self.assertEqual(db.declared, [(1, "S1")] if numbered else [])
def test_no_deadlock_no_declaration(self):
# Two transactions that ask for a and b in the same order wait but
# never deadlock, even with probes in flight while locks move.
for seed in range(100):
rng = random.Random(seed)
db = CMH(SITES)
txns = {t: (SITES[t % 3], [("a", "S1"), ("b", "S2"), ("c", "S3")]) for t in (1, 2, 3)}
self.assertEqual(db.run(rng, txns), [])
self.assertEqual(db.declared, [])
self.assertTrue(all(t.status == "committed" for t in db.txns.values()))
if __name__ == "__main__":
unittest.main()
History
By the early 1980s many distributed deadlock detection protocols had been published, and Chandy, Misra and Haas (1983) quote Gligor and Shattuck (1980): "renewed interest in distributed systems has resulted in the publication of at least ten protocols for deadlock detection. However, few of these protocols are correct and fewer appear to be practical." Chandy and Misra (1982) gave the probe algorithm for the resource model at the first PODC, with detailed proofs. The 1983 paper in ACM Transactions on Computer Systems, with Haas, took the resource model from Menasce and Muntz (1979), restated the probe algorithm, and added the query algorithm for the communication model, which builds on the termination detection of Dijkstra and Scholten (1980). Obermarck (1982), whom the paper cites, had given a path-pushing algorithm in ACM Transactions on Database Systems in the same period.
References
- K. Mani Chandy, Jayadev Misra and Laura M. Haas, Distributed deadlock detection, ACM Transactions on Computer Systems 1(2), 1983, pages 144 to 156, Section 2.1 (the resource model), Section 2.3 (cycles in the resource model and knots in the communication model), Section 3.1 (the probe algorithm and the outline of its proof), Section 4 (query computations for the communication model) and Section 5 (the bound on probes and the idle time before a computation starts)
- K. Mani Chandy and Jayadev Misra, A distributed algorithm for detecting resource deadlocks in distributed systems, Proceedings of the First ACM Symposium on Principles of Distributed Computing, 1982, pages 157 to 164, the probe algorithm for the resource model with its detailed proofs
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W0 stub |
|
Tag H4QN6P Edit this page History Report an error Markdown