Skip to content

< all problems95 · Level 08, Production

Run Agent Workers Off a Work Queue

medium · implement · Production

Tasks arrive faster than one agent can run them, so you run several replicas and let each pull from a queue. Implement run_pool(tasks, workers, handle), a simulation of that pool, exact to the tick.

tasks is a list of {"id": ..., "duration": ticks} in arrival order. workers is the replica count. handle(task) is called when a task starts and returns its result, or raises when the run fails.

  1. Time starts at 0. A free worker takes the task at the head of the queue and holds it for duration ticks. When several workers are free, the lowest index goes first.
  2. A task that raises is put back at the back of the queue, available from the tick its failed run ended, for one more try. A second failure sends its id to dead. A failed run still occupies the worker for the full duration.
  3. A requeued task may be available later than a worker is free; its start is the later of the two.
  4. Return {"schedule": [(id, worker, start, end), ...], "results": {id: result}, "dead": [ids], "makespan": last end}. The schedule is in start order, ties by worker index. An empty list of tasks has makespan 0.

This is a Deployment with N replicas on a queue, and the two things people get wrong in real ones are both in here: a task run twice because the failed attempt was not accounted for, and a task lost because it was.