Sub topic 15
Topological Sort in Real Systems
This chapter assumes you can already run Kahn's algorithm, detect cycles, group nodes into levels, and use graphlib.TopologicalSorter. Here we look at how real tools apply those pieces. In every case the problem comes down to three questions: what the nodes are, what an edge means, and what the tool should do when it finds a cycle.
The Same Pattern in Many Tools
| System | Nodes | Edge u → v means | What a cycle means |
|---|---|---|---|
| Build tools (Make, Bazel, Ninja) | Files and targets | v is built from u | Circular build rule, reported as an error |
| Workflow schedulers (Airflow, dbt) | Tasks or models | v reads u's output | The DAG is rejected when it is loaded |
| Package managers (apt, npm) | Packages | v requires u | Circular dependency, sometimes broken by a special install step |
| Spreadsheets | Cells | v's formula refers to u | "Circular reference" warning |
| Database migrations | Migration scripts | v assumes u has already run | Migration history conflict |
| Course planning | Courses | u is a prerequisite of v | The curriculum cannot be completed |
Most of these tools need more than a single order. They also use the variants from earlier chapters:
- Schedulers run each level in parallel, so independent tasks overlap in time.
- Build tools rebuild only the targets downstream of a change.
- Spreadsheets recalculate only the cells that depend on the cell you edited, in topological order.
- Course planners treat each level as a semester, sometimes with a cap on how many courses fit in one semester.
Worked Example: An Incremental Build
A full rebuild sorts every target. An incremental build first finds the targets that a changed file can reach, then builds only those targets, in topological order.
from graphlib import TopologicalSorter
# Each target maps to the set of things it is built from.
deps = {
"app": {"main.o", "util.o"},
"main.o": {"main.c", "util.h"},
"util.o": {"util.c", "util.h"},
"tests": {"app"},
}
def rebuild_plan(deps, changed):
# Reverse the edges so we can walk from a source file to everything built from it.
dependents = {}
for target, prereqs in deps.items():
for p in prereqs:
dependents.setdefault(p, set()).add(target)
stale = set()
stack = [changed]
while stack:
node = stack.pop()
for t in dependents.get(node, ()):
if t not in stale:
stale.add(t)
stack.append(t)
order = TopologicalSorter(deps).static_order()
return [n for n in order if n in stale]
print(rebuild_plan(deps, "util.c"))
# ['util.o', 'app', 'tests']
print(rebuild_plan(deps, "util.h"))When util.c changes, main.o stays as it is. When util.h changes, both object files are stale. The order between main.o and util.o is not fixed, but both always come before app. Real build tools add one more check: they compare timestamps or content hashes to decide whether a file has changed at all.
Common Errors in Practice
- Missing nodes. A dependency that never appears as a key still has to be in the graph. Kahn's in-degree table needs an entry for it, which graphlib adds automatically.
- Hidden dependencies. If a task reads a file that is not declared as an edge, the order may happen to work by luck and then fail once the work runs in parallel.
- Unhelpful cycle errors. Users need the cycle itself, such as
a → b → a, not just the word "cycle". graphlib gives you this list inerr.args[1]. - Edges added at runtime. A sort is valid only for the graph it was computed on. If tasks can add new dependencies while running, the scheduler has to sort again.
Exercise
In the build example, which targets does rebuild_plan return when main.c changes, and why does util.o not appear?
Show answer
It returns ['main.o', 'app', 'tests']. util.o is not built from main.c, directly or indirectly, so main.c cannot reach it in the dependents graph, and util.o is never marked stale.
Exercise
A course planner gives you levels [['intro'], ['datastructures', 'discretemath'], ['algorithms']], but a student can take only one course per semester. How many semesters are needed, and is the plan still a valid topological order?
Show answer
Four semesters. Taking the courses one at a time, level by level (intro, datastructures, discretemath, algorithms), gives a valid topological order, because each course still comes after all of its prerequisites. Load caps only stretch the schedule over more semesters; they never break the ordering.