7/32
Part 2 of 7 · Kahn's algorithmLearn and do

Sorting by the count can break the order, and rescanning for a ready task is slow

Two first ideas are tempting, and neither is the answer.

Sorting by the count can put a task before what it needs

Four tasks and their counts
compilecount 0assetscount 0packagecount 2releasecount 1

Sorted by count: compile, assets, release, package. release lands before package, which it needs.

sorted(tasks, key=waiting.get) puts the tasks that need nothing first, and on the pipeline it happens to give a valid order. On these four it doesn't. A count says how many prerequisites a task has, not how long the chain behind them is.

Rescanning for a ready task works, but a chain listed backwards takes n(n + 1)/2 checks

def rescan_order(tasks, needs):
    prerequisites = defaultdict(list)
    for task, prerequisite in needs:
        prerequisites[task].append(prerequisite)
    done, order, remaining = set(), [], list(tasks)
    while remaining:
        for task in remaining:
            if all(p in done for p in prerequisites[task]):
                break
        else:
            raise ValueError("no task can run")
        remaining.remove(task)
        done.add(task)
        order.append(task)
    return order

This finds any task whose prerequisites have all run, places it, and looks again. The else belongs to the for: it runs only when the loop ends without a break, here when no task is ready. It's correct. It's also slow, because it forgets everything between passes. Its worst case is a chain listed backwards:

Rescanning the chain t0 → t1 → t2 → t3, listed t3, t2, t1, t0
pass 1: 4 checks
t3t2t1t0
pass 2: 3 checks
t3t2t1
pass 3: 2 checks
t3t2
pass 4: 1 check
t3
checked, not readyready, placedplaced already

10 checks in all, to place 4 tasks.

Every pass walks to the end of what's left to find the one ready task. For nn tasks that's n(n+1)/2n(n+1)/2 checks, nn times n+1n + 1 over 2. It came to 500,500 checks for 1,000 tasks, and 32,004,000 for 8,000.

The editor holds the pipeline and an empty ready_now. Write it to return the tasks the rescan could place next, given the set of tasks already done.