Sub topic 15
Where Cycle Detection Is Used
This chapter assumes you have worked through the earlier chapters. You should know three-color DFS, Kahn's algorithm, union-find, and Floyd's tortoise and hare. You should also be comfortable reading Python that uses collections.deque and defaultdict. The chapter takes those algorithms into real systems. In each case it names the graph, says what a cycle means, and explains which detection method fits.
The Same Question in Different Systems
Many systems model "X must wait for Y" or "X depends on Y" as a directed edge. A cycle in that graph means some work can never start or never finish. What separates the applications is when the graph is built and how it changes:
- Static graphs are built once and then checked. A build file and a package manifest are examples. Kahn's algorithm fits well here because you usually want the ordering anyway.
- Incrementally growing graphs gain edges over time. Lock waits and spreadsheet edits are examples. Each new edge can be checked when it arrives.
- Undirected graphs that only gain edges, such as network links or candidate edges in a spanning tree, fit union-find.
- Graphs where each node has exactly one successor, such as linked lists and iterated functions, fit Floyd's algorithm.
Dependency Resolution and Build Systems
Package managers, module bundlers, and build tools such as Make and Bazel all hold a dependency graph. An edge A → B means "A needs B first." A valid build order is a topological order of the reversed graph. When no such order exists, the tool has to stop and report the cycle in a form a person can act on.
Kahn's algorithm gives the order directly. When it fails, the vertices it never removed include every vertex on a cycle, plus every vertex that depends on a cycle. Printing that whole leftover set is a common mistake. A project with one bad edge in a core library can leave hundreds of targets stuck, and the error message then hides the two or three that matter.
There is an easy way to narrow the set. Every stuck vertex still has at least one stuck dependency, because otherwise its count would have reached zero. So if you start at any stuck vertex and keep stepping to some stuck dependency, you can never get out of the stuck set. The walk must eventually revisit a vertex, and the part of the walk from the first visit to the repeat is a real cycle. That repeated-visit walk is the same structure Floyd's algorithm exploits in functional graphs.
from collections import deque, defaultdict
def find_cycle(deps, stuck):
"""Walk stuck dependencies until a vertex repeats; return that cycle."""
path, pos = [], {}
node = min(stuck)
while node not in pos:
pos[node] = len(path)
path.append(node)
node = min(d for d in deps[node] if d in stuck)
return path[pos[node]:] + [node]
def build_order(deps):
"""deps maps each target to the targets it depends on."""
nodes = set(deps)
for ds in deps.values():
nodes.update(ds)
users = defaultdict(list)
remaining = {n: 0 for n in nodes}
for target, ds in deps.items():
for d in ds:
users[d].append(target)
remaining[target] += 1
ready = deque(sorted(n for n in nodes if remaining[n] == 0))
order = []
while ready:
n = ready.popleft()
order.append(n)
for u in users[n]:
remaining[u] -= 1
if remaining[u] == 0:
ready.append(u)
if len(order) < len(nodes):
cycle = find_cycle(deps, nodes - set(order))
raise ValueError("dependency cycle: " + " -> ".join(cycle))
return order
deps = {"app": ["lib", "utils"], "lib": ["core"], "core": ["utils"], "utils": []}
print(build_order(deps)) # ['utils', 'core', 'lib', 'app']
deps["utils"] = ["app"]
try:
build_order(deps)
except ValueError as e:
print(e) # dependency cycle: app -> lib -> core -> utils -> appThe cycle walk adds at most O(V + E) work, so the whole check stays linear. min makes the output deterministic. Without it, two runs over the same broken project could report different cycles, which confuses users and makes test snapshots flaky.
Real tools differ in how strict they are. GNU Make prints a "Circular dependency dropped" warning and keeps going. Most package managers refuse to install. Python permits circular imports at runtime, but the module that is imported second sees a partly initialized module, so attribute lookups can fail in confusing ways. Linters and bundlers run cycle detection on the import graph to warn about this before it bites.
Deadlock Detection
A database lock manager or an operating system can model blocked work as a wait-for graph. A vertex is a transaction or a thread, and an edge T1 → T2 means T1 is waiting for a lock that T2 holds. A cycle is a deadlock: no member can proceed until another member releases a lock first.
This graph changes all the time. Edges appear when a request blocks and disappear when a lock is released. You do not need to search the whole graph on every change. Adding waiter → holder closes a cycle exactly when holder can already reach waiter, so one reachability search from holder is enough.
class WaitForGraph:
def __init__(self):
self.waits_on = {}
def would_deadlock(self, waiter, holder):
stack, seen = [holder], {holder}
while stack:
t = stack.pop()
if t == waiter:
return True
for nxt in self.waits_on.get(t, ()):
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
return False
def add_wait(self, waiter, holder):
if self.would_deadlock(waiter, holder):
return False
self.waits_on.setdefault(waiter, set()).add(holder)
return True
def release(self, waiter):
self.waits_on.pop(waiter, None)
g = WaitForGraph()
print(g.add_wait("T1", "T2")) # True
print(g.add_wait("T2", "T3")) # True
print(g.add_wait("T3", "T1")) # False: T1 -> T2 -> T3 -> T1When add_wait returns False, the system must pick a victim, a transaction it aborts to break the cycle. Common rules pick the youngest transaction or the one holding the fewest locks.
Production systems often delay the check. PostgreSQL, for example, lets a blocked backend wait for deadlock_timeout (1 second by default) before it searches the wait-for graph. Most lock waits end on their own, and skipping the search for those is cheaper than searching on every block.
Spreadsheets and Reactive Recalculation
A spreadsheet stores formulas in cells. If B1 = A1 * 2, then B1 depends on A1. Recalculation evaluates cells in topological order. A circular reference such as A1 = B1 + 1 with B1 = A1 * 2 has no order, so the program has to warn about it. Spreadsheets check when a formula is entered, using the same per-edge reachability idea as the wait-for graph. Reactive UI frameworks and incremental computation engines do the same with derived values. Many of them throw an error when a computed value ends up reading itself during evaluation, which is a cycle found by the evaluation itself.
Undirected Uses: Spanning Trees and Networks
Kruskal's minimum spanning tree algorithm sorts the edges by weight and adds each edge unless it would create a cycle. "Would create a cycle" is exactly the union-find test: the two endpoints are already in the same set. Edges only ever get added, so union-find is a better fit here than repeated DFS.
Ethernet networks face a related problem. A physical loop of switches makes broadcast frames circulate forever. The Spanning Tree Protocol prevents this by switching off links until the remaining links form a tree. That is cycle removal rather than detection, but it rests on the same idea: a connected undirected graph with V vertices and V − 1 edges has no cycle.
Functional Graphs in Practice
Floyd's algorithm applies whenever each state has exactly one next state. Concrete cases include:
- Checking a linked list for a corrupted
nextpointer that loops back, using O(1) extra memory. - Finding the period of a pseudo-random number generator, since iterating its state function must eventually repeat.
- Pollard's rho factorization, which iterates
x → x² + c mod nand uses cycle detection to find a factor.
Summary of Applications
| Application | Graph | What a cycle means | Typical method |
|---|---|---|---|
| Package or build tool | Directed, static | Impossible build order | Kahn's algorithm plus cycle walk |
| Import linter | Directed, static | Partly initialized modules | Three-color DFS or SCCs |
| Database locks | Directed, changing | Deadlock | Reachability per new wait, or periodic DFS |
| Spreadsheet | Directed, edited | Circular reference | Reachability per formula edit |
| Kruskal's MST | Undirected, growing | Edge is redundant | Union-find |
| Linked list or PRNG | Functional | Loop or period | Floyd's tortoise and hare |
| Workflow scheduler | Directed, static | Workflow cannot run | Validate with Kahn's algorithm at load time |
Exercise
A build tool runs Kahn's algorithm on 500 targets and 120 are never removed. Why is printing all 120 as "the cycle" misleading, and what should the tool print instead?
Show answer
The leftover set holds every vertex on a cycle plus every vertex that depends, directly or indirectly, on a cycle. Most of the 120 may be ordinary targets that are blocked downstream. The tool should start at any stuck vertex and repeatedly step to a stuck dependency until a vertex repeats, then print that one concrete cycle. Optionally it can list the strongly connected components that contain more than one vertex, or one vertex with a self-loop.
Exercise
In WaitForGraph, why is it enough to search from holder for waiter, rather than running full three-color DFS over the whole graph after each new edge?
Show answer
Before the edge is added the graph has no cycle, because every earlier edge passed the same check. So any new cycle must use the new edge waiter → holder. A cycle through that edge exists exactly when a path from holder back to waiter already exists. The search only visits vertices reachable from holder, which is usually far fewer than the whole graph.
Exercise
Kruskal's algorithm processes edges (a,b), (b,c), (a,c), (c,d) in that order. Which edge does union-find reject, and why?
Show answer
It rejects (a,c). After (a,b) and (b,c) are added, a and c are already in the same set, so adding (a,c) would close the cycle a–b–c–a. The edge (c,d) joins d to the set and is accepted.