Representing a Graph With Dicts
Concepts covered: Collections
A nightly pipeline is a set of tasks plus a set of rules of the form "this task waits for that one". That structure is a directed graph: each task is a node and each rule is an edge. Python holds one with no graph library at all. A dict mapping every task to the list of tasks it depends on stores the whole graph, and deps["join"] answers "what must finish before join?" in a single lookup.
deps = {
"bookings": [],
"listings": [],
"clean": ["bookings"],
"join": ["clean", "listings"],
"pricing": ["join"],
"report": ["join", "pricing"],
}- bookings (transform, nightly scheduler)
- listings (transform, nightly scheduler)
- clean (transform, nightly scheduler)
- join (transform, nightly scheduler)
- pricing (transform, nightly scheduler)
- report (transform, nightly scheduler)
- bookings -> clean
- clean -> join
- listings -> join
- join -> pricing
- join -> report
- pricing -> report
Exactly 2 tasks have empty lists. They are the sources: nothing sits upstream of them, so they can start the moment the run begins. Every other task waits until each name in its list has finished.
Flipping the edges to find downstream impact
deps answers upstream questions. The on-call question runs the other way: if listings fails tonight, which tasks will never get fresh data? Answering it from deps means scanning every list for the name listings. Building a reversed dict once, mapping each task to the tasks that wait on it, turns each step of the search into one lookup. A breadth-first walk with a deque and a broken set then collects everything reachable.
from collections import deque
deps = {
"bookings": [],
"listings": [],
"clean": ["bookings"],
"join": ["clean", "listings"],
"pricing": ["join"],
"report": ["join", "pricing"],
}
downstream = {task: [] for task in deps}
for task, parents in deps.items():
for parent in parents:
downstream[parent].append(task)
print(downstream["join"])
broken = {"listings"}
queue = deque(["listings"])
while queue:
task = queue.popleft()
for child in downstream[task]:
if child not in broken:
broken.add(child)
queue.append(child)
print(sorted(broken))Output:
['pricing', 'report'] ['join', 'listings', 'pricing', 'report']
The broken set does 2 jobs. It holds the answer, and it stops the walk from processing report twice, since report is reachable through both join and pricing. On a graph with a shared upstream table and hundreds of tasks, that check is what keeps the walk from revisiting the same subtree again and again.
Ordering tasks with in-degree counts
A scheduler needs an order in which every task runs after all of its dependencies, called a topological order. Kahn's algorithm finds one with 2 dicts and a queue. remaining counts how many dependencies each task still waits on; that count is the task's in-degree. Tasks at 0 go into the queue. Each time a task runs, every task downstream of it loses 1 from its count, and any count that reaches 0 joins the queue.
from collections import deque
deps = {
"bookings": [],
"listings": [],
"clean": ["bookings"],
"join": ["clean", "listings"],
"pricing": ["join"],
"report": ["join", "pricing"],
}
remaining = {task: len(parents) for task, parents in deps.items()}
downstream = {task: [] for task in deps}
for task, parents in deps.items():
for parent in parents:
downstream[parent].append(task)
queue = deque(t for t in deps if remaining[t] == 0)
order = []
while queue:
task = queue.popleft()
order.append(task)
print("run", task)
for child in downstream[task]:
remaining[child] -= 1
if remaining[child] == 0:
queue.append(child)
print(order)run bookings run listings run clean run join run pricing run report ['bookings', 'listings', 'clean', 'join', 'pricing', 'report']
Watch remaining["join"] during the run: it starts at 2 and the task enters the queue only after both clean and listings have run. The printed order is one valid schedule among several. Swapping bookings and listings at the front would satisfy every rule too, which is why 2 schedulers can disagree on order and both be correct.
Batches that can run in parallel
Kahn's queue hands out one task at a time, but a scheduler with spare workers can do better. Process the ready tasks as a wave: every task whose count reaches 0 during a wave goes into the next one. Tasks in the same wave share no path between them, so they can run at the same time, and the number of waves is the shortest possible run length when each task takes one step.
deps = {
"bookings": [],
"listings": [],
"clean": ["bookings"],
"join": ["clean", "listings"],
"pricing": ["join"],
"report": ["join", "pricing"],
}
remaining = {task: len(parents) for task, parents in deps.items()}
downstream = {task: [] for task in deps}
for task, parents in deps.items():
for parent in parents:
downstream[parent].append(task)
wave = [t for t in deps if remaining[t] == 0]
while wave:
print(wave)
next_wave = []
for task in wave:
for child in downstream[task]:
remaining[child] -= 1
if remaining[child] == 0:
next_wave.append(child)
wave = next_waveOutput:
['bookings', 'listings'] ['clean'] ['join'] ['pricing'] ['report']
Only the first wave holds 2 tasks. The chain bookings, clean, join, pricing, report is the critical path, and adding workers can't shorten the run below 5 waves: speeding up the run means splitting or shortening a task on that chain.
A cycle shows up as tasks left behind
If a task depends on itself through any chain of edges, no task on that loop ever reaches a count of 0. Kahn's algorithm then runs out of ready tasks and stops early, with no error. Comparing the length of the order with the number of tasks detects the cycle, and the tasks missing from the order are the ones stuck on the loop or behind it.
from collections import deque
def topo_order(deps):
remaining = {task: len(parents) for task, parents in deps.items()}
downstream = {task: [] for task in deps}
for task, parents in deps.items():
for parent in parents:
downstream[parent].append(task)
queue = deque(t for t in deps if remaining[t] == 0)
order = []
while queue:
task = queue.popleft()
order.append(task)
for child in downstream[task]:
remaining[child] -= 1
if remaining[child] == 0:
queue.append(child)
return order
deps = {
"bookings": [],
"listings": [],
"clean": ["bookings", "report"],
"join": ["clean", "listings"],
"report": ["join"],
}
order = topo_order(deps)
done = set(order)
print(order)
print("stuck:", [t for t in deps if t not in done])Output:
['bookings', 'listings'] stuck: ['clean', 'join', 'report']
Here clean was rewired to wait on report, which waits on join, which waits on clean. Both sources run, each lowers a count from 2 to 1, and the queue empties with 3 tasks unreached. Run this check before the first task starts: a cycle discovered halfway through a run leaves some tables rebuilt and others stale.
A teammate adds 2 tasks to a new pipeline file and builds the reversed dict. What does this program print?
deps = {
"clean": ["bookings"],
"join": ["clean", "fx_rates"],
}
downstream = {task: [] for task in deps}
for task, parents in deps.items():
for parent in parents:
downstream[parent].append(task)
print(downstream)- {'clean': ['join'], 'join': []}, with the unknown parents skipped
- KeyError: 'bookings', raised while the loop handles the clean task
- KeyError: 'fx_rates', raised while the loop handles the join task
- {'clean': ['join'], 'join': [], 'bookings': ['clean'], 'fx_rates': ['join']}
About this lesson
This section is part of the Data Structures: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.