Sub topic 15
Topological Sort in Real Systems
This chapter assumes you know Kahn's algorithm, DFS-based sorting, cycle detection, parallel levels, and Python's graphlib.TopologicalSorter from earlier chapters. Here we take those tools and look at how real software uses them. Real systems rarely call "sort the whole graph once and print it." They sort part of a graph, run nodes concurrently, apply resource limits, and must explain a cycle to a human in a useful way.
The Common Pattern
Every system in this chapter follows the same three steps:
- Pick what the nodes are: files, packages, tasks, courses, cells, or resources.
- Pick what an edge means. Usually "A must finish before B starts."
- Run a topological sort, often a variant, and act on the order.
The variation is in steps 1 and 2, and in what "act on the order" means.
| System | Nodes | Edge u → v means | What the order is used for |
|---|---|---|---|
| Build tools (Make, Bazel, Ninja) | Files and targets | v is built from u | Compile in a valid order and rebuild only stale targets |
| Package managers (pip, npm, apt) | Packages | v requires u | Install dependencies before the packages that need them |
| Workflow schedulers (Airflow, CI pipelines) | Tasks | v consumes u's output | Start tasks as soon as their inputs are ready |
| Spreadsheets | Cells | v's formula reads u | Recalculate cells after their inputs change |
| Infrastructure tools (Terraform) | Cloud resources | v references u | Create in order, destroy in reverse order |
| Database migrations | Migration scripts | v assumes u's schema | Apply schema changes in a safe sequence |
| Course planning | Courses | u is a prerequisite of v | Lay out semesters |
The Unix utility tsort does step 3 and nothing else. You give it pairs of names and it prints an order, or reports a loop.
Build Systems: Sorting Only What Changed
A build graph links source files to the objects and programs made from them. When you edit one file, rebuilding everything wastes time. A build tool finds the targets downstream of the change and rebuilds only those, still in topological order.
The algorithm has two parts. First, a breadth-first search from the changed files along "is used by" edges marks the dirty targets. Then the full topological order is filtered down to only those targets.
from collections import deque
from graphlib import TopologicalSorter
# Each target maps to the inputs it is built from (its predecessors).
deps = {
"app": {"main.o", "util.o"},
"main.o": {"main.c", "util.h"},
"util.o": {"util.c", "util.h"},
"tests": {"util.o"},
}
def rebuild_order(deps, changed):
# Reverse the edges: input -> targets that use it.
dependents = {}
for target, inputs in deps.items():
for i in inputs:
dependents.setdefault(i, set()).add(target)
# Everything reachable from a changed file is stale.
dirty = set()
queue = deque(changed)
while queue:
node = queue.popleft()
for t in dependents.get(node, ()):
if t not in dirty:
dirty.add(t)
queue.append(t)
order = TopologicalSorter(deps).static_order()
return [n for n in order if n in dirty]
print(rebuild_order(deps, {"util.c"}))
# e.g. ['util.o', 'app', 'tests'] (app and tests may appear in either order)
print(rebuild_order(deps, {"util.h"}))
# e.g. ['main.o', 'util.o', 'app', 'tests']Filtering a topological order keeps it valid. If u comes before v in the full order, it still comes before v in any subsequence. Real tools decide what is "changed" using file timestamps (Make) or content hashes (Bazel), but the graph logic is the same.
Package Managers: Direction and Cycles
When a package manager installs app, it resolves the set of required packages and installs them dependencies-first. Two practical points come up:
- Edge direction is the most common bug. A requirements file says "app depends on lib," which is the edge app → lib. Installation needs lib before app. If you feed "depends on" edges straight into Kahn's algorithm, which expects "comes before" edges, you get the reverse order.
graphlibavoids the confusion because it takes predecessors directly:{"app": {"lib"}}. - Cycles happen in practice. Some ecosystems allow mutually dependent packages. The package manager then either installs the whole strongly connected component as one unit or refuses and names the cycle. A message like "graph has a cycle" doesn't tell the user what to fix.
graphlib.CycleErrorputs the actual loop inerr.args[1], and you should show that list to the user.
Uninstall and teardown use the reverse topological order. Terraform, for example, destroys a resource only after everything that references it is gone.
Workflow Schedulers: Running Tasks as They Become Ready
Parallel levels, covered in an earlier chapter, wait for a whole level to finish before starting the next. This leaves workers idle when one task in the level is slow. Schedulers such as Airflow and CI runners start each task as soon as its own predecessors finish. graphlib supports this directly with prepare(), get_ready(), and done().
import time
from concurrent.futures import ThreadPoolExecutor, FIRST_COMPLETED, wait
from graphlib import TopologicalSorter
deps = {
"compile": {"fetch"},
"lint": {"fetch"},
"test": {"compile", "lint"},
"package": {"test"},
}
def run(task):
time.sleep(0.1) # stand-in for real work
return task
def run_all(deps, workers=2):
ts = TopologicalSorter(deps)
ts.prepare() # raises CycleError here if the graph has a cycle
finished = []
with ThreadPoolExecutor(max_workers=workers) as pool:
pending = {}
while ts.is_active():
for task in ts.get_ready():
pending[pool.submit(run, task)] = task
done, _ = wait(pending, return_when=FIRST_COMPLETED)
for fut in done:
task = pending.pop(fut)
fut.result() # re-raises if the task failed
finished.append(task)
ts.done(task) # may unlock new ready tasks
return finished
print(run_all(deps))
# e.g. ['fetch', 'compile', 'lint', 'test', 'package']This is Kahn's algorithm with the queue replaced by a pool of workers. Calling ts.done(task) decrements the in-degree of the task's successors, and get_ready() returns those that reached zero.
Failure handling follows from the graph. If compile fails, fut.result() raises and the run stops. A production scheduler would catch the exception, skip done() for that task, and mark every task downstream of it as "upstream failed." Tasks on independent branches can keep running.
Course Planning: Levels with a Capacity Limit
A student can take only so many courses per semester. That limit turns plain level grouping into a constrained scheduling problem. The greedy approach is to fill each term with available courses up to the cap.
def plan_semesters(prereqs, max_per_term):
"""prereqs maps each course to the set of courses that must come first."""
courses = set(prereqs) | {p for ps in prereqs.values() for p in ps}
remaining = {c: set(prereqs.get(c, ())) for c in courses}
taken = set()
terms = []
while remaining:
available = sorted(c for c, ps in remaining.items() if ps <= taken)
if not available:
raise ValueError(f"cycle among: {sorted(remaining)}")
term = available[:max_per_term]
terms.append(term)
taken.update(term)
for c in term:
del remaining[c]
return terms
prereqs = {
"data_structures": {"intro"},
"discrete_math": {"intro"},
"systems": {"intro"},
"algorithms": {"data_structures", "discrete_math"},
"compilers": {"algorithms", "systems"},
}
print(plan_semesters(prereqs, 2))
# [['intro'], ['data_structures', 'discrete_math'], ['algorithms', 'systems'], ['compilers']]Courses that appear only as prerequisites, like intro, are not keys in prereqs. The first line of the function collects them anyway. Forgetting such sink or source nodes is a common source of KeyError or of silently missing nodes.
Gotchas That Show Up in Production
| Problem | Symptom | Fix |
|---|---|---|
| Reversed edges | Dependents run before dependencies | Write down the convention ("u → v means u first") and convert at input |
| Missing nodes | Nodes that appear only as targets are dropped | Build the node set from keys and values |
| Nondeterministic ties | Builds that differ between runs, flaky tests | Break ties by sorting (a min-heap) when output must be reproducible |
| Unhelpful cycle errors | Users can't find the loop | Report the cycle's nodes, as `CycleError` does |
| Hidden dependencies | Parallel runs fail randomly while serial runs pass | Declare every input as an edge; a serial run only works by luck of the order |
| Graph changes during a run | Stale ready sets | Rebuild the sorter, or use a design that allows incremental edge insertion |
The hidden-dependency row deserves a note. A serial build follows one fixed order, so a missing edge may never cause trouble. A parallel scheduler can pick any valid order of the declared graph, so the missing edge eventually breaks the build. This is one reason Bazel runs build actions in a sandbox, where an action can see only the inputs it declared.
Exercise
In rebuild_order, a teammate replaces the final filter with a topological sort of only the dirty nodes, built from deps restricted to dirty targets. Is the result still a valid rebuild order? What can go wrong if they restrict the predecessor sets incorrectly?
Show answer
Yes, provided each dirty target keeps the predecessors that are also dirty. Clean predecessors are already up to date and can be dropped. Every dirty predecessor of a dirty target must remain an edge. If they drop edges between dirty targets (for example, by keeping only edges from changed files), util.o and app become unordered, and app could be linked from a stale util.o.
Exercise
In runall, why does the loop check ts.isactive() instead of checking whether get_ready() returned anything?
Show answer
getready() can return an empty tuple while tasks are still running, because their successors are not unlocked yet. Stopping then would abandon the rest of the graph. isactive() stays true until every node has been passed to done(), so the loop keeps waiting on running futures.
Exercise
A package manager reports "cycle: ['a', 'b', 'c', 'a']". List two ways the system or the user can resolve it.
Show answer
The user can break the cycle by removing or loosening one dependency, for example by moving shared code into a new package that a, b, and c all depend on. Alternatively, the system can treat the strongly connected component {a, b, c} as one unit, install it together, and sort the condensed graph, which is always a DAG.