Running Tasks in Dependency Order: Python's graphlib

This article explains how Python's graphlib orders a dependency graph with TopologicalSorter, releases independent tasks for parallel execution, reports cycles, and why the order of ready tasks can change between runs.

A bright green tree python draped in layered coils over a branch, its head resting on the lowest coil against blurred foliage.
Photo by Derek Otway on Unsplash

Build systems, package installers, database migrations and data pipelines share one problem: a set of tasks in which some can start only after others have finished. The present article addresses the module graphlib, added to the standard library in Python 3.9, whose class TopologicalSorter orders the nodes of a dependency graph so that every node comes after all of its predecessors. It covers the static order of a whole graph, the incremental interface that releases tasks for parallel execution as their dependencies finish, the detection of cycles, and the details that make an apparently correct order differ from one run to the next. Turning a declaration of what each task needs into a valid execution order, and into the set of tasks that may run at the same time, is the secret weapon of graphlib.

Tech Tree: Declaring What Each Task Requires

A graph is given to TopologicalSorter as a dictionary in which each key is a node and each value is an iterable of the nodes that must come before it, its predecessors, not the nodes that depend on it. The method add(node, *predecessors) builds or extends the same graph piece by piece, and a predecessor that has not been declared is added automatically as a node without dependencies. The following example orders a small build and then reports a cycle.

from graphlib import CycleError, TopologicalSorter

build = {
    "link": ["compile_code", "compile_resources"],
    "compile_code": ["clean_temp"],
    "compile_resources": ["clean_temp"],
}
sorter = TopologicalSorter(build)
sorter.add("package", "link")
print(list(sorter.static_order()))
# Output: ['clean_temp', 'compile_code', 'compile_resources', 'link', 'package']

cyclic = TopologicalSorter({"a": ["b"], "b": ["c"], "c": ["a"]})
try:
    list(cyclic.static_order())
except CycleError as error:
    print(isinstance(error, ValueError), error.args[1])  # Output: True ['a', 'c', 'b', 'a']

The node clean_temp appears first although it was never declared as a key, and package appears last because add attached it after link. A cycle makes any order impossible, so the sorter raises CycleError, a subclass of ValueError whose second argument lists one cycle with its first node repeated at the end. The same requirement, every class before its bases, governs the method resolution order examined in the article devoted to C3 linearization, which adds rules of its own about the order of the bases.

Releasing Tasks as Their Dependencies Finish

A static order executes tasks one after another, even when several of them are independent. The incremental interface exposes that independence: after prepare, which freezes the graph and checks it for cycles, get_ready returns every node whose predecessors are all finished, done marks nodes as finished, and is_active reports whether work remains. The following example runs the build with a thread pool, in the spirit of the worker-queue example of the official documentation, and each task waits a tenth of a second.

import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from graphlib import TopologicalSorter

build = {
    "link": ["compile_code", "compile_resources"],
    "compile_code": ["clean_temp"],
    "compile_resources": ["clean_temp"],
}


def run(task):
    time.sleep(0.1)
    return task


sorter = TopologicalSorter(build)
sorter.prepare()
finished = []
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as pool:
    running = {}
    while sorter.is_active():
        for task in sorter.get_ready():
            running[pool.submit(run, task)] = task
        completed, _ = wait(running, return_when=FIRST_COMPLETED)
        for future in completed:
            finished.append(running.pop(future))
            sorter.done(finished[-1])
elapsed = time.perf_counter() - start
print(finished[0], finished[-1])  # Output: clean_temp link
print(elapsed < 0.35)             # Output: True

The two compilation tasks became ready together and ran in parallel, so four tasks of a tenth of a second finished in about three tenths instead of four. The loop hands each task to a worker as soon as its last predecessor finishes, without waiting for a whole level of the graph. Coordinating workers through queues and futures is examined in the article devoted to thread synchronization, and the choice between threads, processes and asyncio for the tasks themselves in the article devoted to concurrency models.

Pitfalls of graphlib

The sorter guarantees only that predecessors come first, so its pitfalls come from expecting more than that guarantee or from describing the graph incorrectly. Six pitfalls are distinguished, which are the following:

  1. Inverted edges. The values of the dictionary are predecessors; writing the dependents instead produces a valid but reversed order without any error.
  2. Unstable order. Nodes that are ready together have no defined order, and when predecessors are given as sets of strings the order changes between runs because of hash randomization.
  3. Misspelt names. A predecessor written incorrectly becomes a new independent node, so the real dependency is silently lost.
  4. Mixing interfaces. static_order must not be combined with prepare, get_ready and done on the same sorter.
  5. Protocol errors. add after prepare, or done for a node not yet returned by get_ready, raises ValueError; before Python 3.14, calling prepare twice did as well.
  6. Unhandled cycles. CycleError reports one cycle only, so a graph with several cycles needs repeated corrections.

The second and third pitfalls are reproduced in the following example, which runs the same ordering under different hash seeds.

import os
import subprocess
import sys
from graphlib import TopologicalSorter

code = (
    "from graphlib import TopologicalSorter\n"
    "print(*TopologicalSorter({'app': {'db', 'cache', 'queue', 'auth'}}).static_order())"
)
orders = set()
for seed in range(6):
    result = subprocess.run(
        [sys.executable, "-c", code],
        env={**os.environ, "PYTHONHASHSEED": str(seed)},
        capture_output=True, text=True,
    )
    orders.add(result.stdout.strip())
print(len(orders) > 1)  # Output: True

typo = TopologicalSorter({"link": ["compile_cod"], "compile_code": ["clean_temp"]})
print(list(typo.static_order()))
# Output: ['compile_cod', 'clean_temp', 'link', 'compile_code']

The same graph produced several different orders across six interpreter runs, all of them valid, which is harmless for correctness but breaks reproducible logs and tests; giving predecessors as lists, or sorting each group returned by get_ready, removes the variation. The misspelt compile_cod made link independent of the real compilation, and nothing reported the mistake.

Choosing How to Order Dependent Tasks

Consequently, graphlib suits any set of tasks whose dependencies form a directed acyclic graph, as the following table summarizes.

Situation Recommended approach
One valid order for a dependency graph TopologicalSorter(graph).static_order()
Running independent tasks in parallel prepare, get_ready and done with a pool of workers
Reproducible order between runs Lists of predecessors, or sorting each ready group
Validating declared names Checking every predecessor against the known nodes before sorting
Detecting dependency cycles Catching CycleError and reporting args[1]
Weighted graphs or shortest paths A dedicated graph library
Ordering class hierarchies The interpreter's own MRO

Conclusion

It is concluded that TopologicalSorter orders a graph described by predecessors, that its incremental interface releases each task as soon as its dependencies finish, and that cycles are reported through CycleError with the offending path. This magic guarantees only the dependency order: ready nodes have no fixed order, misspelt names create independent nodes, and the direction of the edges is never checked. Keeping a value that is private to each asynchronous task or thread, without passing it through every function call, is the purpose of the module contextvars, which is developed in a future article of this series.