Every graph so far had no cycle. Add one, and run your order_from_config on it.
A cycle stops Kahn's loop early, and the tasks on it never reach 0
# compile now needs test toobroken = needs + [("compile", "test")]config = {task: [p for t, p in broken if t == task] for task in tasks}order = order_from_config(config)print(order)print(len(order), "of", len(tasks), "tasks")
Predict
One pair is added: compile now needs test too. How many tasks make it into Kahn's order?
Pick one to see what it prints.
One wrong pair, ("compile", "test"), means compile needs test while test still needs compile. Kahn's loop doesn't crash or run forever. It stops early. Step through it:
Kahn's algorithm on the broken pipelineInteractive
on the queue just popped done stuck
queue, popleft takes the left end:empty
order:fetchdocsassets
Pop assets: package drops to 1. The queue is empty with 3 of 7 tasks in the order. compile, test, package and deploy never reach 0.
Neither compile nor test can reach 0: each needs the other to finish first. package and deploy aren't on the cycle, but they wait on tasks that are, so they're stuck behind it.
A cycle makes the order short. The other direction holds too: if the order comes out short, there's a cycle. Every leftover task has a count above 0. So one of its prerequisites never finished, and that prerequisite is left over too. Start at any leftover task, and keep stepping to a leftover prerequisite:
From a leftover task, keep stepping to a leftover prerequisite
each arrow: needs
deploy
→
test
→
compile
→
testagain
Sooner or later a task repeats, and the steps since then form a cycle.
That gives you the test: there's a cycle exactly when len(order) < len(tasks). It's the graphlib rule from the top of the lesson, seen from inside the loop.
The stuck tasks are the ones whose count is still above 0 after the loop
stuck = sorted(task for task in tasks if waiting[task] > 0)# ['compile', 'deploy', 'package', 'test']
Keep waiting after Kahn's loop, and that one line names the stuck tasks. On the broken pipeline it gives the four red tasks in the figure. A count still above 0 at the end is exactly what stuck means.
A task that needs itself, ("lint", "lint"), is a cycle of one.
Pick an answer above to see the rest
Predict
Kahn's runs on the tasks lint and format, with the one pair ("lint", "lint"). What does it return?
A task that needs itself
Kahn's handles it with no special case. Code that drops such pairs as typos reports lint as runnable.
The editor holds the broken pipeline and the three tasks that Kahn's ran. Write blocked_by, which pairs each leftover task with a leftover prerequisite.
Pick an answer above to see the rest
Instructions
1
Write blocked_by(tasks, needs, order): a dict from each task missing from order to its first prerequisite, in the order of needs, that is also missing.