19/28
Part 4 of 6 · Tasks that wait on othersLearn and do

Every dependency must already exist, so there's never a cycle

What should enqueue("index", depends_on=["parse", "thumb"]) do if thumb was never enqueued? You could wait for thumb to show up. But then a typo in an id makes index wait forever, with no error.

The practice problem raises ValueError instead. Every dependency must already be in the queue.

That rule has a bonus. A task can only depend on tasks enqueued before it. So the dependencies all point back in time, and a cycle, where a waits on b and b waits on a, can't happen. You never need cycle detection. Say that in the interview: it's the kind of reasoning that shows you see the whole design.

The other half of the rule is easy to get wrong: a call that raises must store nothing. Check every argument first, then change the state. If the code stores the task and then finds the bad dependency, half a task stays behind. Its id is in status, so a corrected retry of the same enqueue raises "already enqueued".

The order inside enqueue:

  1. Raise if the id was seen before.
  2. Raise if any dependency is unknown.
  3. If a dependency is already dead, the new task is dead at once, since it can never run.
  4. Otherwise store it as waiting, count its open dependencies, and register it with each one.

Step 3 is the practice problem's last rule, and it follows from the cascade: a task that joins after its dependency died would have died with it.

In the editor, WorkQueue has an enqueue that stores a task and its open dependencies. Write the checks at its top, so a bad call raises ValueError before anything is stored.