DAGs and Scheduling
A directed acyclic graph (DAG) is a digraph with no cycles. DAGs describe dependencies: course prerequisites, build steps, spreadsheet formulas, package versions, tasks in a project. Two questions come up constantly: in what order can the tasks be done, and how fast can they be finished if several can run in parallel?
Topological sort
A topological sort lists the vertices so that every edge goes from an earlier vertex to a later one: every task comes after its prerequisites.
Theorem. A digraph has a topological sort if and only if it is a DAG.
Proof. If there were a cycle , each would have to come before , so would come before itself. Conversely, a finite DAG always has a source (a vertex with in-degree 0): otherwise, walking backwards along incoming edges forever would repeat a vertex and close a cycle. List a source, delete it (the rest is still a DAG), and repeat.
The proof is Kahn's algorithm:
from collections import deque
prereq = { # course: courses it requires
"intro": [], "discrete": ["intro"], "datastructs": ["intro"],
"algorithms": ["discrete", "datastructs"], "databases": ["datastructs"],
"compilers": ["algorithms"], "ml": ["algorithms", "databases"],
}
def topo_sort(req):
indeg = {c: len(r) for c, r in req.items()}
unlocks = {c: [] for c in req}
for c, r in req.items():
for p in r:
unlocks[p].append(c)
ready = deque(sorted(c for c in req if indeg[c] == 0))
order = []
while ready:
c = ready.popleft()
order.append(c)
for nxt in unlocks[c]:
indeg[nxt] -= 1
if indeg[nxt] == 0:
ready.append(nxt)
if len(order) < len(req):
raise ValueError("cycle detected")
return order
print(topo_sort(prereq))
try:
topo_sort({"a": ["c"], "b": ["a"], "c": ["b"]})
except ValueError as e:
print("a -> b -> c -> a:", e)['intro', 'discrete', 'datastructs', 'algorithms', 'databases', 'compilers', 'ml']
a -> b -> c -> a: cycle detected
Parallel scheduling
Suppose every task takes one time unit and any number of tasks can run at once, as long as prerequisites are finished. Then the minimum time is the number of vertices on a longest path (a longest chain of dependencies, the critical path). The schedule: put each task one step after the latest step of its prerequisites (tasks without prerequisites go in step 1).
prereq = {
"intro": [], "discrete": ["intro"], "datastructs": ["intro"],
"algorithms": ["discrete", "datastructs"], "databases": ["datastructs"],
"compilers": ["algorithms"], "ml": ["algorithms", "databases"],
}
order = ["intro", "discrete", "datastructs", "algorithms", "databases", "compilers", "ml"] # a topological order
step = {}
for c in order:
step[c] = 1 + max((step[p] for p in prereq[c]), default=0)
for s in range(1, max(step.values()) + 1):
print(f"semester {s}:", sorted(c for c in step if step[c] == s))semester 1: ['intro']
semester 2: ['datastructs', 'discrete']
semester 3: ['algorithms', 'databases']
semester 4: ['compilers', 'ml']
No schedule can be shorter: the chain intro → discrete → algorithms → ml has 4 tasks that must run one after another.
Chains, antichains and Dilworth
A chain is a set of tasks that must be done in sequence (each pair is comparable through dependencies); an antichain is a set of tasks with no dependencies between them, which can all run at once. If the longest chain has elements, the step-by-step schedule above splits the tasks into antichains. So some step has at least tasks:
Theorem. In a DAG with vertices whose longest chain has vertices, there is an antichain of size at least .
A consequence: any sequence of distinct numbers has an increasing subsequence of length at least or a decreasing one of at least that length (Erdős–Szekeres). The general version for partial orders is Dilworth's theorem.
With a limited number of processors , scheduling becomes harder (finding the optimum is NP-hard in general), but the bounds still hold: you need at least steps.
In software
make, Bazel and Gradle sort the build DAG topologically and run independent targets in parallel; the critical path bounds the build time. Package managers detect circular dependencies with exactly the cycle check above. Spreadsheets recompute cells in topological order of their formula references. Airflow and similar tools schedule data pipelines as DAGs. See also Topological Sort in the DSA course.
Exercises
Exercise 1: Valid orders
Edges: , , , . List all topological sorts.
Answer
and .
Solution
must be first (only source) and last (it needs both and ). and are independent, so either order works.
Exercise 2: Minimum time
Tasks with prerequisites: needs ; needs ; needs ; needs ; needs . With unlimited workers and unit-time tasks, what is the minimum time?
Answer
4 steps.
Solution
Step 1: . Step 2: . Step 3: . Step 4: . The chain has 4 tasks, so 4 steps is optimal.
Exercise 3: Find a cycle (code)
Use the topological sort to decide whether the dependencies {"app": ["lib"], "lib": ["util"], "util": ["log"], "log": ["app"]} contain a cycle.
Answer
Yes: app, lib, util and log form a cycle, so no order exists.
Solution
No vertex has in-degree 0, so Kahn's algorithm cannot even start.
req = {"app": ["lib"], "lib": ["util"], "util": ["log"], "log": ["app"]}
indeg = {c: len(r) for c, r in req.items()}
print("sources:", [c for c in req if indeg[c] == 0])sources: []
Test yourself
A digraph has a topological sort exactly when…
- it is connected
- it has no cycles
- every vertex has in-degree 1
- it has an even number of edges
With unlimited parallel workers and unit-time tasks, the minimum completion time equals…
- the number of tasks
- the number of vertices on a longest dependency chain
- the number of sources
- the maximum out-degree
12 tasks have a longest chain of 3. What must exist?
- A chain of 4
- 4 tasks that can run at the same time
- A cycle
- 12 independent tasks