Algorithm Search⌘K

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.

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
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 tt has a home process (t,h)(t, h) at its home site and at most one agent (t,m)(t, m) at each other site mm. 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 (u,s)→(v,s)(u, s) \to (v, s) when (u,s)(u, s) waits at ss for a resource that vv holds at ss;
  • a remote edge (t,h)→(t,m)(t, h) \to (t, m) when the home process waits for the reply of the agent at mm;
  • a remote edge (t,m)→(t,h)(t, m) \to (t, h) when the agent holds resources at mm and waits for its home process to tell it to release them.

The paper defines PiP_i to be dependent on PkP_k when a chain of idle processes leads from PiP_i to PkP_k, 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 LD∗(Pk)\mathrm{LD}^*(P_k) be the set of processes that PkP_k reaches by local edges, with PkP_k 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

  1. INITIATE(i) ▷ at the controller of an idle process P_i
  2. 1if P_i is on a cycle of local edges then declare P_i deadlocked and stop
  3. 2m_i ← m_i + 1 ▷ the number of this computation
  4. 3for each P_a in LD*(P_i) and each P_b at another site such that P_a waits for P_b do
  5. 4send probe(i, m_i, a, b) to the controller of P_b
  6. RECEIVE-PROBE(i, m, j, k) ▷ at the controller of P_k
  7. 5if P_k is idle and P_k has not answered P_j and dependent_k(i) < m then
  8. 6dependent_k(i) ← m
  9. 7if P_i is in LD*(P_k) then declare P_i deadlocked
  10. 8else for each P_a in LD*(P_k) and each P_b at another site such that P_a waits for P_b do
  11. 9send probe(i, m, a, b) to the controller of P_b
  12. WHEN P_k STOPS BEING IDLE
  13. 10clear dependent_k

A probe (i,m,j,k)(i, m, j, k) belongs to computation number mm of the initiator PiP_i, and goes from PjP_j at one site to PkP_k at another. The flag dependentk(i)_k(i) means that the controller of PkP_k knows that PiP_i depends on PkP_k. A probe that fails the test of line L5 is dropped. The test "has not answered PjP_j" is condition (iii) of the paper: if PkP_k is an agent, the request of its home is still waiting; if PkP_k is a home process, it has not sent a new request to the agent PjP_j, 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 PiP_i when k=ik = i. Line L7 also declares when PiP_i is in LD∗(Pk)\mathrm{LD}^*(P_k), that is, when the probe comes back to the site of PiP_i 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 TT. 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 k=ik = i. Transaction 1 has its home at S1S_1 and holds aa there. Transaction 2 has its home at S2S_2 and holds bb there. Then 1 asks for bb and 2 asks for aa. The cycle is

(1,S1)→(1,S2)→(2,S2)→(2,S1)→(1,S1),(1, S_1) \to (1, S_2) \to (2, S_2) \to (2, S_1) \to (1, S_1),

with remote edges from each home process to its agent and local edges from each agent to the home process of the other transaction. S1S_1 starts a computation for (1,S1)(1, S_1). It sends probe(1,1,(1,S1),(1,S2))(1, 1, (1,S_1), (1,S_2)) to S2S_2. There the agent (1,S2)(1, S_2) waits for bb, held by (2,S2)(2, S_2), which waits for its agent at S1S_1, so S2S_2 sends probe(…,(2,S2),(2,S1))(\dots, (2,S_2), (2,S_1)) back to S1S_1. The probe arrives at (2,S1)(2, S_1), not at (1,S1)(1, S_1). With line L7, S1S_1 sees that (1,S1)(1, S_1) is in LD∗((2,S1))\mathrm{LD}^*((2, S_1)) and declares it deadlocked after 2 probes. With the test k=ik = i, S1S_1 passes the probe on along the edge from (1,S1)(1, S_1) to (1,S2)(1, S_2) again, and S2S_2 drops it because the flag is set: 3 probes and no declaration. A computation for (2,S1)(2, S_1), the end of a remote edge, finds the cycle with either test.

