Sub topic 11
Grouping Tasks into Parallel Levels
This chapter assumes you already know Kahn's algorithm from earlier in the tutorial: in-degree counts, a queue of ready nodes, and cycle detection by counting how many nodes were output. You should also be comfortable with Python lists and dictionaries.
A plain topological order puts every task in one line. Real systems often have several workers, such as CPU cores, build agents or CI runners, so the question changes. You no longer ask only "which order is valid?" You ask "which tasks can run at the same time?" Level-by-level ordering is the simplest answer. It splits the nodes into groups, called levels, where no task in a level depends on any other task in the same level.
The idea: Kahn's algorithm in rounds
Standard Kahn's algorithm takes one ready node at a time from a queue. The level version processes the queue in rounds instead:
- Level 0 is every node whose in-degree is 0. These nodes have no prerequisites.
- Remove all of level 0 at once. Decrement the in-degree of each successor.
- The nodes whose in-degree just dropped to 0 form level 1.
- Repeat until no ready nodes remain.
Every node in a given round became ready only after all of its predecessors were removed in earlier rounds. So two nodes in the same level cannot have an edge between them. If u -> v existed with both in level k, then v could not have reached in-degree 0 until u was removed, which places v in level k+1 or later.
The implementation
def topo_levels(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
level = [u for u, d in indegree.items() if d == 0]
levels = []
seen = 0
while level:
levels.append(level)
seen += len(level)
next_level = []
for u in level:
for v in graph.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
next_level.append(v)
level = next_level
if seen != len(indegree):
raise ValueError("graph has a cycle")
return levels
print(topo_levels({"fetch": ["compile", "lint"], "compile": ["test"], "lint": ["test"], "test": []}))
# [['fetch'], ['compile', 'lint'], ['test']]The structure matches Kahn's algorithm, with one change: the single queue is replaced by two lists, level for the current round and next_level for the next one. The cycle check works the same way. If some nodes never reach in-degree 0, seen is smaller than the number of nodes, and the function raises an error.
Concatenating the levels gives a valid topological order. Running time is still O(V + E), because each node enters exactly one level and each edge is decremented exactly once. Extra memory is O(V) for the in-degree map and the level lists.
Details that matter
- Nodes that appear only as targets.
indegree.get(v, 0)adds nodes that never appear as keys, andgraph.get(u, [])treats them as having no outgoing edges. The function still works if"test"is missing from the dictionary's keys. - Isolated nodes have in-degree 0 and land in level 0, which is correct because they can start at any time.
- Order inside a level follows dictionary insertion order and edge order. That order is deterministic but means nothing. If you need stable output, for logs or tests for example, sort each level with
levels.append(sorted(level)). - Empty graph. The function returns
[], and the cycle check passes because0 == 0.
What a level number means
A node's level equals the length, counted in edges, of the longest path from any source to that node. Here is why. A node becomes ready only after its slowest chain of predecessors has been removed, and each round removes one more link of every chain.
This has a direct consequence. The number of levels equals the number of nodes on the longest path in the DAG. That path is called the critical path. With unlimited workers and tasks that each take one time unit, no schedule can finish in fewer steps than the critical path has nodes, and the level schedule reaches that bound. So for unit-time tasks and enough workers, level-by-level scheduling is optimal.
def level_of(graph):
return {u: i for i, lvl in enumerate(topo_levels(graph)) for u in lvl}
g = {"a": ["b", "d"], "b": ["c"], "c": ["d"], "d": []}
print(level_of(g))
# {'a': 0, 'b': 1, 'c': 2, 'd': 3}Node d has a direct edge from a, but it lands in level 3, not level 1, because the longer chain a -> b -> c -> d controls when it becomes ready. A common mistake is to assign levels with BFS distance from the sources. BFS finds the shortest path and would put d at level 1, which is too early.
Where level scheduling falls short
Levels are easy to explain and easy to show to users ("stage 1 of 3"). They rest on assumptions that real systems often break.
Tasks with different durations
Running levels in order puts a barrier between them: level k+1 waits until every task in level k finishes. When durations differ, that barrier wastes time.
| Task | Depends on | Duration |
|---|---|---|
| A | none | 10 |
| B | none | 1 |
| C | A | 1 |
| D | B | 5 |
Levels are [A, B] then [C, D]. With a barrier, D starts at time 10 and the run finishes at 15. D only needs B, so it could start at time 1, and then everything finishes at 11.
The fix is event-driven scheduling. Keep Kahn's in-degree counts. Whenever a task finishes, decrement its successors' counts and hand any newly ready task to a free worker right away. Python's graphlib.TopologicalSorter supports this through get_ready() and done(), which a later chapter covers. With durations, the earliest possible start time of a task is the longest weighted path to it, which is the DAG dynamic programming from the longest-path chapter.
A limited number of workers
If a level holds more tasks than you have workers, you have to choose which ones run first. With k workers the level schedule is no longer guaranteed to be optimal, and finding the minimum-length schedule for unit tasks with a fixed k ≥ 3 is a classic hard problem whose exact complexity is still open. Practical schedulers use heuristics instead. A common one runs first the ready task with the longest remaining path below it, because delaying the critical path delays everything.
As-soon-as-possible versus as-late-as-possible
Kahn's rounds place each task in the earliest level it can occupy. A task such as a lone docs step with no dependents ends up in level 0, even though it could just as well run at the very end. If you want tasks to run as late as possible, for example to delay expensive work or keep early levels small, run the same algorithm on the reversed graph and then reverse the list of levels. A task's slack, meaning how far it can move without lengthening the schedule, is its late level minus its early level. Tasks with zero slack lie on the critical path.
Choosing an approach
| Situation | Approach |
|---|---|
| Unit-time tasks, many workers | Kahn's rounds (`topo_levels`) |
| Showing stages to users | Kahn's rounds, sort each level |
| Durations differ | Event-driven Kahn's with a worker pool |
| Fewer workers than ready tasks | Event-driven, prioritize the longest remaining path |
| Defer non-urgent work | Levels on the reversed graph |
Exercise
Compute the levels for the graph {"a": ["c"], "b": ["c", "e"], "c": ["d"], "d": [], "e": ["d"], "f": []}. How many levels are there, and what is the critical path?
Show answer
Level 0 is ['a', 'b', 'f'], level 1 is ['c', 'e'], level 2 is ['d']. There are 3 levels. The critical paths have 3 nodes: a -> c -> d, b -> c -> d and b -> e -> d. Node f is isolated and sits in level 0.
Exercise
A colleague assigns levels by running BFS from all in-degree-0 nodes and using each node's BFS distance. Give a graph where this produces two nodes with an edge between them in the same level.
Show answer
Use {"a": ["b", "c"], "b": ["c"], "c": []}. BFS gives b distance 1 and c distance 1, because of the direct edge a -> c. But b -> c is an edge, so c cannot run in parallel with b. Kahn's rounds correctly put c in level 2.
Exercise
Modify topo_levels so it returns levels for as-late-as-possible scheduling. Describe the change without rewriting the whole function.
Show answer
Build the reversed graph, where every edge u -> v becomes v -> u and every node is kept as a key. Run topo_levels on it and reverse the resulting list of levels. Sinks now land in the last level, and each task sits in the latest level its dependents allow.