TExcelTAD
Home › Discrete Mathematics › DAGs and Scheduling

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 u→vu \to v 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 v0→v1→⋯→v0v_0 \to v_1 \to \cdots \to v_0, each viv_i would have to come before vi+1v_{i+1}, so v0v_0 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. ■\blacksquare

The proof is Kahn's algorithm:

python · try it yourself
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).

python · try it yourself
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 tt elements, the step-by-step schedule above splits the nn tasks into tt antichains. So some step has at least n/tn/t tasks:

Theorem. In a DAG with nn vertices whose longest chain has tt vertices, there is an antichain of size at least ⌈n/t⌉\lceil n/t \rceil.

A consequence: any sequence of nn distinct numbers has an increasing subsequence of length at least n\sqrt{n} 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 pp, scheduling becomes harder (finding the optimum is NP-hard in general), but the bounds still hold: you need at least max⁡(t,⌈n/p⌉)\max(t, \lceil n/p \rceil) 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: a→ba \to b, a→ca \to c, b→db \to d, c→dc \to d. List all topological sorts.

Answer

a,b,c,da, b, c, d and a,c,b,da, c, b, d.

Solution

aa must be first (only source) and dd last (it needs both bb and cc). bb and cc are independent, so either order works.

Exercise 2: Minimum time

Tasks with prerequisites: BB needs AA; CC needs AA; DD needs B,CB, C; EE needs DD; FF needs CC. With unlimited workers and unit-time tasks, what is the minimum time?

Answer

4 steps.

Solution

Step 1: AA. Step 2: B,CB, C. Step 3: D,FD, F. Step 4: EE. The chain A→B→D→EA \to B \to D \to E 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.

python · try it yourself
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…

  1. it is connected
  2. it has no cycles
  3. every vertex has in-degree 1
  4. it has an even number of edges

With unlimited parallel workers and unit-time tasks, the minimum completion time equals…

  1. the number of tasks
  2. the number of vertices on a longest dependency chain
  3. the number of sources
  4. the maximum out-degree

12 tasks have a longest chain of 3. What must exist?

  1. A chain of 4
  2. 4 tasks that can run at the same time
  3. A cycle
  4. 12 independent tasks