Three sites, and the numbers. Transaction tt has its home at StS_t 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 (1,S1)(1, S_1) sets flags at (1,S2)(1, S_2) and (2,S3)(2, S_3), and stops, because (3,S3)(3, S_3) is not idle. Then 3 asks for the resource of 1, and the cycle closes. A second computation for (1,S1)(1, S_1) with Boolean flags is dropped at (1,S2)(1, S_2), and the deadlock is never reported for (1,S1)(1, S_1). With numbers, the second computation passes and declares (1,S1)(1, S_1).

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 PiP_i starts while PiP_i is on a cycle, PiP_i is declared by it or by a later computation. With the test k=ik = i, this holds only when the edge of the cycle that enters PiP_i 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 Pi∈LD∗(Pk)P_i \in \mathrm{LD}^*(P_k)), 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 tt has a home process (t,h)(t, h) and at most one agent (t,m)(t, m) at each other site mm. 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 WW at a moment has a node for each idle process and these edges between idle processes:

  • (u,s)→(v,s)(u, s) \to (v, s) if (u,s)(u, s) waits at ss for a resource that vv holds at ss (a local edge);
  • (t,h)→(t,m)(t, h) \to (t, m) if the home process has a request to mm that is not yet answered (a remote edge);
  • (t,m)→(t,h)(t, m) \to (t, h) if the agent holds resources at mm, waits for none, and no request from the home to mm 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. PiP_i depends on PkP_k if WW has a path from PiP_i to PkP_k. LD∗(Pk)\mathrm{LD}^*(P_k) is the set of processes that PkP_k reaches by local edges, with PkP_k. The controller of PkP_k computes it from its own lock table.

Lemma 1 (stability). If p→qp \to q is an edge of WW, the edge stays in WW while qq stays idle. So a path p0→⋯→prp_0 \to \dots \to p_r of WW stays in WW while prp_r stays idle, and a cycle of WW stays forever.

Proof. Look at what removes each kind of edge. A local edge (u,s)→(v,s)(u, s) \to (v, s) goes away only when vv releases the resource at ss, which happens when the home of vv commits or when the agent (v,s)(v, s) gets the release from its home; in both cases (v,s)(v, s) stops being idle in that step. An edge (t,h)→(t,m)(t, h) \to (t, m) 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 (t,m)→(t,h)(t, m) \to (t, h) goes away when the home sends a release, a new request or an abort to mm, 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: pr−1→prp_{r-1} \to p_r stays while prp_r is idle, so pr−1p_{r-1} 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. □\square

Lemma 2 (a probe carries a true dependency). Let the controller of aa send probe(i,m,a,b)(i, m, a, b) at time τ\tau, at a moment when PiP_i depends on aa or equals aa, and aa is idle. If the controller of bb accepts it at time τ′\tau' (line L5), then at τ′\tau' the edge a→ba \to b is in WW, aa has been idle since τ\tau, and PiP_i depends on bb.

Proof. There are two cases for the edge that the controller of aa saw.

From a home to an agent. At τ\tau the home aa has an open request to the site of bb. The probe goes on the same channel as the request and after it. Line L5 accepts only if bb 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 [τ,τ′][\tau, \tau'], aa was idle, and at τ′\tau' the edge a→ba \to b is in WW.

From an agent to its home. At τ\tau the agent aa holds resources and waits for none. Line L5 accepts only if the home bb is idle and has no open request to the site of aa. Suppose the home sent a request to that site at some time before τ′\tau' and after the last reply of aa. If the request is still open at τ′\tau', the probe is dropped. If it was answered, the answer came after the request reached aa; if the request reached aa after τ\tau, the answer is behind the probe on the channel and cannot have arrived; if it reached aa before τ\tau, then aa was not free at τ\tau, a contradiction. So no request went from bb to aa in [τ,τ′][\tau, \tau'], bb did not commit or abort (it is idle), and aa held its resources and waited for bb during the whole interval. At τ′\tau' the edge a→ba \to b is in WW.

In both cases aa stayed idle from τ\tau to τ′\tau'. By Lemma 1, the path from PiP_i to aa that existed at τ\tau is still in WW at τ′\tau'. With the edge a→ba \to b, PiP_i depends on bb. □\square

Lemma 3 (the flags). At all times, if the controller of PkP_k holds dependentk(i)=m_k(i) = m, then PkP_k is idle and PiP_i depends on PkP_k.

Proof. The flag is set only at line L6, where PkP_k is idle and, by Lemma 2, PiP_i depends on PkP_k. While PkP_k stays idle the path stays, by Lemma 1. When PkP_k leaves the idle state, line L10 clears all its flags. For the probes that PkP_k forwards at line L9: they start at some a∈LD∗(Pk)a \in \mathrm{LD}^*(P_k), so PiP_i depends on aa, and aa is idle; this is the premise of Lemma 2 for the next step. The probes of line L4 satisfy it because a∈LD∗(Pi)a \in \mathrm{LD}^*(P_i). □\square

Theorem 1 (no false deadlocks). If a process PiP_i is declared deadlocked, then at that moment PiP_i is on a cycle of WW. With no aborts, it then stays deadlocked forever.

Proof. At line L1 the controller sees a cycle of local edges through PiP_i. At line L7, the flag dependentk(i)_k(i) was just set, so PiP_i depends on PkP_k by Lemma 3, and Pi∈LD∗(Pk)P_i \in \mathrm{LD}^*(P_k) gives a path back from PkP_k to PiP_i. The literal rule k=ik = i is the special case Pk=PiP_k = P_i. The cycle stays by Lemma 1. ■\blacksquare

Theorem 2 (every cycle is found). If a computation for PiP_i starts (line L2) while PiP_i is on a cycle of WW, then PiP_i is declared deadlocked, by this computation or by a later computation for PiP_i.

Proof. If the cycle has no remote edge, line L1 declares PiP_i. Otherwise write the cycle as Pi⇝a1→b1⇝a2→b2⇝⋯⇝ar→br⇝PiP_i \leadsto a_1 \to b_1 \leadsto a_2 \to b_2 \leadsto \dots \leadsto a_r \to b_r \leadsto P_i, where each aj→bja_j \to b_j is a remote edge and each ⇝\leadsto is a path of local edges. The cycle stays forever by Lemma 1, so each aja_j is in LD∗(bj−1)\mathrm{LD}^*(b_{j-1}) (with b0=Pib_0 = P_i) at all later times, and each controller sees the edge aj→bja_j \to b_j.

We show by induction on jj that the flag dependentbj(i)_{b_j}(i) is set to mm or to a larger number at some time, and that at the moment it is set to some number m′≥mm' \geq m, the controller of bjb_j checks line L7 and, if it does not declare, sends probe(i,m′,aj+1,bj+1)(i, m', a_{j+1}, b_{j+1}). For j=0j = 0 this is line L3. For the step, the probe(i,m′,aj,bj)(i, m', a_j, b_j) arrives at bjb_j. The process bjb_j is idle forever, and the remote edge stays, so the condition on replies in line L5 holds. If the flag of bjb_j is less than m′m', the probe is accepted. If it is already at least m′m', it was set by a probe of a computation numbered at least m′m', and the claim holds for that number. Flags of bjb_j are never cleared, because bjb_j never leaves the idle state.

For j=rj = r: when the flag of brb_r is set, Pi∈LD∗(br)P_i \in \mathrm{LD}^*(b_r), so line L7 declares PiP_i. ■\blacksquare

With the literal rule k=ik = i, the last step needs br=Pib_r = P_i, that is, the edge of the cycle that enters PiP_i must be a remote edge. If it is a local edge, the probes go round the cycle and are dropped at b1b_1, whose flag is already set; the test file has such a case with two sites. A computation for bjb_j, 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 bjb_j to be false when the computation starts. A computation for PiP_i that ran before the cycle closed can leave a flag at a process that stays idle, and this flag stops every later probe for PiP_i 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 ee be the number of remote edges that start at idle processes. Then the computation sends at most e(e+1)e(e + 1) 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 ee processes accept, and each of them, and the initiator, sends at most one probe for each remote edge that starts in its set LD∗\mathrm{LD}^*, at most ee probes. ■\blacksquare

Complexity

  • Messages. If the graph does not change during a computation, each process accepts the computation at most once, so at most ee processes and the initiator forward probes, each at most one per remote edge: at most e(e+1)e(e + 1) probes. The paper, Section 5, states a bound of ee probes, where ee 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 nn processes, a number per initiator: O(np)O(n p). 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 rr remote edges takes rr 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 k=ik = i alone, a computation for a process whose cycle comes back through a local edge never reports it. Either check LD∗(Pk)\mathrm{LD}^*(P_k) 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.

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

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

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